Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2764 lines
74 KiB

  1. //========= Copyright � 1996-2005, Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //=============================================================================//
  7. // Author: Michael S. Booth ([email protected]), 2003
  8. #pragma warning( disable : 4530 ) // STL uses exceptions, but we are not compiling with them - ignore warning
  9. #include "cbase.h"
  10. #include "cs_bot.h"
  11. #include "nav_area.h"
  12. #include "cs_gamerules.h"
  13. #include "shared_util.h"
  14. #include "keyvalues.h"
  15. #include "tier0/icommandline.h"
  16. #include "fmtstr.h"
  17. // memdbgon must be the last include file in a .cpp file!!!
  18. #include "tier0/memdbgon.h"
  19. #ifdef _WIN32
  20. #pragma warning (disable:4701) // disable warning that variable *may* not be initialized
  21. #endif
  22. CBotManager *TheBots = NULL;
  23. bool CCSBotManager::m_isMapDataLoaded = false;
  24. int g_nClientPutInServerOverrides = 0;
  25. void DrawOccupyTime( void );
  26. ConVar bot_show_occupy_time( "bot_show_occupy_time", "0", FCVAR_GAMEDLL | FCVAR_CHEAT, "Show when each nav area can first be reached by each team." );
  27. void DrawBattlefront( void );
  28. ConVar bot_show_battlefront( "bot_show_battlefront", "0", FCVAR_GAMEDLL | FCVAR_CHEAT, "Show areas where rushing players will initially meet." );
  29. int UTIL_CSSBotsInGame( void );
  30. ConVar bot_join_delay( "bot_join_delay", "0", FCVAR_GAMEDLL, "Prevents bots from joining the server for this many seconds after a map change." );
  31. ConVar bot_join_in_warmup( "bot_join_in_warmup", "1", FCVAR_GAMEDLL, "Prevents bots from joining the server while warmup phase is active." );
  32. ConVar throttle_expensive_ai( "throttle_expensive_ai", IsGameConsole() ? "1" : "0" );
  33. extern ConVar mp_guardian_target_site;
  34. /**
  35. * Determine whether bots can be used or not
  36. */
  37. inline bool AreBotsAllowed()
  38. {
  39. // If they pass in -nobots, don't allow bots. This is for people who host servers, to
  40. // allow them to disallow bots to enforce CPU limits.
  41. const char *nobots = CommandLine()->CheckParm( "-nobots" );
  42. if ( nobots )
  43. {
  44. return false;
  45. }
  46. return true;
  47. }
  48. //--------------------------------------------------------------------------------------------------------------
  49. void InstallBotControl( void )
  50. {
  51. if ( TheBots != NULL )
  52. delete TheBots;
  53. TheBots = new CCSBotManager;
  54. }
  55. //--------------------------------------------------------------------------------------------------------------
  56. void RemoveBotControl( void )
  57. {
  58. if ( TheBots != NULL )
  59. delete TheBots;
  60. TheBots = NULL;
  61. }
  62. //--------------------------------------------------------------------------------------------------------------
  63. CBasePlayer* ClientPutInServerOverride_Bot( edict_t *pEdict, const char *playername )
  64. {
  65. CBasePlayer *pPlayer = TheBots->AllocateAndBindBotEntity( pEdict );
  66. if ( pPlayer )
  67. {
  68. pPlayer->SetPlayerName( playername );
  69. }
  70. ++g_nClientPutInServerOverrides;
  71. return pPlayer;
  72. }
  73. //--------------------------------------------------------------------------------------------------------------
  74. // Constructor
  75. CCSBotManager::CCSBotManager()
  76. {
  77. m_zoneCount = 0;
  78. SetLooseBomb( NULL );
  79. m_serverActive = false;
  80. m_isBombPlanted = false;
  81. m_bombDefuser = NULL;
  82. m_roundStartTimestamp = 0.0f;
  83. m_eventListenersEnabled = true;
  84. m_commonEventListeners.AddToTail( &m_PlayerFootstepEvent );
  85. m_commonEventListeners.AddToTail( &m_PlayerRadioEvent );
  86. m_commonEventListeners.AddToTail( &m_PlayerFallDamageEvent );
  87. m_commonEventListeners.AddToTail( &m_BombBeepEvent );
  88. m_commonEventListeners.AddToTail( &m_DoorMovingEvent );
  89. m_commonEventListeners.AddToTail( &m_BreakPropEvent );
  90. m_commonEventListeners.AddToTail( &m_BreakBreakableEvent );
  91. m_commonEventListeners.AddToTail( &m_WeaponFireEvent );
  92. m_commonEventListeners.AddToTail( &m_WeaponFireOnEmptyEvent );
  93. m_commonEventListeners.AddToTail( &m_WeaponReloadEvent );
  94. m_commonEventListeners.AddToTail( &m_WeaponZoomEvent );
  95. m_commonEventListeners.AddToTail( &m_BulletImpactEvent );
  96. m_commonEventListeners.AddToTail( &m_GrenadeBounceEvent );
  97. m_commonEventListeners.AddToTail( &m_NavBlockedEvent );
  98. TheBotPhrases = new BotPhraseManager;
  99. TheBotProfiles = new BotProfileManager;
  100. m_nNumExpensiveOperationsThisFrame = 0;
  101. }
  102. const CCSBotManager::Zone* Helper_GetZoneForPlaceName( const char* szName )
  103. {
  104. Place pl = TheNavMesh->NameToPlace( szName );
  105. for ( int i = 0; i < TheCSBots()->GetZoneCount(); ++i )
  106. {
  107. if ( !TheCSBots()->GetZone( i ) )
  108. continue;
  109. for ( int j = 0; j < CCSBotManager::MAX_ZONE_NAV_AREAS; ++j )
  110. {
  111. if ( !TheCSBots()->GetZone( i )->m_area[ j ] )
  112. continue;
  113. if ( TheCSBots()->GetZone( i )->m_area[ j ]->GetPlace() == pl )
  114. {
  115. return TheCSBots()->GetZone( i );
  116. }
  117. }
  118. }
  119. return NULL;
  120. }
  121. //--------------------------------------------------------------------------------------------------------------
  122. /**
  123. * Invoked when a new round begins
  124. */
  125. void CCSBotManager::RestartRound( void )
  126. {
  127. // extend
  128. CBotManager::RestartRound();
  129. SetLooseBomb( NULL );
  130. m_isBombPlanted = false;
  131. if ( CSGameRules()->IsPlayingGunGameTRBomb() )
  132. {
  133. // push to plant the bomb quickly in this game mode
  134. m_earliestBombPlantTimestamp = gpGlobals->curtime + RandomFloat( 0.0f, 10.0f );
  135. }
  136. else
  137. {
  138. m_earliestBombPlantTimestamp = gpGlobals->curtime + RandomFloat( 10.0f, 30.0f ); // 60
  139. }
  140. m_bombDefuser = NULL;
  141. ResetRadioMessageTimestamps();
  142. m_lastSeenEnemyTimestamp = -9999.9f;
  143. m_roundStartTimestamp = gpGlobals->curtime + mp_freezetime.GetFloat();
  144. // randomly decide if defensive team wants to "rush" as a whole
  145. const float defenseRushChance = 33.3f; // 25.0f;
  146. m_isDefenseRushing = (RandomFloat( 0.0f, 100.0f ) <= defenseRushChance) ? true : false;
  147. if ( CSGameRules()->IsPlayingCoopGuardian() && mp_guardian_target_site.GetInt() >= 0 )
  148. {
  149. m_isDefenseRushing = 0;
  150. m_earliestBombPlantTimestamp = 0;
  151. m_eTStrat = k_ETStrat_Rush;
  152. m_iTerroristTargetSite = mp_guardian_target_site.GetInt();
  153. /*
  154. // Choose random strat if there are no humans on team
  155. if ( UTIL_HumansOnTeam( TEAM_TERRORIST ) == 0 )
  156. {
  157. m_eTStrat = k_ETStrat_Rush;
  158. m_iTerroristTargetSite = RandomInt( 0, 1 );
  159. }
  160. if ( UTIL_HumansOnTeam( TEAM_CT ) == 0 )
  161. {
  162. m_eCTStrat = k_ECTStrat_StackSite;
  163. m_iCTPrioritySite = RandomInt( 0, 1 );
  164. }
  165. */
  166. }
  167. TheBotPhrases->OnRoundRestart();
  168. m_isRoundOver = false;
  169. }
  170. //--------------------------------------------------------------------------------------------------------------
  171. void UTIL_DrawBox( Extent *extent, int lifetime, int red, int green, int blue )
  172. {
  173. int darkRed = red/2;
  174. int darkGreen = green/2;
  175. int darkBlue = blue/2;
  176. Vector v[8];
  177. v[0].x = extent->lo.x; v[0].y = extent->lo.y; v[0].z = extent->lo.z;
  178. v[1].x = extent->hi.x; v[1].y = extent->lo.y; v[1].z = extent->lo.z;
  179. v[2].x = extent->hi.x; v[2].y = extent->hi.y; v[2].z = extent->lo.z;
  180. v[3].x = extent->lo.x; v[3].y = extent->hi.y; v[3].z = extent->lo.z;
  181. v[4].x = extent->lo.x; v[4].y = extent->lo.y; v[4].z = extent->hi.z;
  182. v[5].x = extent->hi.x; v[5].y = extent->lo.y; v[5].z = extent->hi.z;
  183. v[6].x = extent->hi.x; v[6].y = extent->hi.y; v[6].z = extent->hi.z;
  184. v[7].x = extent->lo.x; v[7].y = extent->hi.y; v[7].z = extent->hi.z;
  185. static int edge[] =
  186. {
  187. 1, 2, 3, 4, -1,
  188. 5, 6, 7, 8, -5,
  189. 1, -5,
  190. 2, -6,
  191. 3, -7,
  192. 4, -8,
  193. 0
  194. };
  195. Vector from, to;
  196. bool restart = true;
  197. for( int i=0; edge[i] != 0; ++i )
  198. {
  199. if (restart)
  200. {
  201. to = v[ edge[i]-1 ];
  202. restart = false;
  203. continue;
  204. }
  205. from = to;
  206. int index = edge[i];
  207. if (index < 0)
  208. {
  209. restart = true;
  210. index = -index;
  211. }
  212. to = v[ index-1 ];
  213. NDebugOverlay::Line( from, to, darkRed, darkGreen, darkBlue, true, 0.1f );
  214. NDebugOverlay::Line( from, to, red, green, blue, false, 0.15f );
  215. }
  216. }
  217. //--------------------------------------------------------------------------------------------------------------
  218. void CCSBotManager::EnableEventListeners( bool enable )
  219. {
  220. if ( m_eventListenersEnabled == enable )
  221. {
  222. return;
  223. }
  224. m_eventListenersEnabled = enable;
  225. // enable/disable the most frequent event listeners, to improve performance when no bots are present.
  226. for ( int i=0; i<m_commonEventListeners.Count(); ++i )
  227. {
  228. if ( enable )
  229. {
  230. gameeventmanager->AddListener( m_commonEventListeners[i], m_commonEventListeners[i]->GetEventName(), true );
  231. }
  232. else
  233. {
  234. gameeventmanager->RemoveListener( m_commonEventListeners[i] );
  235. }
  236. }
  237. }
  238. //--------------------------------------------------------------------------------------------------------------
  239. /**
  240. * Called each frame
  241. */
  242. void CCSBotManager::StartFrame( void )
  243. {
  244. m_nNumExpensiveOperationsThisFrame = 0;
  245. if ( engine->IsPaused() )
  246. return;
  247. if ( !AreBotsAllowed() )
  248. {
  249. EnableEventListeners( false );
  250. return;
  251. }
  252. // EXTEND
  253. CBotManager::StartFrame();
  254. if ( !CSGameRules()->IsSwitchingTeamsAtRoundReset() )
  255. {
  256. // Maintain the bot quota only if the game is not currently switching teams at halftime
  257. MaintainBotQuota();
  258. }
  259. EnableEventListeners( UTIL_CSSBotsInGame() > 0 );
  260. // debug zone extent visualization
  261. if (cv_bot_debug.GetInt() == 5)
  262. {
  263. for( int z=0; z<m_zoneCount; ++z )
  264. {
  265. Zone *zone = &m_zone[z];
  266. if ( zone->m_isBlocked )
  267. {
  268. UTIL_DrawBox( &zone->m_extent, 1, 255, 0, 200 );
  269. }
  270. else
  271. {
  272. UTIL_DrawBox( &zone->m_extent, 1, 255, 100, 0 );
  273. }
  274. }
  275. }
  276. if (bot_show_occupy_time.GetBool())
  277. {
  278. DrawOccupyTime();
  279. }
  280. if (bot_show_battlefront.GetBool())
  281. {
  282. DrawBattlefront();
  283. }
  284. if ( m_checkTransientAreasTimer.IsElapsed() && !nav_edit.GetBool() )
  285. {
  286. CUtlVector< CNavArea * >& transientAreas = TheNavMesh->GetTransientAreas();
  287. for ( int i=0; i<transientAreas.Count(); ++i )
  288. {
  289. CNavArea *area = transientAreas[i];
  290. if ( area->GetAttributes() & NAV_MESH_TRANSIENT )
  291. {
  292. area->UpdateBlocked();
  293. }
  294. }
  295. m_checkTransientAreasTimer.Start( 2.0f );
  296. }
  297. }
  298. //--------------------------------------------------------------------------------------------------------------
  299. /**
  300. * Return true if the bot can use this weapon
  301. */
  302. bool CCSBotManager::IsWeaponUseable( const CWeaponCSBase *weapon ) const
  303. {
  304. if (weapon == NULL)
  305. return false;
  306. if (weapon->IsA( WEAPON_C4 ))
  307. return true;
  308. if ((!AllowShotguns() && weapon->IsKindOf( WEAPONTYPE_SHOTGUN )) ||
  309. (!AllowMachineGuns() && weapon->IsKindOf( WEAPONTYPE_MACHINEGUN )) ||
  310. (!AllowRifles() && weapon->IsKindOf( WEAPONTYPE_RIFLE )) ||
  311. (!AllowShotguns() && weapon->IsKindOf( WEAPONTYPE_SHOTGUN )) ||
  312. (!AllowSnipers() && weapon->IsKindOf( WEAPONTYPE_SNIPER_RIFLE )) ||
  313. (!AllowSubMachineGuns() && weapon->IsKindOf( WEAPONTYPE_SUBMACHINEGUN )) ||
  314. (!AllowPistols() && weapon->IsKindOf( WEAPONTYPE_PISTOL )) ||
  315. (!AllowGrenades() && weapon->IsKindOf( WEAPONTYPE_GRENADE )))
  316. {
  317. return false;
  318. }
  319. return true;
  320. }
  321. //--------------------------------------------------------------------------------------------------------------
  322. /**
  323. * Return true if this player is on "defense"
  324. */
  325. bool CCSBotManager::IsOnDefense( const CCSPlayer *player ) const
  326. {
  327. switch (GetScenario())
  328. {
  329. case SCENARIO_DEFUSE_BOMB:
  330. return (player->GetTeamNumber() == TEAM_CT);
  331. case SCENARIO_RESCUE_HOSTAGES:
  332. return (player->GetTeamNumber() == TEAM_TERRORIST);
  333. case SCENARIO_ESCORT_VIP:
  334. return (player->GetTeamNumber() == TEAM_TERRORIST);
  335. }
  336. return false;
  337. }
  338. //--------------------------------------------------------------------------------------------------------------
  339. /**
  340. * Return true if this player is on "offense"
  341. */
  342. bool CCSBotManager::IsOnOffense( const CCSPlayer *player ) const
  343. {
  344. return !IsOnDefense( player );
  345. }
  346. //--------------------------------------------------------------------------------------------------------------
  347. /**
  348. * Invoked when a map has just been loaded
  349. */
  350. void CCSBotManager::ServerActivate( void )
  351. {
  352. m_isMapDataLoaded = false;
  353. // load the database of bot radio chatter
  354. TheBotPhrases->Reset();
  355. TheBotPhrases->Initialize( "BotChatter.db", 0 );
  356. TheBotProfiles->Reset();
  357. TheBotProfiles->FindVoiceBankIndex( "BotChatter.db" ); // make sure default voice bank is first
  358. const char *filename;
  359. if ( false ) // g_engfuncs.pfnIsCareerMatch() )
  360. {
  361. filename = "MissionPacks/BotPackList.db";
  362. }
  363. else
  364. {
  365. filename = "BotPackList.db";
  366. }
  367. // read in the list of bot profile DBs
  368. FileHandle_t file = filesystem->Open( filename, "r" );
  369. if ( !file )
  370. {
  371. if ( CSGameRules()->IsPlayingCoopMission() )
  372. TheBotProfiles->Init( "BotProfileCoop.db" );
  373. else
  374. TheBotProfiles->Init( "BotProfile.db" );
  375. }
  376. else
  377. {
  378. int dataLength = filesystem->Size( filename );
  379. if ( dataLength > 0 )
  380. {
  381. char *dataPointer = new char[ dataLength + 1 ];
  382. int nDataReadSize = filesystem->Read( dataPointer, dataLength, file );
  383. if ( nDataReadSize > 0 )
  384. {
  385. dataPointer[nDataReadSize] = '\0';
  386. const char *dataFile = SharedParse( dataPointer );
  387. const char *token;
  388. while ( dataFile )
  389. {
  390. token = SharedGetToken();
  391. char *clone = CloneString( token );
  392. TheBotProfiles->Init( clone );
  393. delete[] clone;
  394. dataFile = SharedParse( dataFile );
  395. }
  396. delete [] dataPointer;
  397. }
  398. }
  399. filesystem->Close( file );
  400. }
  401. // Now that we've parsed all the profiles, we have a list of the voice banks they're using.
  402. // Go back and parse the custom voice speakables.
  403. const BotProfileManager::VoiceBankList *voiceBanks = TheBotProfiles->GetVoiceBanks();
  404. for ( int i=1; i<voiceBanks->Count(); ++i )
  405. {
  406. TheBotPhrases->Initialize( (*voiceBanks)[i], i );
  407. }
  408. // tell the Navigation Mesh system what CS spawn points are named
  409. if ( CSGameRules()->IsPlayingCoopMission() )
  410. {
  411. TheNavMesh->SetPlayerSpawnName( "info_enemy_terrorist_spawn" );
  412. }
  413. else
  414. {
  415. TheNavMesh->SetPlayerSpawnName( "info_player_terrorist" );
  416. }
  417. ExtractScenarioData();
  418. RestartRound();
  419. TheBotPhrases->OnMapChange();
  420. m_serverActive = true;
  421. }
  422. void CCSBotManager::ServerDeactivate( void )
  423. {
  424. m_serverActive = false;
  425. }
  426. void CCSBotManager::ClientDisconnect( CBaseEntity *entity )
  427. {
  428. /*
  429. if ( FBitSet( entity->GetFlags(), FL_FAKECLIENT ) )
  430. {
  431. FREE_PRIVATE( entity );
  432. }
  433. */
  434. /*
  435. // make sure voice feedback is turned off
  436. CBasePlayer *pPlayer = (CBasePlayer *)CBaseEntity::Instance( pEntity );
  437. if ( pPlayer && pPlayer->IsBot() )
  438. {
  439. CCSBot *pBot = static_cast<CCSBot *>(pPlayer);
  440. if (pBot)
  441. {
  442. pBot->EndVoiceFeedback( true );
  443. }
  444. }
  445. */
  446. }
  447. //--------------------------------------------------------------------------------------------------------------
  448. /**
  449. * Parses out bot name/template/etc params from the current ConCommand
  450. */
  451. void BotArgumentsFromArgv( const CCommand &args, const char **name, CSWeaponType *weaponType, BotDifficultyType *difficulty, int *team = NULL, bool *all = NULL )
  452. {
  453. static char s_name[MAX_PLAYER_NAME_LENGTH];
  454. s_name[0] = 0;
  455. *name = s_name;
  456. *difficulty = NUM_DIFFICULTY_LEVELS;
  457. if ( team )
  458. {
  459. *team = TEAM_UNASSIGNED;
  460. }
  461. if ( all )
  462. {
  463. *all = false;
  464. }
  465. *weaponType = WEAPONTYPE_UNKNOWN;
  466. for ( int arg=1; arg<args.ArgC(); ++arg )
  467. {
  468. bool found = false;
  469. const char *token = args[arg];
  470. if ( all && FStrEq( token, "all" ) )
  471. {
  472. *all = true;
  473. found = true;
  474. }
  475. else if ( team && FStrEq( token, "t" ) )
  476. {
  477. *team = TEAM_TERRORIST;
  478. found = true;
  479. }
  480. else if ( team && FStrEq( token, "ct" ) )
  481. {
  482. *team = TEAM_CT;
  483. found = true;
  484. }
  485. for( int i=0; i<NUM_DIFFICULTY_LEVELS && !found; ++i )
  486. {
  487. if (!stricmp( BotDifficultyName[i], token ))
  488. {
  489. *difficulty = (BotDifficultyType)i;
  490. found = true;
  491. }
  492. }
  493. if ( !found )
  494. {
  495. *weaponType = WeaponClassFromString( token );
  496. if ( *weaponType != WEAPONTYPE_UNKNOWN )
  497. {
  498. found = true;
  499. }
  500. }
  501. if ( !found )
  502. {
  503. Q_strncpy( s_name, token, sizeof( s_name ) );
  504. }
  505. }
  506. }
  507. //--------------------------------------------------------------------------------------------------------------
  508. CON_COMMAND_F( bot_place, "bot_place - Places a bot from the map at where the local player is pointing.", FCVAR_GAMEDLL | FCVAR_CHEAT )
  509. {
  510. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  511. return;
  512. uint nTeamMask = 0;
  513. for ( int i = 1; i < args.ArgC(); ++i )
  514. {
  515. if ( !V_strcmp( args.Arg( i ), "t" ) )
  516. nTeamMask |= 1 << TEAM_TERRORIST;
  517. else if ( !V_strcmp( args.Arg( i ), "ct" ) )
  518. nTeamMask |= 1 << TEAM_CT;
  519. }
  520. if ( !nTeamMask )
  521. nTeamMask = 0xFFFFFFFF;
  522. TheCSBots()->BotPlaceCommand(nTeamMask);
  523. }
  524. //--------------------------------------------------------------------------------------------------------------
  525. CON_COMMAND_F( bot_add, "bot_add <t|ct> <type> <difficulty> <name> - Adds a bot matching the given criteria.", FCVAR_GAMEDLL )
  526. {
  527. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  528. return;
  529. const char *name;
  530. BotDifficultyType difficulty;
  531. CSWeaponType weaponType;
  532. int team;
  533. BotArgumentsFromArgv( args, &name, &weaponType, &difficulty, &team );
  534. TheCSBots()->BotAddCommand( team, FROM_CONSOLE, name, weaponType, difficulty );
  535. }
  536. //--------------------------------------------------------------------------------------------------------------
  537. CON_COMMAND_F( bot_add_t, "bot_add_t <type> <difficulty> <name> - Adds a terrorist bot matching the given criteria.", FCVAR_GAMEDLL )
  538. {
  539. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  540. return;
  541. const char *name;
  542. BotDifficultyType difficulty;
  543. CSWeaponType weaponType;
  544. BotArgumentsFromArgv( args, &name, &weaponType, &difficulty );
  545. TheCSBots()->BotAddCommand( TEAM_TERRORIST, FROM_CONSOLE, name, weaponType, difficulty );
  546. }
  547. //--------------------------------------------------------------------------------------------------------------
  548. CON_COMMAND_F( bot_add_ct, "bot_add_ct <type> <difficulty> <name> - Adds a Counter-Terrorist bot matching the given criteria.", FCVAR_GAMEDLL )
  549. {
  550. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  551. return;
  552. const char *name;
  553. BotDifficultyType difficulty;
  554. CSWeaponType weaponType;
  555. BotArgumentsFromArgv( args, &name, &weaponType, &difficulty );
  556. TheCSBots()->BotAddCommand( TEAM_CT, FROM_CONSOLE, name, weaponType, difficulty );
  557. }
  558. //--------------------------------------------------------------------------------------------------------------
  559. /**
  560. * Collects all bots matching the given criteria (player name, profile template name, difficulty, and team)
  561. */
  562. class CollectBots
  563. {
  564. public:
  565. CollectBots( const char *name, CSWeaponType weaponType, BotDifficultyType difficulty, int team )
  566. {
  567. m_name = name;
  568. m_difficulty = difficulty;
  569. m_team = team;
  570. m_weaponType = weaponType;
  571. }
  572. bool operator() ( CBasePlayer *player )
  573. {
  574. if ( !player->IsBot() )
  575. {
  576. return true;
  577. }
  578. CCSBot *bot = dynamic_cast< CCSBot * >(player);
  579. if ( !bot || !bot->GetProfile() )
  580. {
  581. return true;
  582. }
  583. if ( m_name && *m_name )
  584. {
  585. // accept based on name
  586. if ( FStrEq( m_name, bot->GetProfile()->GetName() ) )
  587. {
  588. m_bots.RemoveAll();
  589. m_bots.AddToTail( bot );
  590. return false;
  591. }
  592. // Reject based on profile template name
  593. if ( !bot->GetProfile()->InheritsFrom( m_name ) )
  594. {
  595. return true;
  596. }
  597. }
  598. // reject based on difficulty
  599. if ( m_difficulty != NUM_DIFFICULTY_LEVELS )
  600. {
  601. if ( !bot->GetProfile()->IsDifficulty( m_difficulty ) )
  602. {
  603. return true;
  604. }
  605. }
  606. // reject based on team
  607. if ( m_team == TEAM_CT || m_team == TEAM_TERRORIST )
  608. {
  609. if ( bot->GetTeamNumber() != m_team )
  610. {
  611. return true;
  612. }
  613. }
  614. // reject based on weapon preference
  615. if ( m_weaponType != WEAPONTYPE_UNKNOWN )
  616. {
  617. if ( !bot->GetProfile()->GetWeaponPreferenceCount() )
  618. {
  619. return true;
  620. }
  621. if ( m_weaponType != WeaponClassFromWeaponID( (CSWeaponID)bot->GetProfile()->GetWeaponPreference( 0 ) ) )
  622. {
  623. return true;
  624. }
  625. }
  626. // A match!
  627. m_bots.AddToTail( bot );
  628. return true;
  629. }
  630. CUtlVector< CCSBot * > m_bots;
  631. private:
  632. const char *m_name;
  633. CSWeaponType m_weaponType;
  634. BotDifficultyType m_difficulty;
  635. int m_team;
  636. };
  637. //--------------------------------------------------------------------------------------------------------------
  638. CON_COMMAND_F( bot_kill, "bot_kill <all> <t|ct> <type> <difficulty> <name> - Kills a specific bot, or all bots, matching the given criteria.", FCVAR_GAMEDLL | FCVAR_CHEAT )
  639. {
  640. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  641. return;
  642. const char *name;
  643. BotDifficultyType difficulty;
  644. CSWeaponType weaponType;
  645. int team;
  646. bool all;
  647. BotArgumentsFromArgv( args, &name, &weaponType, &difficulty, &team, &all );
  648. if ( (!name || !*name) && team == TEAM_UNASSIGNED && difficulty == NUM_DIFFICULTY_LEVELS )
  649. {
  650. all = true;
  651. }
  652. CollectBots collector( name, weaponType, difficulty, team );
  653. ForEachPlayer( collector );
  654. for ( int i=0; i<collector.m_bots.Count(); ++i )
  655. {
  656. CCSBot *bot = collector.m_bots[i];
  657. if ( !bot->IsAlive() )
  658. continue;
  659. bot->CommitSuicide();
  660. if ( !all )
  661. {
  662. return;
  663. }
  664. }
  665. }
  666. //--------------------------------------------------------------------------------------------------------------
  667. CON_COMMAND_F( bot_kick, "bot_kick <all> <t|ct> <type> <difficulty> <name> - Kicks a specific bot, or all bots, matching the given criteria.", FCVAR_GAMEDLL )
  668. {
  669. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  670. return;
  671. const char *name;
  672. BotDifficultyType difficulty;
  673. CSWeaponType weaponType;
  674. int team;
  675. bool all;
  676. BotArgumentsFromArgv( args, &name, &weaponType, &difficulty, &team, &all );
  677. if ( (!name || !*name) && team == TEAM_UNASSIGNED && difficulty == NUM_DIFFICULTY_LEVELS )
  678. {
  679. all = true;
  680. }
  681. CollectBots collector( name, weaponType, difficulty, team );
  682. ForEachPlayer( collector );
  683. for ( int i=0; i<collector.m_bots.Count(); ++i )
  684. {
  685. CCSBot *bot = collector.m_bots[i];
  686. engine->ServerCommand( UTIL_VarArgs( "kickid %d\n", engine->GetPlayerUserId( bot->edict() ) ) );
  687. if ( !all )
  688. {
  689. // adjust bot quota so kicked bot is not immediately added back in
  690. int newQuota = cv_bot_quota.GetInt() - 1;
  691. cv_bot_quota.SetValue( clamp( newQuota, 0, cv_bot_quota.GetInt() ) );
  692. return;
  693. }
  694. }
  695. // adjust bot quota so kicked bot is not immediately added back in
  696. if ( all && (!name || !*name) && team == TEAM_UNASSIGNED && difficulty == NUM_DIFFICULTY_LEVELS )
  697. {
  698. cv_bot_quota.SetValue( 0 );
  699. }
  700. else
  701. {
  702. int newQuota = cv_bot_quota.GetInt() - collector.m_bots.Count();
  703. cv_bot_quota.SetValue( clamp( newQuota, 0, cv_bot_quota.GetInt() ) );
  704. }
  705. }
  706. //--------------------------------------------------------------------------------------------------------------
  707. CON_COMMAND_F( bot_knives_only, "Restricts the bots to only using knives", FCVAR_GAMEDLL )
  708. {
  709. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  710. return;
  711. cv_bot_allow_pistols.SetValue( 0 );
  712. cv_bot_allow_shotguns.SetValue( 0 );
  713. cv_bot_allow_sub_machine_guns.SetValue( 0 );
  714. cv_bot_allow_rifles.SetValue( 0 );
  715. cv_bot_allow_machine_guns.SetValue( 0 );
  716. cv_bot_allow_grenades.SetValue( 0 );
  717. cv_bot_allow_snipers.SetValue( 0 );
  718. #ifdef CS_SHIELD_ENABLED
  719. cv_bot_allow_shield.SetValue( 0 );
  720. #endif // CS_SHIELD_ENABLED
  721. }
  722. //--------------------------------------------------------------------------------------------------------------
  723. CON_COMMAND_F( bot_pistols_only, "Restricts the bots to only using pistols", FCVAR_GAMEDLL )
  724. {
  725. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  726. return;
  727. cv_bot_allow_pistols.SetValue( 1 );
  728. cv_bot_allow_shotguns.SetValue( 0 );
  729. cv_bot_allow_sub_machine_guns.SetValue( 0 );
  730. cv_bot_allow_rifles.SetValue( 0 );
  731. cv_bot_allow_machine_guns.SetValue( 0 );
  732. cv_bot_allow_grenades.SetValue( 0 );
  733. cv_bot_allow_snipers.SetValue( 0 );
  734. #ifdef CS_SHIELD_ENABLED
  735. cv_bot_allow_shield.SetValue( 0 );
  736. #endif // CS_SHIELD_ENABLED
  737. }
  738. //--------------------------------------------------------------------------------------------------------------
  739. CON_COMMAND_F( bot_snipers_only, "Restricts the bots to only using sniper rifles", FCVAR_GAMEDLL )
  740. {
  741. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  742. return;
  743. cv_bot_allow_pistols.SetValue( 0 );
  744. cv_bot_allow_shotguns.SetValue( 0 );
  745. cv_bot_allow_sub_machine_guns.SetValue( 0 );
  746. cv_bot_allow_rifles.SetValue( 0 );
  747. cv_bot_allow_machine_guns.SetValue( 0 );
  748. cv_bot_allow_grenades.SetValue( 0 );
  749. cv_bot_allow_snipers.SetValue( 1 );
  750. #ifdef CS_SHIELD_ENABLED
  751. cv_bot_allow_shield.SetValue( 0 );
  752. #endif // CS_SHIELD_ENABLED
  753. }
  754. //--------------------------------------------------------------------------------------------------------------
  755. CON_COMMAND_F( bot_all_weapons, "Allows the bots to use all weapons", FCVAR_GAMEDLL )
  756. {
  757. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  758. return;
  759. cv_bot_allow_pistols.SetValue( 1 );
  760. cv_bot_allow_shotguns.SetValue( 1 );
  761. cv_bot_allow_sub_machine_guns.SetValue( 1 );
  762. cv_bot_allow_rifles.SetValue( 1 );
  763. cv_bot_allow_machine_guns.SetValue( 1 );
  764. cv_bot_allow_grenades.SetValue( 1 );
  765. cv_bot_allow_snipers.SetValue( 1 );
  766. #ifdef CS_SHIELD_ENABLED
  767. cv_bot_allow_shield.SetValue( 1 );
  768. #endif // CS_SHIELD_ENABLED
  769. }
  770. //--------------------------------------------------------------------------------------------------------------
  771. static void BotGotoArea( CNavArea *pArea )
  772. {
  773. if ( !pArea )
  774. return;
  775. for ( int i = 1; i <= gpGlobals->maxClients; ++i )
  776. {
  777. CBasePlayer *player = static_cast<CBasePlayer *>( UTIL_PlayerByIndex( i ) );
  778. if (player == NULL)
  779. continue;
  780. if (player->IsBot())
  781. {
  782. CCSBot *bot = dynamic_cast<CCSBot *>( player );
  783. if ( bot )
  784. {
  785. bot->MoveTo( pArea->GetCenter(), FASTEST_ROUTE );
  786. }
  787. break;
  788. }
  789. }
  790. }
  791. //--------------------------------------------------------------------------------------------------------------
  792. CON_COMMAND_F( bot_goto_mark, "Sends a bot to the marked nav area (useful for testing navigation meshes)", FCVAR_GAMEDLL | FCVAR_CHEAT )
  793. {
  794. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  795. return;
  796. // tell the first bot we find to go to our marked area
  797. BotGotoArea( TheNavMesh->GetMarkedArea() );
  798. }
  799. //--------------------------------------------------------------------------------------------------------------
  800. CON_COMMAND_F( bot_goto_selected, "Sends a bot to the selected nav area (useful for testing navigation meshes)", FCVAR_GAMEDLL | FCVAR_CHEAT )
  801. {
  802. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  803. return;
  804. // tell the first bot we find to go to our selected area
  805. BotGotoArea( TheNavMesh->GetSelectedArea() );
  806. }
  807. //--------------------------------------------------------------------------------------------------------------
  808. #if 0
  809. CON_COMMAND_F( bot_memory_usage, "Reports on the bots' memory usage", FCVAR_GAMEDLL )
  810. {
  811. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  812. return;
  813. Msg( "Memory usage:\n" );
  814. Msg( " %d bytes per bot\n", sizeof(CCSBot) );
  815. Msg( " %d Navigation Areas @ %d bytes each = %d bytes\n",
  816. TheNavMesh->GetNavAreaCount(),
  817. sizeof( CNavArea ),
  818. TheNavMesh->GetNavAreaCount() * sizeof( CNavArea ) );
  819. Msg( " %d Hiding Spots @ %d bytes each = %d bytes\n",
  820. TheHidingSpotList.Count(),
  821. sizeof( HidingSpot ),
  822. TheHidingSpotList.Count() * sizeof( HidingSpot ) );
  823. /*
  824. unsigned int encounterMem = 0;
  825. FOR_EACH_LL( TheNavAreaList, it )
  826. {
  827. CNavArea *area = TheNavAreaList[ it ];
  828. FOR_EACH_LL( area->m_spotEncounterList, it )
  829. {
  830. SpotEncounter *se = area->m_spotEncounterList[ it ];
  831. encounterMem += sizeof( SpotEncounter );
  832. encounterMem += se->spotList.Count() * sizeof( SpotOrder );
  833. }
  834. }
  835. Msg( " Encounter Spot data = %d bytes\n", encounterMem );
  836. */
  837. }
  838. #endif
  839. bool CCSBotManager::ServerCommand( const char *cmd )
  840. {
  841. return false;
  842. }
  843. bool CCSBotManager::ClientCommand( CBasePlayer *player, const CCommand &args )
  844. {
  845. return false;
  846. }
  847. /**
  848. * Process the "bot_add" console command
  849. */
  850. bool CCSBotManager::BotAddCommand( int team, bool isFromConsole, const char *profileName, CSWeaponType weaponType, BotDifficultyType difficulty )
  851. {
  852. if ( !TheNavMesh->IsLoaded() )
  853. {
  854. // [msmith] We don't want to run nav mesh generation if we're on a console.
  855. if ( IsGameConsole() )
  856. {
  857. DevWarning("Cannot add bot! No nav mesh found for this map!");
  858. return false;
  859. }
  860. // If there isn't a Navigation Mesh in memory, create one
  861. if ( !TheNavMesh->IsGenerating() )
  862. {
  863. if ( !m_isMapDataLoaded )
  864. {
  865. TheNavMesh->BeginGeneration();
  866. m_isMapDataLoaded = true;
  867. }
  868. return false;
  869. }
  870. }
  871. // dont allow bots to join if the Navigation Mesh is being generated
  872. if (TheNavMesh->IsGenerating())
  873. return false;
  874. const BotProfile *profile = NULL;
  875. if ( !isFromConsole )
  876. {
  877. profileName = NULL;
  878. difficulty = GetDifficultyLevel();
  879. }
  880. else
  881. {
  882. if ( difficulty == NUM_DIFFICULTY_LEVELS )
  883. {
  884. difficulty = GetDifficultyLevel();
  885. }
  886. // if team not specified, check bot_join_team cvar for preference
  887. if (team == TEAM_UNASSIGNED)
  888. {
  889. if (!stricmp( cv_bot_join_team.GetString(), "T" ))
  890. team = TEAM_TERRORIST;
  891. else if (!stricmp( cv_bot_join_team.GetString(), "CT" ))
  892. team = TEAM_CT;
  893. else
  894. team = CSGameRules()->SelectDefaultTeam();
  895. }
  896. }
  897. if ( profileName && *profileName )
  898. {
  899. // in career, ignore humans, since we want to add anyway
  900. bool ignoreHumans = CSGameRules()->IsCareer();
  901. if (UTIL_IsNameTaken( profileName, ignoreHumans ))
  902. {
  903. if ( isFromConsole )
  904. {
  905. Msg( "Error - %s is already in the game.\n", profileName );
  906. }
  907. return true;
  908. }
  909. // try to add a bot by name
  910. profile = TheBotProfiles->GetProfile( profileName, team );
  911. if ( !profile )
  912. {
  913. // try to add a bot by template
  914. profile = TheBotProfiles->GetProfileMatchingTemplate( profileName, team, difficulty, CSGameRules()->GetMatchDevice() );
  915. if ( !profile )
  916. {
  917. if ( isFromConsole )
  918. {
  919. Msg( "Error - no profile for '%s' exists.\n", profileName );
  920. }
  921. return true;
  922. }
  923. }
  924. }
  925. else
  926. {
  927. // if team not specified, check bot_join_team cvar for preference
  928. if (team == TEAM_UNASSIGNED)
  929. {
  930. if (!stricmp( cv_bot_join_team.GetString(), "T" ))
  931. team = TEAM_TERRORIST;
  932. else if (!stricmp( cv_bot_join_team.GetString(), "CT" ))
  933. team = TEAM_CT;
  934. else
  935. {
  936. if ( CSGameRules()->IsPlayingCooperativeGametype() )
  937. {
  938. team = UTIL_HumansOnTeam( TEAM_CT ) > 0 ? TEAM_TERRORIST : TEAM_CT;
  939. #if defined ( DBGFLAG_ASSERT )
  940. if ( UTIL_HumansOnTeam( team ) > 0 )
  941. {
  942. Assert( ( UTIL_HumansOnTeam( TEAM_TERRORIST ) ^ UTIL_HumansOnTeam( TEAM_CT ) ) ); // No humans on opposing teams in coop
  943. }
  944. #endif
  945. }
  946. else
  947. {
  948. team = CSGameRules()->SelectDefaultTeam();
  949. }
  950. }
  951. }
  952. if ( !isFromConsole && !profileName && ( weaponType == WEAPONTYPE_UNKNOWN ) && CSGameRules() && CSGameRules()->IsPlayingCooperativeGametype() )
  953. {
  954. //
  955. // Ensure that we have a sniper profile on the bot team for cooperative game
  956. //
  957. int numSniperBots = 0;
  958. for ( int i = 1; i <= gpGlobals->maxClients; ++i )
  959. {
  960. CCSBot *player = dynamic_cast< CCSBot * >( UTIL_PlayerByIndex( i ) );
  961. if ( player == NULL )
  962. continue;
  963. const BotProfile *pExistingBotProfile = player->GetProfile();
  964. if ( !pExistingBotProfile )
  965. continue;
  966. if ( !pExistingBotProfile->GetWeaponPreferenceCount() )
  967. continue;
  968. if ( WeaponClassFromWeaponID( pExistingBotProfile->GetWeaponPreference( 0 ) ) == WEAPONTYPE_SNIPER_RIFLE )
  969. { // found a bot who will buy a sniper rifle guaranteed
  970. ++ numSniperBots;
  971. }
  972. }
  973. int minNumSniperBots = 1;
  974. if ( CSGameRules()->IsPlayingCoopGuardian() )
  975. {
  976. extern ConVar mp_guardian_special_weapon_needed;
  977. char const *szWepShortName = mp_guardian_special_weapon_needed.GetString();
  978. if ( szWepShortName && *szWepShortName && V_strcmp( szWepShortName, "any" ) )
  979. {
  980. CSWeaponID csWeaponIdGuardianRequired = AliasToWeaponID( szWepShortName );
  981. if ( ( csWeaponIdGuardianRequired != WEAPON_NONE ) &&
  982. ( WeaponClassFromWeaponID( csWeaponIdGuardianRequired ) == WEAPONTYPE_SNIPER_RIFLE ) )
  983. {
  984. ++ minNumSniperBots;
  985. }
  986. }
  987. }
  988. if ( numSniperBots < minNumSniperBots )
  989. profile = TheBotProfiles->GetRandomProfile( difficulty, team, WEAPONTYPE_SNIPER_RIFLE );
  990. }
  991. if ( !profile )
  992. profile = TheBotProfiles->GetRandomProfile( difficulty, team, weaponType );
  993. if (profile == NULL)
  994. {
  995. if ( isFromConsole )
  996. {
  997. Msg( "All bot profiles at this difficulty level are in use.\n" );
  998. }
  999. return true;
  1000. }
  1001. }
  1002. if (team == TEAM_UNASSIGNED || team == TEAM_SPECTATOR)
  1003. {
  1004. if ( isFromConsole )
  1005. {
  1006. Msg( "Could not add bot to the game: The game is full\n" );
  1007. }
  1008. return false;
  1009. }
  1010. if (CSGameRules()->TeamFull( team ))
  1011. {
  1012. if ( isFromConsole )
  1013. {
  1014. Msg( "Could not add bot to the game: Team is full\n" );
  1015. }
  1016. return false;
  1017. }
  1018. if (CSGameRules()->TeamStacked( team, TEAM_UNASSIGNED ))
  1019. {
  1020. if ( isFromConsole )
  1021. {
  1022. Msg( "Could not add bot to the game: Team is stacked (to disable this check, set mp_autoteambalance to zero, increase mp_limitteams, and restart the round).\n" );
  1023. }
  1024. return false;
  1025. }
  1026. // create the actual bot
  1027. CCSBot *bot = CreateBot<CCSBot>( profile, team );
  1028. if (bot == NULL)
  1029. {
  1030. if ( isFromConsole )
  1031. {
  1032. Msg( "Error: CreateBot() failed.\n" );
  1033. }
  1034. return false;
  1035. }
  1036. if (isFromConsole)
  1037. {
  1038. // increase the bot quota to account for manually added bot
  1039. cv_bot_quota.SetValue( cv_bot_quota.GetInt() + 1 );
  1040. }
  1041. //
  1042. // In Queued Matchmaking mode bots are always taking spots of humans
  1043. // find a human that is not yet connected and use that human's stats
  1044. // TODO: <vitaliy> this would allow bots to take over humans
  1045. //
  1046. if ( 0 && CSGameRules() && CSGameRules()->IsQueuedMatchmaking() && CSGameRules()->m_mapQueuedMatchmakingPlayersData.Count() )
  1047. {
  1048. CUtlVector< uint32 > arrConnectedHumans;
  1049. for ( int i = 1; i <= gpGlobals->maxClients; ++i )
  1050. {
  1051. CCSPlayer *pHuman = dynamic_cast<CCSPlayer *>(UTIL_PlayerByIndex( i ));
  1052. if ( pHuman )
  1053. {
  1054. uint32 uiAccountId = pHuman->GetHumanPlayerAccountID();
  1055. if ( uiAccountId )
  1056. arrConnectedHumans.AddToTail( uiAccountId );
  1057. }
  1058. }
  1059. FOR_EACH_MAP( CSGameRules()->m_mapQueuedMatchmakingPlayersData, idxQueuedPlayer )
  1060. {
  1061. CCSGameRules::CQMMPlayerData_t &qmmPlayerData = * CSGameRules()->m_mapQueuedMatchmakingPlayersData.Element( idxQueuedPlayer );
  1062. if ( arrConnectedHumans.Find( qmmPlayerData.m_uiPlayerAccountId ) != arrConnectedHumans.InvalidIndex() )
  1063. continue; // such human is already connected
  1064. bool bThisPlayerIsFirstTeam = ( qmmPlayerData.m_iDraftIndex < 5 );
  1065. bool bTeamsArePlayingSwitchedSides = CSGameRules() ? CSGameRules()->AreTeamsPlayingSwitchedSides() : false;
  1066. // Force team according to queue reservation
  1067. int nThisHumanTeam = ( bThisPlayerIsFirstTeam == !bTeamsArePlayingSwitchedSides ) ? TEAM_CT : TEAM_TERRORIST;
  1068. if ( nThisHumanTeam != team )
  1069. continue;
  1070. // Otherwise let's take over this human!
  1071. bot->SetHumanPlayerAccountID( qmmPlayerData.m_uiPlayerAccountId );
  1072. engine->SetFakeClientConVarValue( bot->edict(), "name", CFmtStr( "BOT %u", qmmPlayerData.m_uiPlayerAccountId ).Access() );
  1073. }
  1074. }
  1075. return true;
  1076. }
  1077. /**
  1078. * Process the "bot_place" console command
  1079. */
  1080. bool CCSBotManager::BotPlaceCommand( uint nTeamMask )
  1081. {
  1082. static int lastBotPlaced = -1;
  1083. int numBots = 0;
  1084. //Count the number of bots in the map.
  1085. for ( int i = 1; i <= gpGlobals->maxClients; ++i )
  1086. {
  1087. CCSBot *bot = dynamic_cast<CCSBot *>(UTIL_PlayerByIndex( i ));
  1088. if ( NULL != bot )
  1089. {
  1090. numBots++;
  1091. }
  1092. }
  1093. if ( numBots <= 0 )
  1094. {
  1095. Msg( "Error: bot_place needs at least one bot already in the map.\n" );
  1096. return false;
  1097. }
  1098. // See which bot is the next one to be placed.
  1099. int nextBotToPlace = (lastBotPlaced+1) % numBots;
  1100. int botCount = 0;
  1101. CCSPlayer *botToMove = NULL;
  1102. for ( int i = 1; i <= gpGlobals->maxClients && botToMove == NULL; ++i )
  1103. {
  1104. CCSBot *bot = dynamic_cast<CCSBot *>(UTIL_PlayerByIndex( i ));
  1105. if ( NULL != bot )
  1106. {
  1107. if ( nextBotToPlace == botCount )
  1108. {
  1109. if ( nTeamMask & ( 1u << bot->GetTeamNumber() ) )
  1110. {
  1111. botToMove = bot;
  1112. }
  1113. else
  1114. {
  1115. nextBotToPlace = ( nextBotToPlace + 1 ) % numBots;
  1116. }
  1117. }
  1118. botCount++;
  1119. }
  1120. }
  1121. lastBotPlaced = nextBotToPlace;
  1122. CBasePlayer* localPlayer = UTIL_GetCommandClient();
  1123. if ( NULL == localPlayer )
  1124. {
  1125. Msg( "Error: BotPlaceCommand() could not find a human player to move a bot to.\n" );
  1126. return false;
  1127. }
  1128. if ( NULL == botToMove )
  1129. {
  1130. Msg( "Error: BotPlaceCommand() could not find a bot to move to player's location.\n" );
  1131. return false;
  1132. }
  1133. Vector forward;
  1134. localPlayer->EyeVectors( &forward, NULL, NULL );
  1135. trace_t tr;
  1136. UTIL_ClearTrace( tr );
  1137. // trace forward from the eye
  1138. Vector vEye = localPlayer->GetAbsOrigin() + localPlayer->GetViewOffset(), vTargetEye = vEye + ( forward * PLAYER_USE_RADIUS );
  1139. UTIL_TraceLine( vEye, vTargetEye, CONTENTS_SOLID, localPlayer->GetRefEHandle().Get(), COLLISION_GROUP_NONE, &tr );
  1140. if ( tr.DidHit() )
  1141. vTargetEye = tr.endpos;
  1142. UTIL_ClearTrace( tr );
  1143. Vector vTargetOrigin = vTargetEye - localPlayer->GetViewOffset() - Vector( 0, 0, ( 0.03125 ) );
  1144. UTIL_TraceLine( vTargetEye, vTargetOrigin, CONTENTS_SOLID, localPlayer->GetRefEHandle().Get(), COLLISION_GROUP_NONE, &tr );
  1145. if ( tr.DidHit() )
  1146. {
  1147. vTargetOrigin = tr.endpos;
  1148. vTargetOrigin.z += ( 0.03125 );
  1149. }
  1150. botToMove->SetAbsOrigin( vTargetOrigin );
  1151. return true;
  1152. }
  1153. int UTIL_CSSBotsInGame()
  1154. {
  1155. int count = 0;
  1156. for (int i = 1; i <= gpGlobals->maxClients; ++i )
  1157. {
  1158. CCSBot *player = dynamic_cast<CCSBot *>(UTIL_PlayerByIndex( i ));
  1159. if ( player == NULL )
  1160. continue;
  1161. count++;
  1162. }
  1163. return count;
  1164. }
  1165. bool UTIL_CSSKickBotFromTeam( int kickTeam )
  1166. {
  1167. int i;
  1168. // try to kick a dead bot first
  1169. for ( i = 1; i <= gpGlobals->maxClients; ++i )
  1170. {
  1171. CCSBot *player = dynamic_cast<CCSBot *>( UTIL_PlayerByIndex( i ) );
  1172. if (player == NULL)
  1173. continue;
  1174. if (!player->IsAlive() && player->GetTeamNumber() == kickTeam)
  1175. {
  1176. // its a bot on the right team - kick it
  1177. engine->ServerCommand( UTIL_VarArgs( "kickid %d\n", engine->GetPlayerUserId( player->edict() ) ) );
  1178. return true;
  1179. }
  1180. }
  1181. // no dead bots, kick any bot on the given team
  1182. for ( i = 1; i <= gpGlobals->maxClients; ++i )
  1183. {
  1184. CCSBot *player = dynamic_cast<CCSBot *>( UTIL_PlayerByIndex( i ) );
  1185. if (player == NULL)
  1186. continue;
  1187. if (player->GetTeamNumber() == kickTeam)
  1188. {
  1189. // its a bot on the right team - kick it
  1190. engine->ServerCommand( UTIL_VarArgs( "kickid %d\n", engine->GetPlayerUserId( player->edict() ) ) );
  1191. return true;
  1192. }
  1193. }
  1194. return false;
  1195. }
  1196. //--------------------------------------------------------------------------------------------------------------
  1197. /**
  1198. * Keep a minimum quota of bots in the game
  1199. */
  1200. void CCSBotManager::MaintainBotQuota( void )
  1201. {
  1202. if ( !AreBotsAllowed() )
  1203. return;
  1204. if (TheNavMesh->IsGenerating())
  1205. return;
  1206. int totalHumansInGame = UTIL_HumansInGame();
  1207. int humanPlayersInGame = UTIL_HumansInGame( IGNORE_SPECTATORS, IGNORE_UNASSIGNED );
  1208. int spectatorPlayersInGame = UTIL_SpectatorsInGame();
  1209. // don't add bots until local player has been registered, to make sure he's player ID #1
  1210. if (!engine->IsDedicatedServer() && totalHumansInGame == 0)
  1211. return;
  1212. // new players can't spawn immediately after the round has been going for some time
  1213. if ( !CSGameRules() || !TheCSBots() )
  1214. {
  1215. return;
  1216. }
  1217. int desiredBotCount = cv_bot_quota.GetInt();
  1218. int botsInGame = UTIL_CSSBotsInGame();
  1219. /// isRoundInProgress is true if the round has progressed far enough that new players will join as dead.
  1220. bool isRoundInProgress = CSGameRules()->m_bFirstConnected &&
  1221. !TheCSBots()->IsRoundOver() &&
  1222. ( CSGameRules()->GetRoundElapsedTime() >= 20.0f );
  1223. if ( FStrEq( cv_bot_quota_mode.GetString(), "fill" ) )
  1224. {
  1225. // If bot_quota_mode is 'fill', we want the number of bots and humans together to equal bot_quota
  1226. // unless the round is already in progress, in which case we play with what we've been dealt
  1227. // don't do this check in coop mission mode because we change the number every wave
  1228. if ( !isRoundInProgress || CSGameRules()->IsPlayingCoopMission() )
  1229. {
  1230. desiredBotCount = MAX( 0, desiredBotCount - humanPlayersInGame + spectatorPlayersInGame );
  1231. }
  1232. else
  1233. {
  1234. desiredBotCount = botsInGame;
  1235. }
  1236. }
  1237. else if ( FStrEq( cv_bot_quota_mode.GetString(), "match" ) )
  1238. {
  1239. // If bot_quota_mode is 'match', we want the number of bots to be bot_quota * total humans
  1240. // unless the round is already in progress, in which case we play with what we've been dealt
  1241. if ( !isRoundInProgress )
  1242. {
  1243. desiredBotCount = (int)MAX( 0, cv_bot_quota.GetFloat() * humanPlayersInGame );
  1244. }
  1245. else
  1246. {
  1247. desiredBotCount = botsInGame;
  1248. }
  1249. }
  1250. // wait for a player to join, if necessary
  1251. if (cv_bot_join_after_player.GetBool())
  1252. {
  1253. if ( humanPlayersInGame == 0 && spectatorPlayersInGame == 0 )
  1254. desiredBotCount = 0;
  1255. }
  1256. // wait until the map has been loaded for a bit, to allow players to transition across
  1257. // the transition without missing the pistol round
  1258. if ( bot_join_delay.GetInt() > CSGameRules()->GetMapElapsedTime() )
  1259. {
  1260. desiredBotCount = 0;
  1261. }
  1262. // If the match is in warmup phase and we don't want any bots in warmup then don't have
  1263. // the bots joining the match during warmup
  1264. if ( !bot_join_in_warmup.GetBool() && CSGameRules()->IsWarmupPeriod() )
  1265. {
  1266. desiredBotCount = 0;
  1267. }
  1268. // if bots will auto-vacate, we need to keep one slot open to allow players to join
  1269. if ( cv_bot_auto_vacate.GetBool() && !CSGameRules()->IsPlayingCoopMission() )
  1270. desiredBotCount = MIN( desiredBotCount, gpGlobals->maxClients - (humanPlayersInGame + 1) );
  1271. else
  1272. desiredBotCount = MIN( desiredBotCount, gpGlobals->maxClients - humanPlayersInGame + spectatorPlayersInGame );
  1273. // Try to balance teams, if we are in the first 20 seconds of a round and bots can join either team.
  1274. if ( botsInGame > 0 && desiredBotCount == botsInGame && CSGameRules()->m_bFirstConnected )
  1275. {
  1276. if ( CSGameRules()->GetRoundElapsedTime() < 20.0f ) // new bots can still spawn during this time
  1277. {
  1278. if ( mp_autoteambalance.GetBool() )
  1279. {
  1280. int numAliveTerrorist;
  1281. int numAliveCT;
  1282. int numDeadTerrorist;
  1283. int numDeadCT;
  1284. CSGameRules()->InitializePlayerCounts( numAliveTerrorist, numAliveCT, numDeadTerrorist, numDeadCT );
  1285. if ( !FStrEq( cv_bot_join_team.GetString(), "T" ) &&
  1286. !FStrEq( cv_bot_join_team.GetString(), "CT" ) )
  1287. {
  1288. if ( numAliveTerrorist > CSGameRules()->m_iNumCT + 1 )
  1289. {
  1290. if ( UTIL_KickBotFromTeam( TEAM_TERRORIST ) )
  1291. return;
  1292. }
  1293. else if ( numAliveCT > CSGameRules()->m_iNumTerrorist + 1 )
  1294. {
  1295. if ( UTIL_KickBotFromTeam( TEAM_CT ) )
  1296. return;
  1297. }
  1298. }
  1299. }
  1300. }
  1301. }
  1302. // add bots if necessary
  1303. if (desiredBotCount > botsInGame)
  1304. {
  1305. // don't try to add a bot if all teams are full
  1306. if ( !CSGameRules()->TeamFull( TEAM_TERRORIST ) || !CSGameRules()->TeamFull( TEAM_CT ) )
  1307. TheCSBots()->BotAddCommand( TEAM_UNASSIGNED );
  1308. }
  1309. else if (desiredBotCount < botsInGame)
  1310. {
  1311. // kick a bot to maintain quota
  1312. // first remove any unassigned bots
  1313. if (UTIL_CSSKickBotFromTeam( TEAM_UNASSIGNED ))
  1314. return;
  1315. int kickTeam;
  1316. CCSMatch* match = CSGameRules()->GetMatch();
  1317. // remove from the team that has more players
  1318. if (CSGameRules()->m_iNumTerrorist > CSGameRules()->m_iNumCT)
  1319. {
  1320. kickTeam = TEAM_TERRORIST;
  1321. }
  1322. else if (CSGameRules()->m_iNumTerrorist < CSGameRules()->m_iNumCT)
  1323. {
  1324. kickTeam = TEAM_CT;
  1325. }
  1326. // remove from the team that's winning
  1327. else if ( match && match->GetWinningTeam() == TEAM_TERRORIST )
  1328. {
  1329. kickTeam = TEAM_TERRORIST;
  1330. }
  1331. else if ( match && match->GetWinningTeam() == TEAM_CT )
  1332. {
  1333. kickTeam = TEAM_CT;
  1334. }
  1335. else
  1336. {
  1337. // teams and scores are equal, pick a team at random
  1338. kickTeam = (RandomInt( 0, 1 ) == 0) ? TEAM_CT : TEAM_TERRORIST;
  1339. }
  1340. // attempt to kick a bot from the given team
  1341. if (UTIL_CSSKickBotFromTeam( kickTeam ))
  1342. return;
  1343. // if there were no bots on the team, kick a bot from the other team
  1344. if (kickTeam == TEAM_TERRORIST)
  1345. UTIL_CSSKickBotFromTeam( TEAM_CT );
  1346. else
  1347. UTIL_CSSKickBotFromTeam( TEAM_TERRORIST );
  1348. }
  1349. }
  1350. //--------------------------------------------------------------------------------------------------------------
  1351. /**
  1352. * Collect all nav areas that overlap the given zone
  1353. */
  1354. class CollectOverlappingAreas
  1355. {
  1356. public:
  1357. CollectOverlappingAreas( CCSBotManager::Zone *zone )
  1358. {
  1359. m_zone = zone;
  1360. zone->m_areaCount = 0;
  1361. }
  1362. bool operator() ( CNavArea *area )
  1363. {
  1364. Extent areaExtent;
  1365. area->GetExtent(&areaExtent);
  1366. if (areaExtent.hi.x >= m_zone->m_extent.lo.x && areaExtent.lo.x <= m_zone->m_extent.hi.x &&
  1367. areaExtent.hi.y >= m_zone->m_extent.lo.y && areaExtent.lo.y <= m_zone->m_extent.hi.y &&
  1368. areaExtent.hi.z >= m_zone->m_extent.lo.z && areaExtent.lo.z <= m_zone->m_extent.hi.z)
  1369. {
  1370. // area overlaps m_zone
  1371. m_zone->m_area[ m_zone->m_areaCount++ ] = area;
  1372. if (m_zone->m_areaCount == CCSBotManager::MAX_ZONE_NAV_AREAS)
  1373. {
  1374. return false;
  1375. }
  1376. }
  1377. return true;
  1378. }
  1379. private:
  1380. CCSBotManager::Zone *m_zone;
  1381. };
  1382. //--------------------------------------------------------------------------------------------------------------
  1383. /**
  1384. * Search the map entities to determine the game scenario and define important zones.
  1385. */
  1386. void CCSBotManager::ExtractScenarioData( void )
  1387. {
  1388. if (!TheNavMesh->IsLoaded())
  1389. return;
  1390. m_zoneCount = 0;
  1391. m_gameScenario = SCENARIO_DEATHMATCH;
  1392. //
  1393. // Search all entities in the map and set the game type and
  1394. // store all zones (bomb target, etc).
  1395. //
  1396. CBaseEntity *entity;
  1397. int i;
  1398. for( i=1; i<gpGlobals->maxEntities; ++i )
  1399. {
  1400. entity = CBaseEntity::Instance( INDEXENT( i ) );
  1401. if (entity == NULL)
  1402. continue;
  1403. bool found = false;
  1404. bool isLegacy = false;
  1405. if (FClassnameIs( entity, "func_bomb_target" ))
  1406. {
  1407. m_gameScenario = SCENARIO_DEFUSE_BOMB;
  1408. found = true;
  1409. isLegacy = false;
  1410. }
  1411. else if (FClassnameIs( entity, "info_bomb_target" ))
  1412. {
  1413. m_gameScenario = SCENARIO_DEFUSE_BOMB;
  1414. found = true;
  1415. isLegacy = true;
  1416. }
  1417. else if (FClassnameIs( entity, "func_hostage_rescue" ))
  1418. {
  1419. m_gameScenario = SCENARIO_RESCUE_HOSTAGES;
  1420. found = true;
  1421. isLegacy = false;
  1422. }
  1423. else if (FClassnameIs( entity, "info_hostage_rescue" ))
  1424. {
  1425. m_gameScenario = SCENARIO_RESCUE_HOSTAGES;
  1426. found = true;
  1427. isLegacy = true;
  1428. }
  1429. else if (FClassnameIs( entity, "hostage_entity" ))
  1430. {
  1431. // some very old maps (ie: cs_assault) use info_player_start
  1432. // as rescue zones, so set the scenario if there are hostages
  1433. // in the map
  1434. m_gameScenario = SCENARIO_RESCUE_HOSTAGES;
  1435. }
  1436. else if (FClassnameIs( entity, "func_vip_safetyzone" ))
  1437. {
  1438. m_gameScenario = SCENARIO_ESCORT_VIP;
  1439. found = true;
  1440. isLegacy = false;
  1441. }
  1442. if (found)
  1443. {
  1444. if (m_zoneCount < MAX_ZONES)
  1445. {
  1446. Vector absmin, absmax;
  1447. entity->CollisionProp()->WorldSpaceAABB( &absmin, &absmax );
  1448. m_zone[ m_zoneCount ].m_isBlocked = false;
  1449. m_zone[ m_zoneCount ].m_center = (isLegacy) ? entity->GetAbsOrigin() : (absmin + absmax)/2.0f;
  1450. m_zone[ m_zoneCount ].m_isLegacy = isLegacy;
  1451. m_zone[ m_zoneCount ].m_index = m_zoneCount;
  1452. m_zone[ m_zoneCount++ ].m_entity = entity;
  1453. }
  1454. else
  1455. Msg( "Warning: Too many zones, some will be ignored.\n" );
  1456. }
  1457. }
  1458. //
  1459. // If there are no zones and the scenario is hostage rescue,
  1460. // use the info_player_start entities as rescue zones.
  1461. //
  1462. if (m_zoneCount == 0 && m_gameScenario == SCENARIO_RESCUE_HOSTAGES)
  1463. {
  1464. for( entity = gEntList.FindEntityByClassname( NULL, "info_player_start" );
  1465. entity && !FNullEnt( entity->edict() );
  1466. entity = gEntList.FindEntityByClassname( entity, "info_player_start" ) )
  1467. {
  1468. if (m_zoneCount < MAX_ZONES)
  1469. {
  1470. m_zone[ m_zoneCount ].m_isBlocked = false;
  1471. m_zone[ m_zoneCount ].m_center = entity->GetAbsOrigin();
  1472. m_zone[ m_zoneCount ].m_isLegacy = true;
  1473. m_zone[ m_zoneCount ].m_index = m_zoneCount;
  1474. m_zone[ m_zoneCount++ ].m_entity = entity;
  1475. }
  1476. else
  1477. {
  1478. Msg( "Warning: Too many zones, some will be ignored.\n" );
  1479. }
  1480. }
  1481. }
  1482. //
  1483. // Collect nav areas that overlap each zone
  1484. //
  1485. for( i=0; i<m_zoneCount; ++i )
  1486. {
  1487. Zone *zone = &m_zone[i];
  1488. if (zone->m_isLegacy)
  1489. {
  1490. const float legacyRange = 256.0f;
  1491. zone->m_extent.lo.x = zone->m_center.x - legacyRange;
  1492. zone->m_extent.lo.y = zone->m_center.y - legacyRange;
  1493. zone->m_extent.lo.z = zone->m_center.z - legacyRange;
  1494. zone->m_extent.hi.x = zone->m_center.x + legacyRange;
  1495. zone->m_extent.hi.y = zone->m_center.y + legacyRange;
  1496. zone->m_extent.hi.z = zone->m_center.z + legacyRange;
  1497. }
  1498. else
  1499. {
  1500. Vector absmin, absmax;
  1501. zone->m_entity->CollisionProp()->WorldSpaceAABB( &absmin, &absmax );
  1502. zone->m_extent.lo = absmin;
  1503. zone->m_extent.hi = absmax;
  1504. }
  1505. // ensure Z overlap
  1506. const float zFudge = 50.0f;
  1507. zone->m_extent.lo.z -= zFudge;
  1508. zone->m_extent.hi.z += zFudge;
  1509. // build a list of nav areas that overlap this zone
  1510. CollectOverlappingAreas collector( zone );
  1511. TheNavMesh->ForAllAreas( collector );
  1512. }
  1513. }
  1514. //--------------------------------------------------------------------------------------------------------------
  1515. /**
  1516. * Return the zone that contains the given position
  1517. */
  1518. const CCSBotManager::Zone *CCSBotManager::GetZone( const Vector &pos ) const
  1519. {
  1520. for( int z=0; z<m_zoneCount; ++z )
  1521. {
  1522. if (m_zone[z].m_extent.Contains( pos ))
  1523. {
  1524. return &m_zone[z];
  1525. }
  1526. }
  1527. return NULL;
  1528. }
  1529. //--------------------------------------------------------------------------------------------------------------
  1530. /**
  1531. * Return the closest zone to the given position
  1532. */
  1533. const CCSBotManager::Zone *CCSBotManager::GetClosestZone( const Vector &pos ) const
  1534. {
  1535. const Zone *close = NULL;
  1536. float closeRangeSq = 999999999.9f;
  1537. for( int z=0; z<m_zoneCount; ++z )
  1538. {
  1539. if ( m_zone[z].m_isBlocked )
  1540. continue;
  1541. float rangeSq = (m_zone[z].m_center - pos).LengthSqr();
  1542. if (rangeSq < closeRangeSq)
  1543. {
  1544. closeRangeSq = rangeSq;
  1545. close = &m_zone[z];
  1546. }
  1547. }
  1548. return close;
  1549. }
  1550. //--------------------------------------------------------------------------------------------------------------
  1551. /**
  1552. * Return a random position inside the given zone
  1553. */
  1554. const Vector *CCSBotManager::GetRandomPositionInZone( const Zone *zone ) const
  1555. {
  1556. static Vector pos;
  1557. if (zone == NULL)
  1558. return NULL;
  1559. if (zone->m_areaCount == 0)
  1560. return NULL;
  1561. // pick a random overlapping area
  1562. CNavArea *area = GetRandomAreaInZone(zone);
  1563. // pick a location inside both the nav area and the zone
  1564. /// @todo Randomize this
  1565. if (zone->m_isLegacy)
  1566. {
  1567. /// @todo It is possible that the radius might not overlap this area at all...
  1568. area->GetClosestPointOnArea( zone->m_center, &pos );
  1569. }
  1570. else
  1571. {
  1572. Extent areaExtent;
  1573. area->GetExtent(&areaExtent);
  1574. Extent overlap;
  1575. overlap.lo.x = MAX( areaExtent.lo.x, zone->m_extent.lo.x );
  1576. overlap.lo.y = MAX( areaExtent.lo.y, zone->m_extent.lo.y );
  1577. overlap.hi.x = MIN( areaExtent.hi.x, zone->m_extent.hi.x );
  1578. overlap.hi.y = MIN( areaExtent.hi.y, zone->m_extent.hi.y );
  1579. pos.x = (overlap.lo.x + overlap.hi.x)/2.0f;
  1580. pos.y = (overlap.lo.y + overlap.hi.y)/2.0f;
  1581. pos.z = area->GetZ( pos );
  1582. }
  1583. return &pos;
  1584. }
  1585. //--------------------------------------------------------------------------------------------------------------
  1586. /**
  1587. * Return a random area inside the given zone
  1588. */
  1589. CNavArea *CCSBotManager::GetRandomAreaInZone( const Zone *zone ) const
  1590. {
  1591. int areaCount = zone->m_areaCount;
  1592. if( areaCount == 0 )
  1593. {
  1594. Assert( false && "CCSBotManager::GetRandomAreaInZone: No areas for this zone" );
  1595. return NULL;
  1596. }
  1597. // Random, but weighted. Jump areas score zero, since you aren't ever meant to stop on one of those.
  1598. // Avoid areas score 1 to a normal area's 20 because pathfinding treats Avoid as a 20x penalty.
  1599. int totalWeight = 0;
  1600. for( int areaIndex = 0; areaIndex < areaCount; areaIndex++ )
  1601. {
  1602. CNavArea *currentArea = zone->m_area[areaIndex];
  1603. if( currentArea->GetAttributes() & NAV_MESH_JUMP )
  1604. totalWeight += 0;
  1605. else if( currentArea->GetAttributes() & NAV_MESH_AVOID )
  1606. totalWeight += 1;
  1607. else
  1608. totalWeight += 20;
  1609. }
  1610. if( totalWeight == 0 )
  1611. {
  1612. Assert( false && "CCSBotManager::GetRandomAreaInZone: No real areas for this zone" );
  1613. return NULL;
  1614. }
  1615. int randomPick = RandomInt( 1, totalWeight );
  1616. for( int areaIndex = 0; areaIndex < areaCount; areaIndex++ )
  1617. {
  1618. CNavArea *currentArea = zone->m_area[areaIndex];
  1619. if( currentArea->GetAttributes() & NAV_MESH_JUMP )
  1620. randomPick -= 0;
  1621. else if( currentArea->GetAttributes() & NAV_MESH_AVOID )
  1622. randomPick -= 1;
  1623. else
  1624. randomPick -= 20;
  1625. if( randomPick <= 0 )
  1626. return currentArea;
  1627. }
  1628. // Won't ever get here, but the compiler will cry without it.
  1629. return zone->m_area[0];
  1630. }
  1631. //--------------------------------------------------------------------------------------------------------------
  1632. void CCSBotManager::OnServerShutdown( IGameEvent *event )
  1633. {
  1634. if ( !engine->IsDedicatedServer() )
  1635. {
  1636. // Since we're a listenserver, save some config info for the next time we start up
  1637. static const char *botVars[] =
  1638. {
  1639. "bot_quota",
  1640. "bot_difficulty",
  1641. "bot_chatter",
  1642. "bot_prefix",
  1643. "bot_join_team",
  1644. "bot_defer_to_human_items",
  1645. "bot_defer_to_human_goals",
  1646. #ifdef CS_SHIELD_ENABLED
  1647. "bot_allow_shield",
  1648. #endif // CS_SHIELD_ENABLED
  1649. "bot_join_after_player",
  1650. "bot_allow_rogues",
  1651. "bot_allow_pistols",
  1652. "bot_allow_shotguns",
  1653. "bot_allow_sub_machine_guns",
  1654. "bot_allow_machine_guns",
  1655. "bot_allow_rifles",
  1656. "bot_allow_snipers",
  1657. "bot_allow_grenades"
  1658. #if CS_CONTROLLABLE_BOTS_ENABLED
  1659. "bot_controllable",
  1660. #endif
  1661. };
  1662. KeyValues *data = new KeyValues( "ServerConfig" );
  1663. // load the config data
  1664. if (data)
  1665. {
  1666. data->LoadFromFile( filesystem, "ServerConfig.vdf", "GAME" );
  1667. for ( int i=0; i<sizeof(botVars)/sizeof(botVars[0]); ++i )
  1668. {
  1669. const char *varName = botVars[i];
  1670. if ( varName )
  1671. {
  1672. ConVar *var = cvar->FindVar( varName );
  1673. if ( var )
  1674. {
  1675. data->SetString( varName, var->GetString() );
  1676. }
  1677. }
  1678. }
  1679. data->SaveToFile( filesystem, "ServerConfig.vdf", "GAME" );
  1680. data->deleteThis();
  1681. }
  1682. return;
  1683. }
  1684. }
  1685. //--------------------------------------------------------------------------------------------------------------
  1686. void CCSBotManager::OnPlayerFootstep( IGameEvent *event )
  1687. {
  1688. CCSBOTMANAGER_ITERATE_BOTS( OnPlayerFootstep, event );
  1689. }
  1690. //--------------------------------------------------------------------------------------------------------------
  1691. void CCSBotManager::OnPlayerRadio( IGameEvent *event )
  1692. {
  1693. // if it's an Enemy Spotted radio, update our enemy spotted timestamp
  1694. if ( event->GetInt( "slot" ) == RADIO_ENEMY_SPOTTED )
  1695. {
  1696. // to have some idea of when a human Player has seen an enemy
  1697. SetLastSeenEnemyTimestamp();
  1698. }
  1699. CCSBOTMANAGER_ITERATE_BOTS( OnPlayerRadio, event );
  1700. }
  1701. //--------------------------------------------------------------------------------------------------------------
  1702. void CCSBotManager::OnPlayerDeath( IGameEvent *event )
  1703. {
  1704. CCSBOTMANAGER_ITERATE_BOTS( OnPlayerDeath, event );
  1705. }
  1706. //--------------------------------------------------------------------------------------------------------------
  1707. void CCSBotManager::OnPlayerFallDamage( IGameEvent *event )
  1708. {
  1709. CCSBOTMANAGER_ITERATE_BOTS( OnPlayerFallDamage, event );
  1710. }
  1711. //--------------------------------------------------------------------------------------------------------------
  1712. void CCSBotManager::OnBombPickedUp( IGameEvent *event )
  1713. {
  1714. // bomb no longer loose
  1715. SetLooseBomb( NULL );
  1716. CCSBOTMANAGER_ITERATE_BOTS( OnBombPickedUp, event );
  1717. }
  1718. //--------------------------------------------------------------------------------------------------------------
  1719. void CCSBotManager::OnBombPlanted( IGameEvent *event )
  1720. {
  1721. m_isBombPlanted = true;
  1722. m_bombPlantTimestamp = gpGlobals->curtime;
  1723. CCSBOTMANAGER_ITERATE_BOTS( OnBombPlanted, event );
  1724. }
  1725. //--------------------------------------------------------------------------------------------------------------
  1726. void CCSBotManager::OnBombBeep( IGameEvent *event )
  1727. {
  1728. CCSBOTMANAGER_ITERATE_BOTS( OnBombBeep, event );
  1729. }
  1730. //--------------------------------------------------------------------------------------------------------------
  1731. void CCSBotManager::OnBombDefuseBegin( IGameEvent *event )
  1732. {
  1733. m_bombDefuser = static_cast<CCSPlayer *>( UTIL_PlayerByUserId( event->GetInt( "userid" ) ) );
  1734. CCSBOTMANAGER_ITERATE_BOTS( OnBombDefuseBegin, event );
  1735. }
  1736. //--------------------------------------------------------------------------------------------------------------
  1737. void CCSBotManager::OnBombDefused( IGameEvent *event )
  1738. {
  1739. m_isBombPlanted = false;
  1740. m_bombDefuser = NULL;
  1741. CCSBOTMANAGER_ITERATE_BOTS( OnBombDefused, event );
  1742. }
  1743. //--------------------------------------------------------------------------------------------------------------
  1744. void CCSBotManager::OnBombDefuseAbort( IGameEvent *event )
  1745. {
  1746. m_bombDefuser = NULL;
  1747. CCSBOTMANAGER_ITERATE_BOTS( OnBombDefuseAbort, event );
  1748. }
  1749. //--------------------------------------------------------------------------------------------------------------
  1750. void CCSBotManager::OnBombExploded( IGameEvent *event )
  1751. {
  1752. CCSBOTMANAGER_ITERATE_BOTS( OnBombExploded, event );
  1753. }
  1754. //--------------------------------------------------------------------------------------------------------------
  1755. void CCSBotManager::OnRoundEnd( IGameEvent *event )
  1756. {
  1757. m_isRoundOver = true;
  1758. CCSBOTMANAGER_ITERATE_BOTS( OnRoundEnd, event );
  1759. }
  1760. //--------------------------------------------------------------------------------------------------------------
  1761. void CCSBotManager::OnRoundStart( IGameEvent *event )
  1762. {
  1763. RestartRound();
  1764. CCSBOTMANAGER_ITERATE_BOTS( OnRoundStart, event );
  1765. }
  1766. //--------------------------------------------------------------------------------------------------------------
  1767. static CBaseEntity * SelectSpawnSpot( const char *pEntClassName )
  1768. {
  1769. CBaseEntity* pSpot = NULL;
  1770. // Find the next spawn spot.
  1771. pSpot = gEntList.FindEntityByClassname( pSpot, pEntClassName );
  1772. if ( pSpot == NULL ) // skip over the null point
  1773. pSpot = gEntList.FindEntityByClassname( pSpot, pEntClassName );
  1774. CBaseEntity *pFirstSpot = pSpot;
  1775. do
  1776. {
  1777. if ( pSpot )
  1778. {
  1779. // check if pSpot is valid
  1780. if ( pSpot->GetAbsOrigin() == Vector( 0, 0, 0 ) )
  1781. {
  1782. pSpot = gEntList.FindEntityByClassname( pSpot, pEntClassName );
  1783. continue;
  1784. }
  1785. // if so, go to pSpot
  1786. return pSpot;
  1787. }
  1788. // increment pSpot
  1789. pSpot = gEntList.FindEntityByClassname( pSpot, pEntClassName );
  1790. } while ( pSpot != pFirstSpot ); // loop if we're not back to the start
  1791. return NULL;
  1792. }
  1793. //--------------------------------------------------------------------------------------------------------------
  1794. /**
  1795. * Pathfind from each zone to a spawn point to ensure it is valid. Assumes that every spawn can pathfind to
  1796. * every other spawn.
  1797. */
  1798. void CCSBotManager::CheckForBlockedZones( void )
  1799. {
  1800. CBaseEntity *pSpot = SelectSpawnSpot( "info_player_counterterrorist" );
  1801. if ( !pSpot )
  1802. {
  1803. if ( CSGameRules()->IsPlayingCoopMission() )
  1804. {
  1805. pSpot = SelectSpawnSpot( "info_enemy_terrorist_spawn" );
  1806. }
  1807. else
  1808. {
  1809. pSpot = SelectSpawnSpot( "info_player_terrorist" );
  1810. }
  1811. }
  1812. if ( !pSpot )
  1813. return;
  1814. Vector spawnPos = pSpot->GetAbsOrigin();
  1815. CNavArea *spawnArea = TheNavMesh->GetNearestNavArea( spawnPos );
  1816. if ( !spawnArea )
  1817. return;
  1818. ShortestPathCost costFunc;
  1819. for( int i=0; i<m_zoneCount; ++i )
  1820. {
  1821. if (m_zone[i].m_areaCount == 0)
  1822. continue;
  1823. // just use the first overlapping nav area as a reasonable approximation
  1824. float dist = NavAreaTravelDistance( spawnArea, m_zone[i].m_area[0], costFunc );
  1825. m_zone[i].m_isBlocked = (dist < 0.0f );
  1826. if ( cv_bot_debug.GetInt() == 5 )
  1827. {
  1828. if ( m_zone[i].m_isBlocked )
  1829. DevMsg( "%.1f: Zone %d, area %d (%.0f %.0f %.0f) is blocked from spawn area %d (%.0f %.0f %.0f)\n",
  1830. gpGlobals->curtime, i, m_zone[i].m_area[0]->GetID(),
  1831. m_zone[i].m_area[0]->GetCenter().x, m_zone[i].m_area[0]->GetCenter().y, m_zone[i].m_area[0]->GetCenter().z,
  1832. spawnArea->GetID(),
  1833. spawnPos.x, spawnPos.y, spawnPos.z );
  1834. }
  1835. }
  1836. }
  1837. //--------------------------------------------------------------------------------------------------------------
  1838. void CCSBotManager::OnRoundFreezeEnd( IGameEvent *event )
  1839. {
  1840. bool reenableEvents = m_NavBlockedEvent.IsEnabled();
  1841. m_NavBlockedEvent.Enable( false ); // don't listen to nav_blocked events - there could be several, and we don't have bots pathing
  1842. CUtlVector< CNavArea * >& transientAreas = TheNavMesh->GetTransientAreas();
  1843. for ( int i=0; i<transientAreas.Count(); ++i )
  1844. {
  1845. CNavArea *area = transientAreas[i];
  1846. if ( area->GetAttributes() & NAV_MESH_TRANSIENT )
  1847. {
  1848. area->UpdateBlocked();
  1849. }
  1850. }
  1851. if ( reenableEvents )
  1852. {
  1853. m_NavBlockedEvent.Enable( true );
  1854. }
  1855. CheckForBlockedZones();
  1856. }
  1857. //--------------------------------------------------------------------------------------------------------------
  1858. void CCSBotManager::OnNavBlocked( IGameEvent *event )
  1859. {
  1860. CCSBOTMANAGER_ITERATE_BOTS( OnNavBlocked, event );
  1861. CheckForBlockedZones();
  1862. }
  1863. //--------------------------------------------------------------------------------------------------------------
  1864. void CCSBotManager::OnDoorMoving( IGameEvent *event )
  1865. {
  1866. CCSBOTMANAGER_ITERATE_BOTS( OnDoorMoving, event );
  1867. }
  1868. //--------------------------------------------------------------------------------------------------------------
  1869. /**
  1870. * Check all nav areas inside the breakable's extent to see if players would now fall through
  1871. */
  1872. class CheckAreasOverlappingBreakable
  1873. {
  1874. public:
  1875. CheckAreasOverlappingBreakable( CBaseEntity *breakable )
  1876. {
  1877. m_breakable = breakable;
  1878. ICollideable *collideable = breakable->GetCollideable();
  1879. collideable->WorldSpaceSurroundingBounds( &m_breakableExtent.lo, &m_breakableExtent.hi );
  1880. const float expand = 10.0f;
  1881. m_breakableExtent.lo += Vector( -expand, -expand, -expand );
  1882. m_breakableExtent.hi += Vector( expand, expand, expand );
  1883. }
  1884. bool operator() ( CNavArea *area )
  1885. {
  1886. Extent areaExtent;
  1887. area->GetExtent(&areaExtent);
  1888. if (areaExtent.hi.x >= m_breakableExtent.lo.x && areaExtent.lo.x <= m_breakableExtent.hi.x &&
  1889. areaExtent.hi.y >= m_breakableExtent.lo.y && areaExtent.lo.y <= m_breakableExtent.hi.y &&
  1890. areaExtent.hi.z >= m_breakableExtent.lo.z && areaExtent.lo.z <= m_breakableExtent.hi.z)
  1891. {
  1892. // area overlaps the breakable
  1893. area->CheckFloor( m_breakable );
  1894. }
  1895. return true;
  1896. }
  1897. private:
  1898. Extent m_breakableExtent;
  1899. CBaseEntity *m_breakable;
  1900. };
  1901. //--------------------------------------------------------------------------------------------------------------
  1902. void CCSBotManager::OnBreakBreakable( IGameEvent *event )
  1903. {
  1904. CBaseEntity *pEntity = UTIL_EntityByIndex( event->GetInt( "entindex" ) );
  1905. AssertMsg( pEntity, "Bad Entity Index received" );
  1906. if ( pEntity )
  1907. {
  1908. CheckAreasOverlappingBreakable collector( pEntity );
  1909. TheNavMesh->ForAllAreas( collector );
  1910. CCSBOTMANAGER_ITERATE_BOTS( OnBreakBreakable, event );
  1911. }
  1912. }
  1913. //--------------------------------------------------------------------------------------------------------------
  1914. void CCSBotManager::OnBreakProp( IGameEvent *event )
  1915. {
  1916. CBaseEntity *pEntity = UTIL_EntityByIndex( event->GetInt( "entindex" ) );
  1917. AssertMsg( pEntity, "Bad Entity Index received" );
  1918. if ( pEntity )
  1919. {
  1920. CheckAreasOverlappingBreakable collector( pEntity );
  1921. TheNavMesh->ForAllAreas( collector );
  1922. CCSBOTMANAGER_ITERATE_BOTS( OnBreakProp, event );
  1923. }
  1924. }
  1925. //--------------------------------------------------------------------------------------------------------------
  1926. void CCSBotManager::OnHostageFollows( IGameEvent *event )
  1927. {
  1928. CCSBOTMANAGER_ITERATE_BOTS( OnHostageFollows, event );
  1929. }
  1930. //--------------------------------------------------------------------------------------------------------------
  1931. void CCSBotManager::OnHostageRescuedAll( IGameEvent *event )
  1932. {
  1933. CCSBOTMANAGER_ITERATE_BOTS( OnHostageRescuedAll, event );
  1934. }
  1935. //--------------------------------------------------------------------------------------------------------------
  1936. void CCSBotManager::OnWeaponFire( IGameEvent *event )
  1937. {
  1938. CCSBOTMANAGER_ITERATE_BOTS( OnWeaponFire, event );
  1939. }
  1940. //--------------------------------------------------------------------------------------------------------------
  1941. void CCSBotManager::OnWeaponFireOnEmpty( IGameEvent *event )
  1942. {
  1943. CCSBOTMANAGER_ITERATE_BOTS( OnWeaponFireOnEmpty, event );
  1944. }
  1945. //--------------------------------------------------------------------------------------------------------------
  1946. void CCSBotManager::OnWeaponReload( IGameEvent *event )
  1947. {
  1948. CCSBOTMANAGER_ITERATE_BOTS( OnWeaponReload, event );
  1949. }
  1950. //--------------------------------------------------------------------------------------------------------------
  1951. void CCSBotManager::OnWeaponZoom( IGameEvent *event )
  1952. {
  1953. CCSBOTMANAGER_ITERATE_BOTS( OnWeaponZoom, event );
  1954. }
  1955. //--------------------------------------------------------------------------------------------------------------
  1956. void CCSBotManager::OnBulletImpact( IGameEvent *event )
  1957. {
  1958. CCSBOTMANAGER_ITERATE_BOTS( OnBulletImpact, event );
  1959. }
  1960. //--------------------------------------------------------------------------------------------------------------
  1961. void CCSBotManager::OnHEGrenadeDetonate( IGameEvent *event )
  1962. {
  1963. CCSBOTMANAGER_ITERATE_BOTS( OnHEGrenadeDetonate, event );
  1964. }
  1965. //--------------------------------------------------------------------------------------------------------------
  1966. void CCSBotManager::OnFlashbangDetonate( IGameEvent *event )
  1967. {
  1968. CCSBOTMANAGER_ITERATE_BOTS( OnFlashbangDetonate, event );
  1969. }
  1970. //--------------------------------------------------------------------------------------------------------------
  1971. void CCSBotManager::OnSmokeGrenadeDetonate( IGameEvent *event )
  1972. {
  1973. CCSBOTMANAGER_ITERATE_BOTS( OnSmokeGrenadeDetonate, event );
  1974. }
  1975. //--------------------------------------------------------------------------------------------------------------
  1976. void CCSBotManager::OnMolotovDetonate( IGameEvent *event )
  1977. {
  1978. CCSBOTMANAGER_ITERATE_BOTS( OnMolotovDetonate, event );
  1979. }
  1980. //--------------------------------------------------------------------------------------------------------------
  1981. void CCSBotManager::OnDecoyDetonate( IGameEvent *event )
  1982. {
  1983. CCSBOTMANAGER_ITERATE_BOTS( OnDecoyDetonate, event );
  1984. }
  1985. //--------------------------------------------------------------------------------------------------------------
  1986. void CCSBotManager::OnDecoyFiring( IGameEvent *event )
  1987. {
  1988. CCSBOTMANAGER_ITERATE_BOTS( OnDecoyFiring, event );
  1989. }
  1990. //--------------------------------------------------------------------------------------------------------------
  1991. void CCSBotManager::OnGrenadeBounce( IGameEvent *event )
  1992. {
  1993. CCSBOTMANAGER_ITERATE_BOTS( OnGrenadeBounce, event );
  1994. }
  1995. //--------------------------------------------------------------------------------------------------------------
  1996. /**
  1997. * Get the time remaining before the planted bomb explodes
  1998. */
  1999. float CCSBotManager::GetBombTimeLeft( void ) const
  2000. {
  2001. return (mp_c4timer.GetFloat() - (gpGlobals->curtime - m_bombPlantTimestamp));
  2002. }
  2003. //--------------------------------------------------------------------------------------------------------------
  2004. void CCSBotManager::SetLooseBomb( CBaseEntity *bomb )
  2005. {
  2006. m_looseBomb = bomb;
  2007. if (bomb)
  2008. {
  2009. m_looseBombArea = TheNavMesh->GetNearestNavArea( bomb->GetAbsOrigin() );
  2010. }
  2011. else
  2012. {
  2013. m_looseBombArea = NULL;
  2014. }
  2015. }
  2016. //--------------------------------------------------------------------------------------------------------------
  2017. /**
  2018. * Return true if player is important to scenario (VIP, bomb carrier, etc)
  2019. */
  2020. bool CCSBotManager::IsImportantPlayer( CCSPlayer *player ) const
  2021. {
  2022. switch (GetScenario())
  2023. {
  2024. case SCENARIO_DEFUSE_BOMB:
  2025. {
  2026. if (player->GetTeamNumber() == TEAM_TERRORIST && player->HasC4())
  2027. return true;
  2028. /// @todo TEAM_CT's defusing the bomb are important
  2029. return false;
  2030. }
  2031. case SCENARIO_ESCORT_VIP:
  2032. {
  2033. if (player->GetTeamNumber() == TEAM_CT && player->IsVIP())
  2034. return true;
  2035. return false;
  2036. }
  2037. case SCENARIO_RESCUE_HOSTAGES:
  2038. {
  2039. /// @todo TEAM_CT's escorting hostages are important
  2040. return false;
  2041. }
  2042. }
  2043. // everyone is equally important in a deathmatch
  2044. return false;
  2045. }
  2046. //--------------------------------------------------------------------------------------------------------------
  2047. /**
  2048. * Return priority of player (0 = max pri)
  2049. */
  2050. unsigned int CCSBotManager::GetPlayerPriority( CBasePlayer *player ) const
  2051. {
  2052. const unsigned int lowestPriority = 0xFFFFFFFF;
  2053. if (!player->IsPlayer())
  2054. return lowestPriority;
  2055. // human players have highest priority
  2056. if (!player->IsBot())
  2057. return 0;
  2058. CCSBot *bot = dynamic_cast<CCSBot *>( player );
  2059. if ( !bot )
  2060. return 0;
  2061. // bots doing something important for the current scenario have high priority
  2062. switch (GetScenario())
  2063. {
  2064. case SCENARIO_DEFUSE_BOMB:
  2065. {
  2066. // the bomb carrier has high priority
  2067. if (bot->GetTeamNumber() == TEAM_TERRORIST && bot->HasC4())
  2068. return 1;
  2069. break;
  2070. }
  2071. case SCENARIO_ESCORT_VIP:
  2072. {
  2073. // the VIP has high priority
  2074. if (bot->GetTeamNumber() == TEAM_CT && bot->m_bIsVIP)
  2075. return 1;
  2076. break;
  2077. }
  2078. case SCENARIO_RESCUE_HOSTAGES:
  2079. {
  2080. // TEAM_CT's rescuing hostages have high priority
  2081. if (bot->GetTeamNumber() == TEAM_CT && bot->GetHostageEscortCount())
  2082. return 1;
  2083. break;
  2084. }
  2085. }
  2086. // everyone else is ranked by their unique ID (which cannot be zero)
  2087. return 1 + bot->GetID();
  2088. }
  2089. //--------------------------------------------------------------------------------------------------------------
  2090. /**
  2091. * Returns a random spawn point for the given team (no arg means use both team spawnpoints)
  2092. */
  2093. CBaseEntity *CCSBotManager::GetRandomSpawn( int team ) const
  2094. {
  2095. CUtlVector< CBaseEntity * > spawnSet;
  2096. CBaseEntity *spot;
  2097. if (team == TEAM_TERRORIST || team == TEAM_MAXCOUNT)
  2098. {
  2099. const char* szTSpawnEntName = "info_player_terrorist";
  2100. if ( CSGameRules()->IsPlayingCoopMission() )
  2101. szTSpawnEntName = "info_enemy_terrorist_spawn";
  2102. // collect T spawns
  2103. for( spot = gEntList.FindEntityByClassname( NULL, szTSpawnEntName );
  2104. spot;
  2105. spot = gEntList.FindEntityByClassname( spot, szTSpawnEntName ) )
  2106. {
  2107. spawnSet.AddToTail( spot );
  2108. }
  2109. }
  2110. if (team == TEAM_CT || team == TEAM_MAXCOUNT)
  2111. {
  2112. // collect CT spawns
  2113. for( spot = gEntList.FindEntityByClassname( NULL, "info_player_counterterrorist" );
  2114. spot;
  2115. spot = gEntList.FindEntityByClassname( spot, "info_player_counterterrorist" ) )
  2116. {
  2117. spawnSet.AddToTail( spot );
  2118. }
  2119. }
  2120. if (spawnSet.Count() == 0)
  2121. {
  2122. return NULL;
  2123. }
  2124. // select one at random
  2125. int which = RandomInt( 0, spawnSet.Count()-1 );
  2126. return spawnSet[ which ];
  2127. }
  2128. //--------------------------------------------------------------------------------------------------------------
  2129. /**
  2130. * Return the last time the given radio message was sent for given team
  2131. * 'teamID' can be TEAM_CT or TEAM_TERRORIST
  2132. */
  2133. float CCSBotManager::GetRadioMessageTimestamp( RadioType event, int teamID ) const
  2134. {
  2135. int i = (teamID == TEAM_TERRORIST) ? 0 : 1;
  2136. if (event > RADIO_START_1 && event < RADIO_END)
  2137. return m_radioMsgTimestamp[ event - RADIO_START_1 ][ i ];
  2138. return 0.0f;
  2139. }
  2140. //--------------------------------------------------------------------------------------------------------------
  2141. /**
  2142. * Return the interval since the last time this message was sent
  2143. */
  2144. float CCSBotManager::GetRadioMessageInterval( RadioType event, int teamID ) const
  2145. {
  2146. int i = (teamID == TEAM_TERRORIST) ? 0 : 1;
  2147. if (event > RADIO_START_1 && event < RADIO_END)
  2148. return gpGlobals->curtime - m_radioMsgTimestamp[ event - RADIO_START_1 ][ i ];
  2149. return 99999999.9f;
  2150. }
  2151. //--------------------------------------------------------------------------------------------------------------
  2152. /**
  2153. * Set the given radio message timestamp.
  2154. * 'teamID' can be TEAM_CT or TEAM_TERRORIST
  2155. */
  2156. void CCSBotManager::SetRadioMessageTimestamp( RadioType event, int teamID )
  2157. {
  2158. int i = (teamID == TEAM_TERRORIST) ? 0 : 1;
  2159. if (event > RADIO_START_1 && event < RADIO_END)
  2160. m_radioMsgTimestamp[ event - RADIO_START_1 ][ i ] = gpGlobals->curtime;
  2161. }
  2162. //--------------------------------------------------------------------------------------------------------------
  2163. /**
  2164. * Reset all radio message timestamps
  2165. */
  2166. void CCSBotManager::ResetRadioMessageTimestamps( void )
  2167. {
  2168. for( int t=0; t<2; ++t )
  2169. {
  2170. for( int m=0; m<(RADIO_END - RADIO_START_1); ++m )
  2171. m_radioMsgTimestamp[ m ][ t ] = 0.0f;
  2172. }
  2173. }
  2174. //--------------------------------------------------------------------------------------------------------------
  2175. /**
  2176. * Display nav areas as they become reachable by each team
  2177. */
  2178. void DrawOccupyTime( void )
  2179. {
  2180. FOR_EACH_VEC( TheNavAreas, it )
  2181. {
  2182. CNavArea *area = TheNavAreas[ it ];
  2183. int r, g, b;
  2184. if (TheCSBots()->GetElapsedRoundTime() > area->GetEarliestOccupyTime( TEAM_TERRORIST ))
  2185. {
  2186. if (TheCSBots()->GetElapsedRoundTime() > area->GetEarliestOccupyTime( TEAM_CT ))
  2187. {
  2188. r = 255; g = 0; b = 255;
  2189. }
  2190. else
  2191. {
  2192. r = 255; g = 0; b = 0;
  2193. }
  2194. }
  2195. else if (TheCSBots()->GetElapsedRoundTime() > area->GetEarliestOccupyTime( TEAM_CT ))
  2196. {
  2197. r = 0; g = 0; b = 255;
  2198. }
  2199. else
  2200. {
  2201. continue;
  2202. }
  2203. const Vector &nw = area->GetCorner( NORTH_WEST );
  2204. const Vector &ne = area->GetCorner( NORTH_EAST );
  2205. const Vector &sw = area->GetCorner( SOUTH_WEST );
  2206. const Vector &se = area->GetCorner( SOUTH_EAST );
  2207. NDebugOverlay::Line( nw, ne, r, g, b, true, 0.1f );
  2208. NDebugOverlay::Line( nw, sw, r, g, b, true, 0.1f );
  2209. NDebugOverlay::Line( se, sw, r, g, b, true, 0.1f );
  2210. NDebugOverlay::Line( se, ne, r, g, b, true, 0.1f );
  2211. }
  2212. }
  2213. //--------------------------------------------------------------------------------------------------------------
  2214. /**
  2215. * Display areas where players will likely have initial battles
  2216. */
  2217. void DrawBattlefront( void )
  2218. {
  2219. const float epsilon = 1.0f;
  2220. int r = 255, g = 50, b = 0;
  2221. FOR_EACH_VEC( TheNavAreas, it )
  2222. {
  2223. CNavArea *area = TheNavAreas[ it ];
  2224. if ( fabs(area->GetEarliestOccupyTime( TEAM_TERRORIST ) - area->GetEarliestOccupyTime( TEAM_CT )) > epsilon )
  2225. {
  2226. continue;
  2227. }
  2228. const Vector &nw = area->GetCorner( NORTH_WEST );
  2229. const Vector &ne = area->GetCorner( NORTH_EAST );
  2230. const Vector &sw = area->GetCorner( SOUTH_WEST );
  2231. const Vector &se = area->GetCorner( SOUTH_EAST );
  2232. NDebugOverlay::Line( nw, ne, r, g, b, true, 0.1f );
  2233. NDebugOverlay::Line( nw, sw, r, g, b, true, 0.1f );
  2234. NDebugOverlay::Line( se, sw, r, g, b, true, 0.1f );
  2235. NDebugOverlay::Line( se, ne, r, g, b, true, 0.1f );
  2236. }
  2237. }
  2238. //--------------------------------------------------------------------------------------------------------------
  2239. static bool CheckAreaAgainstAllZoneAreas(CNavArea *queryArea)
  2240. {
  2241. // A marked area means they just want to double check this one spot
  2242. int goalZoneCount = TheCSBots()->GetZoneCount();
  2243. for( int zoneIndex = 0; zoneIndex < goalZoneCount; zoneIndex++ )
  2244. {
  2245. const CCSBotManager::Zone *currentZone = TheCSBots()->GetZone(zoneIndex);
  2246. int zoneAreaCount = currentZone->m_areaCount;
  2247. for( int areaIndex = 0; areaIndex < zoneAreaCount; areaIndex++ )
  2248. {
  2249. CNavArea *zoneArea = currentZone->m_area[areaIndex];
  2250. // We need to be connected to every area in the zone, since we don't know what other code might pick for an area
  2251. ShortestPathCost cost;
  2252. if( NavAreaTravelDistance(queryArea, zoneArea, cost) == -1.0f )
  2253. {
  2254. Msg( "Area #%d is disconnected from goal area #%d.\n",
  2255. queryArea->GetID(),
  2256. zoneArea->GetID()
  2257. );
  2258. return false;
  2259. }
  2260. }
  2261. }
  2262. return true;
  2263. }
  2264. CON_COMMAND_F( nav_check_connectivity, "Checks to be sure every (or just the marked) nav area can get to every goal area for the map (hostages or bomb site).", FCVAR_CHEAT )
  2265. {
  2266. //Nav command in here since very CS specific.
  2267. if ( !UTIL_IsCommandIssuedByServerAdmin() )
  2268. return;
  2269. if ( TheNavMesh->GetMarkedArea() )
  2270. {
  2271. CNavArea *markedArea = TheNavMesh->GetMarkedArea();
  2272. bool fine = CheckAreaAgainstAllZoneAreas( markedArea );
  2273. if( fine )
  2274. {
  2275. Msg( "Area #%d is connected to all goal areas.\n", markedArea->GetID() );
  2276. }
  2277. }
  2278. else
  2279. {
  2280. // Otherwise, loop through every area, and make sure they can all get to the goal.
  2281. float start = Plat_FloatTime();
  2282. FOR_EACH_VEC( TheNavAreas, nit )
  2283. {
  2284. CheckAreaAgainstAllZoneAreas(TheNavAreas[ nit ]);
  2285. }
  2286. float end = Plat_FloatTime();
  2287. float time = (end - start) * 1000.0f;
  2288. Msg( "nav_check_connectivity took %2.2f ms\n", time );
  2289. }
  2290. }