SpawnBehavior.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  1. /*
  2. ** Command & Conquer Generals Zero Hour(tm)
  3. ** Copyright 2025 Electronic Arts Inc.
  4. **
  5. ** This program is free software: you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License as published by
  7. ** the Free Software Foundation, either version 3 of the License, or
  8. ** (at your option) any later version.
  9. **
  10. ** This program is distributed in the hope that it will be useful,
  11. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ** GNU General Public License for more details.
  14. **
  15. ** You should have received a copy of the GNU General Public License
  16. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. ////////////////////////////////////////////////////////////////////////////////
  19. // //
  20. // (c) 2001-2003 Electronic Arts Inc. //
  21. // //
  22. ////////////////////////////////////////////////////////////////////////////////
  23. // FILE: SpawnBehavior.cpp ////////////////////////////////////////////////////////////////////////
  24. // Author: Graham Smallwood, January 2002
  25. // Desc: Update will create and monitor a group of spawned units and replace as needed
  26. ///////////////////////////////////////////////////////////////////////////////////////////////////
  27. #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
  28. #include "Common/GameState.h"
  29. #include "Common/ThingFactory.h"
  30. #include "Common/ThingTemplate.h"
  31. #include "Common/Player.h"
  32. #include "Common/Xfer.h"
  33. #include "GameLogic/GameLogic.h"
  34. #include "GameLogic/Object.h"
  35. #include "GameLogic/PartitionManager.h"
  36. #include "GameLogic/Module/AIUpdate.h"
  37. #include "GameLogic/Module/SpawnBehavior.h"
  38. #include "GameLogic/Module/BodyModule.h"
  39. #include "GameClient/Drawable.h" //selection logic
  40. #include "GameClient/InGameUI.h" // selection logic
  41. #include "GameLogic/ExperienceTracker.h" //veterancy logic
  42. #include "GameLogic/Module/StealthUpdate.h"
  43. #define NONE_SPAWNED_YET (0xffffffff)
  44. #ifdef _INTERNAL
  45. // for occasional debugging...
  46. //#pragma optimize("", off)
  47. //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
  48. #endif
  49. #define SPAWN_DELAY_MIN_FRAMES (16) // about as rapidly as you'd expect people to successively exit through the same door
  50. //-------------------------------------------------------------------------------------------------
  51. SpawnBehavior::SpawnBehavior( Thing *thing, const ModuleData* moduleData )
  52. : UpdateModule( thing, moduleData )
  53. {
  54. const SpawnBehaviorModuleData* md = getSpawnBehaviorModuleData();
  55. // GEE, THIS IS NEW...
  56. // NOW, WE CAN HAVE A LIST OF TEMPLATE NAMES
  57. m_templateNameIterator = md->m_spawnTemplateNameData.begin();
  58. m_spawnTemplate = TheThingFactory->findTemplate( *m_templateNameIterator );
  59. //each time m_spawn template is used, it will increment m_templateNameIterator,
  60. //thus scanning through the ordered list of template names
  61. //looping back to the beginning
  62. m_framesToWait = 0;
  63. //Added By Sadullah Nader
  64. //Initialization(s) inserted
  65. m_firstBatchCount = 0;
  66. //
  67. if( md->m_isOneShotData )
  68. m_oneShotCountdown = md->m_spawnNumberData;
  69. else
  70. m_oneShotCountdown = -1;
  71. m_active = TRUE;
  72. m_replacementTimes.clear();
  73. // The initializing of the initial bursters is handled in the first update @todo invent an object::postConstructionProcess() some day
  74. m_initialBurstCountdown = md->m_initialBurst;
  75. m_initialBurstTimesInited = FALSE;
  76. m_aggregateHealth = md->m_aggregateHealth;
  77. m_spawnCount = NONE_SPAWNED_YET;
  78. m_active = TRUE;
  79. m_selfTaskingSpawnCount = 0;
  80. }
  81. //-------------------------------------------------------------------------------------------------
  82. SpawnBehavior::~SpawnBehavior( void )
  83. {
  84. m_replacementTimes.clear();
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. void SpawnBehavior::onDelete()
  88. {
  89. const SpawnBehaviorModuleData *modData = getSpawnBehaviorModuleData();
  90. // destroy anything that we have spawned that is not already dead
  91. if( modData->m_spawnedRequireSpawner )
  92. {
  93. Object *obj;
  94. for( objectIDListIterator it = m_spawnIDs.begin(); it != m_spawnIDs.end(); /*empty*/ )
  95. {
  96. // get object
  97. obj = TheGameLogic->findObjectByID( *it );
  98. // increment iterator incase the id list is alterd because what we're about to do
  99. ++it;
  100. //
  101. // destroy this if it's alive, in the usual case this object "dies" and is
  102. // not "destroyed". on *death* we *KILL* our spawned things, but this is here
  103. // and will *DESTROY* our spawned things if we ourselves are destroyed and they
  104. // are still alive (such a case would be calling destroy object on us directly)
  105. //
  106. if( obj && obj->isEffectivelyDead() == FALSE )
  107. TheGameLogic->destroyObject( obj );
  108. } // end for, it
  109. } // end if
  110. }
  111. // ------------------------------------------------------------------------------------------------
  112. void SpawnBehavior::onDie( const DamageInfo *damageInfo )
  113. {
  114. const SpawnBehaviorModuleData *modData = getSpawnBehaviorModuleData();
  115. ///@todo isDieApplicable should be called outside of the onDie call
  116. if( modData->m_dieMuxData.isDieApplicable( getObject(), damageInfo ) == FALSE )
  117. return;
  118. for( objectIDListIterator iter = m_spawnIDs.begin();
  119. iter != m_spawnIDs.end();
  120. iter++
  121. )
  122. {
  123. Object *currentSpawn = TheGameLogic->findObjectByID( (*iter) );
  124. if( currentSpawn )
  125. {
  126. // Go through all my spawns and see if they have a SlavedUpdate I can tell I was killed to
  127. for (BehaviorModule** update = currentSpawn->getBehaviorModules(); *update; ++update)
  128. {
  129. SlavedUpdateInterface* sdu = (*update)->getSlavedUpdateInterface();
  130. if (sdu != NULL)
  131. {
  132. sdu->onSlaverDie( damageInfo );
  133. break;
  134. }
  135. }
  136. // our spawner has died, we must invalidate the ID now in the spawned object
  137. currentSpawn->setProducer( NULL );
  138. }
  139. }
  140. // kill anything that we have spawned if our module data directs us to do so
  141. if( modData->m_spawnedRequireSpawner )
  142. {
  143. Object *obj;
  144. for( objectIDListIterator it = m_spawnIDs.begin(); it != m_spawnIDs.end(); /*emtpy*/ )
  145. {
  146. // get object
  147. obj = TheGameLogic->findObjectByID( *it );
  148. // increment iterator incase the id list is alterd because what we're about to do
  149. ++it;
  150. // kill it if not already dead
  151. if( obj && obj->isEffectivelyDead() == FALSE )
  152. obj->kill();
  153. } // end for, it
  154. } // end if
  155. }
  156. //-------------------------------------------------------------------------------------------------
  157. UpdateSleepTime SpawnBehavior::update( void )
  158. {
  159. /// @todo srj use SLEEPY_UPDATE here
  160. //EVERY FRAME
  161. if ( m_aggregateHealth )
  162. {
  163. computeAggregateStates();
  164. }
  165. const SpawnBehaviorModuleData* md = getSpawnBehaviorModuleData();
  166. if ( ! m_initialBurstTimesInited )
  167. {
  168. m_initialBurstTimesInited = TRUE;
  169. Bool runtimeProduced = getObject()->getProducerID()!=INVALID_ID; //this was produced by a production module, rather than a script or worldbuilder
  170. Int now = TheGameLogic->getFrame();
  171. Int burstInitCount = m_initialBurstCountdown;
  172. for( int listIndex = 0; listIndex < md->m_spawnNumberData; listIndex++ )
  173. {
  174. if ( md->m_initialBurst > 0 )
  175. {
  176. UnsignedInt birthFrame = now;
  177. if ( runtimeProduced && burstInitCount > 0)
  178. {
  179. --burstInitCount;
  180. birthFrame += (listIndex*SPAWN_DELAY_MIN_FRAMES);
  181. }
  182. m_replacementTimes.push_back( runtimeProduced );// Set all spawns to be created in rapid succession
  183. }
  184. else
  185. m_replacementTimes.push_back( listIndex );// Set all spawns to be created as soon as possible
  186. }
  187. }
  188. //SPARSELY SOLVED
  189. if (--m_framesToWait > 0)
  190. {
  191. return UPDATE_SLEEP_NONE;
  192. }
  193. m_framesToWait = SPAWN_UPDATE_RATE;
  194. //Go through the list and make a spawn for each number that is less than now's frame
  195. if( shouldTryToSpawn() )
  196. {
  197. // Due to STL's list vomiting when you erase in a for loop,
  198. // Start at the beginning, and if you erase one, use the return
  199. // value to manually step to the next. Otherwise, step by yourself.
  200. // begin == end means empty list, so no special check is needed.
  201. intListIterator iterator = m_replacementTimes.begin();
  202. while( iterator != m_replacementTimes.end() )
  203. {
  204. Int replacementTime = *iterator;
  205. UnsignedInt currentTime = TheGameLogic->getFrame();
  206. if( currentTime > replacementTime )
  207. {
  208. //If you create one, you pop the number off the list
  209. if( createSpawn() )
  210. iterator = m_replacementTimes.erase( iterator );
  211. else
  212. iterator++;
  213. }
  214. else
  215. iterator++;
  216. }
  217. if( md->m_isOneShotData && (m_oneShotCountdown <= 0) )
  218. stopSpawning(); //I only trigger one batch. ie on Creation.
  219. }
  220. return UPDATE_SLEEP_NONE;
  221. }
  222. // ------------------------------------------------------------------------------------------------
  223. Bool SpawnBehavior::maySpawnSelfTaskAI( Real maxSelfTaskersRatio )
  224. {
  225. if ( m_spawnCount == 0)
  226. return FALSE;
  227. if ( maxSelfTaskersRatio == 0)
  228. return FALSE;
  229. //if my last attack command was from player or script, I need to forbid my spawn from disobeying that command
  230. //otherwise (since my attack state was autoacquired my ny own ai), let them deviate by the ratio specified.
  231. Object* obj = getObject();
  232. if ( ! obj )
  233. return FALSE;
  234. AIUpdateInterface *ai = obj->getAI();
  235. if ( ! ai )
  236. return FALSE;
  237. CommandSourceType lastAttackCommandSource = ai->getLastCommandSource();
  238. if ( lastAttackCommandSource != CMD_FROM_AI )
  239. return FALSE;
  240. Real curSelfTaskersRatio = (Real)m_selfTaskingSpawnCount / (Real)m_spawnCount;
  241. return ( curSelfTaskersRatio < maxSelfTaskersRatio );
  242. }
  243. // ------------------------------------------------------------------------------------------------
  244. Object* SpawnBehavior::getClosestSlave( const Coord3D *pos )
  245. {
  246. Object *closest = NULL;
  247. Real closestDistance;
  248. for( objectIDListIterator it = m_spawnIDs.begin(); it != m_spawnIDs.end(); ++it )
  249. {
  250. Object *obj = TheGameLogic->findObjectByID( *it );
  251. if( obj )
  252. {
  253. Real distance = ThePartitionManager->getDistanceSquared( obj, pos, FROM_CENTER_2D );
  254. if( !closest || closestDistance > distance )
  255. {
  256. closest = obj;
  257. closestDistance = distance;
  258. }
  259. }
  260. }
  261. return closest; //Could be null!
  262. }
  263. // ------------------------------------------------------------------------------------------------
  264. void SpawnBehavior::orderSlavesToAttackTarget( Object *target, Int maxShotsToFire, CommandSourceType cmdSource )
  265. {
  266. for( objectIDListIterator it = m_spawnIDs.begin(); it != m_spawnIDs.end(); ++it )
  267. {
  268. Object *obj = TheGameLogic->findObjectByID( *it );
  269. if( obj )
  270. {
  271. AIUpdateInterface *ai = obj->getAI();
  272. if( ai )
  273. {
  274. ai->aiForceAttackObject( target, maxShotsToFire, cmdSource );
  275. }
  276. }
  277. }
  278. }
  279. // ------------------------------------------------------------------------------------------------
  280. void SpawnBehavior::orderSlavesToAttackPosition( const Coord3D *pos, Int maxShotsToFire, CommandSourceType cmdSource )
  281. {
  282. for( objectIDListIterator it = m_spawnIDs.begin(); it != m_spawnIDs.end(); ++it )
  283. {
  284. Object *obj = TheGameLogic->findObjectByID( *it );
  285. if( obj )
  286. {
  287. AIUpdateInterface *ai = obj->getAI();
  288. if( ai )
  289. {
  290. ai->aiAttackPosition( pos, maxShotsToFire, cmdSource );
  291. }
  292. }
  293. }
  294. }
  295. // ------------------------------------------------------------------------------------------------
  296. void SpawnBehavior::orderSlavesToGoIdle( CommandSourceType cmdSource )
  297. {
  298. for( objectIDListIterator it = m_spawnIDs.begin(); it != m_spawnIDs.end(); ++it )
  299. {
  300. Object *obj = TheGameLogic->findObjectByID( *it );
  301. if( obj )
  302. {
  303. AIUpdateInterface *ai = obj->getAI();
  304. if( ai )
  305. {
  306. ai->aiIdle( cmdSource );
  307. }
  308. }
  309. }
  310. }
  311. // ------------------------------------------------------------------------------------------------
  312. void SpawnBehavior::orderSlavesDisabledUntil( DisabledType type, UnsignedInt frame )
  313. {
  314. for( objectIDListIterator it = m_spawnIDs.begin(); it != m_spawnIDs.end(); ++it )
  315. {
  316. Object *obj = TheGameLogic->findObjectByID( *it );
  317. if( obj )
  318. {
  319. AIUpdateInterface *ai = obj->getAI();
  320. if( ai )
  321. {
  322. ai->aiIdle( CMD_FROM_AI );
  323. }
  324. obj->setDisabledUntil( type, frame );
  325. }
  326. }
  327. }
  328. // ------------------------------------------------------------------------------------------------
  329. void SpawnBehavior::orderSlavesToClearDisabled( DisabledType type )
  330. {
  331. for( objectIDListIterator it = m_spawnIDs.begin(); it != m_spawnIDs.end(); ++it )
  332. {
  333. Object *obj = TheGameLogic->findObjectByID( *it );
  334. if( obj )
  335. {
  336. obj->clearDisabled( type );
  337. }
  338. }
  339. }
  340. // ------------------------------------------------------------------------------------------------
  341. CanAttackResult SpawnBehavior::getCanAnySlavesAttackSpecificTarget( AbleToAttackType attackType, const Object *target, CommandSourceType cmdSource )
  342. {
  343. Bool invalidShot = FALSE;
  344. for( objectIDListIterator it = m_spawnIDs.begin(); it != m_spawnIDs.end(); ++it )
  345. {
  346. Object *obj = TheGameLogic->findObjectByID( *it );
  347. if( obj )
  348. {
  349. CanAttackResult result = obj->getAbleToAttackSpecificObject( attackType, target, cmdSource );
  350. switch( result )
  351. {
  352. case ATTACKRESULT_POSSIBLE:
  353. case ATTACKRESULT_POSSIBLE_AFTER_MOVING:
  354. return result;
  355. case ATTACKRESULT_NOT_POSSIBLE:
  356. break;
  357. case ATTACKRESULT_INVALID_SHOT:
  358. invalidShot = TRUE;
  359. break;
  360. default:
  361. DEBUG_CRASH( ("SpawnBehavior::getCanAnySlavesAttackSpecificTarget encountered unhandled CanAttackResult of %d. Treating as not possible...", result) );
  362. break;
  363. }
  364. }
  365. }
  366. //Prioritize the reasonings!
  367. if( invalidShot )
  368. {
  369. return ATTACKRESULT_INVALID_SHOT;
  370. }
  371. return ATTACKRESULT_NOT_POSSIBLE;
  372. }
  373. // ------------------------------------------------------------------------------------------------
  374. CanAttackResult SpawnBehavior::getCanAnySlavesUseWeaponAgainstTarget( AbleToAttackType attackType, const Object *victim, const Coord3D *pos, CommandSourceType cmdSource )
  375. {
  376. Bool invalidShot = FALSE;
  377. for( objectIDListIterator it = m_spawnIDs.begin(); it != m_spawnIDs.end(); ++it )
  378. {
  379. Object *obj = TheGameLogic->findObjectByID( *it );
  380. if( obj )
  381. {
  382. CanAttackResult result = obj->getAbleToUseWeaponAgainstTarget( attackType, victim, pos, cmdSource );
  383. switch( result )
  384. {
  385. case ATTACKRESULT_POSSIBLE:
  386. case ATTACKRESULT_POSSIBLE_AFTER_MOVING:
  387. return result;
  388. case ATTACKRESULT_NOT_POSSIBLE:
  389. break;
  390. case ATTACKRESULT_INVALID_SHOT:
  391. invalidShot = TRUE;
  392. break;
  393. default:
  394. DEBUG_CRASH( ("SpawnBehavior::getCanAnySlavesUseWeaponAgainstTarget encountered unhandled CanAttackResult of %d. Treating as not possible...", result) );
  395. break;
  396. }
  397. }
  398. }
  399. //Prioritize the reasonings!
  400. if( invalidShot )
  401. {
  402. return ATTACKRESULT_INVALID_SHOT;
  403. }
  404. return ATTACKRESULT_NOT_POSSIBLE;
  405. }
  406. // ------------------------------------------------------------------------------------------------
  407. void SpawnBehavior::giveSlavesStealthUpgrade( Bool grantStealth )
  408. {
  409. for( objectIDListIterator it = m_spawnIDs.begin(); it != m_spawnIDs.end(); ++it )
  410. {
  411. Object *obj = TheGameLogic->findObjectByID( *it );
  412. if( obj )
  413. {
  414. obj->setStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_CAN_STEALTH ), grantStealth );
  415. }
  416. }
  417. }
  418. // ------------------------------------------------------------------------------------------------
  419. Bool SpawnBehavior::canAnySlavesAttack()
  420. {
  421. for( objectIDListIterator it = m_spawnIDs.begin(); it != m_spawnIDs.end(); ++it )
  422. {
  423. Object *obj = TheGameLogic->findObjectByID( *it );
  424. if( obj )
  425. {
  426. if( obj->isAbleToAttack() )
  427. {
  428. return true;
  429. }
  430. }
  431. }
  432. return false;
  433. }
  434. // ------------------------------------------------------------------------------------------------
  435. // ------------------------------------------------------------------------------------------------
  436. class OrphanData
  437. {
  438. public:
  439. OrphanData( void );
  440. const ThingTemplate *m_matchTemplate;
  441. Object *m_source;
  442. Object *m_closest;
  443. Real m_closestDistSq;
  444. };
  445. #define BIG_DISTANCE 99999999.9f
  446. // ------------------------------------------------------------------------------------------------
  447. // ------------------------------------------------------------------------------------------------
  448. OrphanData::OrphanData( void )
  449. {
  450. m_matchTemplate = NULL;
  451. m_source = NULL;
  452. m_closest = NULL;
  453. m_closestDistSq = BIG_DISTANCE;
  454. }
  455. // ------------------------------------------------------------------------------------------------
  456. static void findClosestOrphan( Object *obj, void *userData )
  457. {
  458. OrphanData *orphanData = (OrphanData *)userData;
  459. // if template doesn't match do nothing
  460. if( obj->getTemplate()->isEquivalentTo( orphanData->m_matchTemplate ) == FALSE )
  461. return;
  462. // this object must be orphaned
  463. if( obj->getProducerID() != INVALID_ID )
  464. return;
  465. // is this the closest one so far
  466. Real distSq = ThePartitionManager->getDistanceSquared( orphanData->m_source, obj, FROM_CENTER_2D );
  467. if( distSq < orphanData->m_closestDistSq )
  468. {
  469. orphanData->m_closest = obj;
  470. orphanData->m_closestDistSq = distSq;
  471. } // end if
  472. } // findClosestOrphan
  473. // ------------------------------------------------------------------------------------------------
  474. Object *SpawnBehavior::reclaimOrphanSpawn( void )
  475. {
  476. Player *player = getObject()->getControllingPlayer();
  477. const SpawnBehaviorModuleData *md = getSpawnBehaviorModuleData();
  478. //
  479. // iterate all the objects my controlling player has and look for any orphaned things
  480. // that we would normally spawn, if found we'll just make it our own
  481. //
  482. // EVEN MORE NEW AND DIFFERENT
  483. // This block scans the list for matchTemplates
  484. //
  485. OrphanData orphanData;
  486. AsciiString prevName = "";
  487. for (std::vector<AsciiString>::const_iterator tempName = md->m_spawnTemplateNameData.begin();
  488. tempName != md->m_spawnTemplateNameData.end();
  489. ++tempName)
  490. {
  491. if (prevName.compare(*tempName)) // the list may have redundancy, this will skip some of it
  492. continue;
  493. orphanData.m_matchTemplate = TheThingFactory->findTemplate( *tempName );;
  494. orphanData.m_source = getObject();
  495. orphanData.m_closest = NULL;
  496. orphanData.m_closestDistSq = BIG_DISTANCE;
  497. player->iterateObjects( findClosestOrphan, &orphanData );
  498. prevName = *tempName;
  499. }
  500. return orphanData.m_closest;
  501. }
  502. //-------------------------------------------------------------------------------------------------
  503. Bool SpawnBehavior::createSpawn()
  504. {
  505. Object *parent = getObject();
  506. const SpawnBehaviorModuleData *md = getSpawnBehaviorModuleData();
  507. ExitInterface* exitInterface = parent->getObjectExitInterface();
  508. if( exitInterface == NULL )
  509. {
  510. DEBUG_ASSERTCRASH( exitInterface != NULL, ("Something cannot have SpawnBehavior without an exit interface") );
  511. return FALSE;
  512. }
  513. ExitDoorType exitDoor = exitInterface->reserveDoorForExit(NULL, NULL);
  514. if (exitDoor == DOOR_NONE_AVAILABLE)
  515. return FALSE;
  516. Object *newSpawn = NULL;
  517. // try to reclaim orphaned objects if possible
  518. Bool reclaimedOrphan = FALSE;
  519. if( md->m_canReclaimOrphans && md->m_isOneShotData == FALSE )
  520. {
  521. newSpawn = reclaimOrphanSpawn();
  522. if( newSpawn )
  523. reclaimedOrphan = TRUE;
  524. }
  525. // This assures that an orphan has not just been reclaimed,
  526. if( newSpawn == NULL ) // and that we really want a new spawn, here.
  527. {
  528. m_spawnTemplate = TheThingFactory->findTemplate( *m_templateNameIterator );
  529. //newSpawn = TheThingFactory->newObject( m_spawnTemplate, parent->getControllingPlayer()->getDefaultTeam() );
  530. newSpawn = TheThingFactory->newObject( m_spawnTemplate, parent->getTeam() ); // just a little worried about this...
  531. // Count this unit towards our score.
  532. newSpawn->getControllingPlayer()->onUnitCreated(parent, newSpawn);
  533. // Gee, this is new...
  534. // Now, we can have a list of template names.
  535. // Each time m_spawn template is used, it will increment m_templateNameIterator,
  536. // thus scanning through the ordered list of template names, and
  537. // looping back to the beginning
  538. ++m_templateNameIterator;
  539. if ( m_templateNameIterator == md->m_spawnTemplateNameData.end())
  540. {
  541. m_templateNameIterator = md->m_spawnTemplateNameData.begin();
  542. }
  543. }
  544. newSpawn->setProducer(parent);
  545. // If they have a SlavedUpdate, then I have to tell them who their daddy is from now on.
  546. for (BehaviorModule** update = newSpawn->getBehaviorModules(); *update; ++update)
  547. {
  548. SlavedUpdateInterface* sdu = (*update)->getSlavedUpdateInterface();
  549. if (sdu != NULL)
  550. {
  551. sdu->onEnslave( parent );
  552. break;
  553. }
  554. }
  555. m_spawnIDs.push_back( newSpawn->getID() );
  556. if( reclaimedOrphan == FALSE )
  557. {
  558. if ( md->m_exitByBudding )
  559. {
  560. Bool barracksExitSuccess = FALSE;
  561. if ( m_initialBurstCountdown > 0 )
  562. {
  563. Object *barracks = TheGameLogic->findObjectByID( parent->getProducerID() );
  564. if ( barracks && barracks->isKindOf( KINDOF_STRUCTURE ) )
  565. {
  566. ExitInterface* barracksExitInterface = barracks->getObjectExitInterface();
  567. if ( barracksExitInterface )
  568. {
  569. ExitDoorType barracksDoor = barracksExitInterface->reserveDoorForExit(NULL, NULL);
  570. barracksExitInterface->exitObjectViaDoor( newSpawn, barracksDoor );
  571. newSpawn->setProducer(parent);//let parents producer exit him, but he thinks it was me
  572. --m_initialBurstCountdown;
  573. barracksExitSuccess = TRUE;
  574. }
  575. }
  576. }
  577. if ( ! barracksExitSuccess )
  578. {
  579. // find the closest spawn to the nexus...
  580. //there is probably a more elegant way to choose the budHost, but oh well
  581. Object *budHost = NULL;
  582. Object *curSpawn = NULL;
  583. Real tapeMeasure = 99999;
  584. Real closest = 999999.9f; // 1000 * 1000
  585. objectIDListIterator iter;
  586. for( iter = m_spawnIDs.begin(); iter != m_spawnIDs.end(); iter++)
  587. {
  588. curSpawn = TheGameLogic->findObjectByID( *iter );
  589. if ( curSpawn )
  590. {
  591. if (curSpawn == newSpawn )
  592. continue;
  593. tapeMeasure = ThePartitionManager->getDistanceSquared( curSpawn, parent, FROM_CENTER_2D );
  594. if ( tapeMeasure < closest )
  595. {
  596. closest = tapeMeasure;
  597. budHost = curSpawn;
  598. }
  599. }
  600. }
  601. exitInterface->exitObjectByBudding( newSpawn, budHost );// also handles the NULL pointer okay
  602. }
  603. }
  604. else
  605. {
  606. exitInterface->exitObjectViaDoor( newSpawn, exitDoor );
  607. }
  608. }
  609. else
  610. exitInterface->unreserveDoorForExit( exitDoor );
  611. if( md->m_isOneShotData )
  612. m_oneShotCountdown--;
  613. if ( m_spawnCount == NONE_SPAWNED_YET )
  614. {
  615. m_spawnCount = 1;
  616. }
  617. else
  618. {
  619. ++ m_spawnCount;
  620. }
  621. return TRUE;
  622. }
  623. //-------------------------------------------------------------------------------------------------
  624. void SpawnBehavior::onSpawnDeath( ObjectID deadSpawn, DamageInfo *damageInfo )
  625. {
  626. objectIDListIterator it = std::find(m_spawnIDs.begin(), m_spawnIDs.end(), deadSpawn);
  627. // If the iterator is at the end, we didn't find deadSpawn, so bail out.
  628. // Otherwise, bad crash stuff will happen.
  629. if (it == m_spawnIDs.end())
  630. return;
  631. //When one dies, you push (now + delay) as the time a new one should be made
  632. const SpawnBehaviorModuleData* md = getSpawnBehaviorModuleData();
  633. Int replacementTime = md->m_spawnReplaceDelayData + TheGameLogic->getFrame();
  634. m_replacementTimes.push_back( replacementTime );
  635. m_spawnIDs.erase( it );
  636. --m_spawnCount;
  637. if ( (m_spawnCount == 0) && m_aggregateHealth) // I'm dead without my spawn
  638. {
  639. Object *killer = TheGameLogic->findObjectByID(damageInfo->in.m_sourceID);
  640. if (killer != NULL) {
  641. killer->scoreTheKill(getObject());
  642. }
  643. TheGameLogic->destroyObject(getObject());
  644. //getObject()->kill();
  645. return;
  646. }
  647. }
  648. //-------------------------------------------------------------------------------------------------
  649. void SpawnBehavior::stopSpawning()
  650. {
  651. m_active = FALSE;
  652. }
  653. //-------------------------------------------------------------------------------------------------
  654. void SpawnBehavior::startSpawning()
  655. {
  656. m_active = TRUE;
  657. }
  658. //-------------------------------------------------------------------------------------------------
  659. /** When I become damaged */
  660. // ------------------------------------------------------------------------------------------------
  661. void SpawnBehavior::onDamage( DamageInfo *info )
  662. {
  663. for( objectIDListIterator iter = m_spawnIDs.begin();
  664. iter != m_spawnIDs.end();
  665. iter++
  666. )
  667. {
  668. Object *currentSpawn = TheGameLogic->findObjectByID( (*iter) );
  669. if( currentSpawn )
  670. {
  671. // Go through all my spawns and see if they have a SlavedUpdate I can tell I was hurt to
  672. for (BehaviorModule** update = currentSpawn->getBehaviorModules(); *update; ++update)
  673. {
  674. SlavedUpdateInterface* sdu = (*update)->getSlavedUpdateInterface();
  675. if (sdu != NULL)
  676. {
  677. sdu->onSlaverDamage( info );
  678. break;
  679. }
  680. }
  681. }
  682. }
  683. }
  684. // ------------------------------------------------------------------------------------------------
  685. // ------------------------------------------------------------------------------------------------
  686. Bool SpawnBehavior::shouldTryToSpawn()
  687. {
  688. const SpawnBehaviorModuleData *modData = getSpawnBehaviorModuleData();
  689. // Not if we are turned off
  690. if( !m_active )
  691. return FALSE;
  692. if( getObject()->getStatusBits().test( OBJECT_STATUS_RECONSTRUCTING ) && modData->m_isOneShotData )
  693. {
  694. // If we are a Hole rebuild, not only should we not, but we should never ask again.
  695. stopSpawning();
  696. return FALSE;
  697. }
  698. // Not if we are under construction or being sold
  699. if( getObject()->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION) || getObject()->testStatus(OBJECT_STATUS_SOLD) )
  700. return FALSE;
  701. // Not if we are civilian controlled
  702. if( getObject()->isNeutralControlled() )
  703. return FALSE;
  704. return TRUE;
  705. }
  706. //********************************************************************
  707. //* This function allows various object states to be either inherited
  708. //* from the spawner to the spawn, or vice versa
  709. //* Selection is distributed across all spawn and spawner at once
  710. //* Health for the spawner is calc'd by aggregating the sum of all
  711. //* spawn health, and dividing by optimal health of full population
  712. //* (that is, the max spawn, SpawnBehaviorModuleData::m_spawnNumberData)
  713. //* at full health.
  714. //* Veterancy is sucked out of any unit that has any and put into the
  715. //* Spawner, scaled by 1/SpawnBehaviorModuleData::m_spawnNumberData;
  716. //* The HealthBoxPosition (maybe to include moodicon, vet icon) is calc'd
  717. //* as an average position of all the spawn.
  718. //********************************************************************
  719. void SpawnBehavior::computeAggregateStates(void)
  720. {
  721. if ( ! m_aggregateHealth ) // sanity
  722. return;
  723. Object* obj = getObject();
  724. const SpawnBehaviorModuleData* md = getSpawnBehaviorModuleData();
  725. Int spawnCount = 0;
  726. Int spawnCountMax = md->m_spawnNumberData;
  727. Coord3D avgSpawnPos;
  728. avgSpawnPos.set(0,0,0);
  729. Real acrHealth = 0.0f;
  730. Real avgHealthMax = 0.0f;
  731. ExperienceTracker *expTracker = obj->getExperienceTracker();
  732. VeterancyLevel vetLevel = expTracker->getVeterancyLevel();
  733. Bool SomebodyIsSelected = FALSE;
  734. Bool SomebodyIsNotSelected = FALSE;
  735. Drawable *spawnDraw = NULL;
  736. Object *currentSpawn = NULL;
  737. WeaponBonusConditionFlags spawnWeaponBonus;
  738. m_selfTaskingSpawnCount = 0;
  739. for( objectIDListIterator iter = m_spawnIDs.begin(); iter != m_spawnIDs.end(); iter++)
  740. {
  741. currentSpawn = TheGameLogic->findObjectByID( (*iter) );
  742. if( currentSpawn )
  743. {
  744. //m_selfTaskingSpawnCount += ( currentSpawn->isSelf);
  745. for (BehaviorModule** update = currentSpawn->getBehaviorModules(); *update; ++update)
  746. {
  747. SlavedUpdateInterface* sdu = (*update)->getSlavedUpdateInterface();
  748. if (sdu != NULL)
  749. {
  750. m_selfTaskingSpawnCount += ( sdu->isSelfTasking());;
  751. break;
  752. }
  753. }
  754. // VETERANCY LEVEL *************************************
  755. VeterancyLevel spawnVetLevel = currentSpawn->getVeterancyLevel();
  756. if ( spawnVetLevel > vetLevel) // whoever has more, set the other guy
  757. {
  758. expTracker->setVeterancyLevel(spawnVetLevel);
  759. }
  760. else if ( spawnVetLevel < vetLevel) // whoever has more, set the other guy
  761. {
  762. currentSpawn->getExperienceTracker()->setVeterancyLevel(vetLevel);
  763. }
  764. spawnWeaponBonus = currentSpawn->getWeaponBonusCondition();
  765. avgSpawnPos.add(currentSpawn->getPosition());
  766. BodyModuleInterface *body = currentSpawn->getBodyModule();
  767. acrHealth += body->getHealth();
  768. avgHealthMax += body->getMaxHealth();
  769. spawnDraw = currentSpawn->getDrawable();
  770. if ( spawnDraw->isSelected() )
  771. {
  772. SomebodyIsSelected = TRUE;
  773. }
  774. else
  775. {
  776. SomebodyIsNotSelected = TRUE;
  777. }
  778. spawnCount++;
  779. }
  780. } // next iter
  781. // SELECTION STATE *****************************************
  782. // THIS LOGIC IS SIMPLE
  783. // IF ANY ONE OF MY SPAWN ARE SELECTED RIGHT NOW,
  784. // I JUST SET THEM ALL SELECTED
  785. // THIS WAY WE ARE ALWAYS ONE BIG HAPPY MOB
  786. // BUT I ONLY PROCEED IF THERE IS ONE AMONG ALL OF US WHO IS NOT SELECTED
  787. if ( SomebodyIsSelected && ( ! obj->getDrawable()->isSelected() || SomebodyIsNotSelected ) )
  788. {
  789. GameMessage *teamMsg = TheMessageStream->appendMessage( GameMessage::MSG_CREATE_SELECTED_GROUP );
  790. teamMsg->appendBooleanArgument( FALSE );// not creating new team so pass false
  791. if ( SomebodyIsNotSelected ) // lets select everybody
  792. {
  793. for( objectIDListIterator iter = m_spawnIDs.begin(); iter != m_spawnIDs.end(); iter++)
  794. {
  795. currentSpawn = TheGameLogic->findObjectByID( (*iter) );
  796. if( currentSpawn )
  797. {
  798. spawnDraw = currentSpawn->getDrawable();
  799. if ( ! spawnDraw->isSelected())
  800. {
  801. TheInGameUI->selectDrawable( spawnDraw );
  802. TheInGameUI->setDisplayedMaxWarning( FALSE );
  803. teamMsg->appendBooleanArgument( FALSE );// not creating new team so pass false
  804. teamMsg->appendObjectIDArgument( currentSpawn->getID() );
  805. }
  806. }
  807. } // next iter
  808. }
  809. // if somebody is selected then I sure need to be!
  810. if ( ! obj->getDrawable()->isSelected())
  811. {
  812. TheInGameUI->selectDrawable( obj->getDrawable() );
  813. TheInGameUI->setDisplayedMaxWarning( FALSE );
  814. teamMsg->appendBooleanArgument( FALSE );// not creating new team so pass false
  815. teamMsg->appendObjectIDArgument( obj->getID() );
  816. }
  817. }
  818. // HEALTH BOX POSITION *****************************
  819. // pick a centered, average spot to draw the health box
  820. avgSpawnPos.scale(1.0f / spawnCount);
  821. avgSpawnPos.sub(obj->getPosition());
  822. obj->setHealthBoxOffset(avgSpawnPos);
  823. // HEALTH STATE *************************************
  824. // make my health an aggregate of all my spawns' healths
  825. if ( spawnCount )
  826. {
  827. avgHealthMax /= spawnCount;
  828. Real perfectTotalHealth = avgHealthMax * spawnCountMax;
  829. Real actualHealth = acrHealth / perfectTotalHealth;
  830. obj->getBodyModule()->setInitialHealth(100.0f * actualHealth);
  831. }
  832. else
  833. {
  834. obj->getBodyModule()->setInitialHealth(0);// I been sick <
  835. }
  836. // HOUSEKEEPING *************************************
  837. //make sure no enemies are shooting at the nexus, since it doesn't 'exist'
  838. obj->setStatus( MAKE_OBJECT_STATUS_MASK( OBJECT_STATUS_MASKED ) );
  839. }
  840. //-------------------------------------------------------------------------------------------------
  841. Bool SpawnBehavior::areAllSlavesStealthed() const
  842. {
  843. Object *currentSpawn;
  844. for( std::list<ObjectID>::const_iterator iter = m_spawnIDs.begin(); iter != m_spawnIDs.end(); iter++)
  845. {
  846. currentSpawn = TheGameLogic->findObjectByID( (*iter) );
  847. if( currentSpawn )
  848. {
  849. const StealthUpdate *stealthUpdate = currentSpawn->getStealth();
  850. if( !stealthUpdate || !stealthUpdate->allowedToStealth( currentSpawn ) )
  851. {
  852. return FALSE;
  853. }
  854. }
  855. }
  856. return TRUE; //0 or more spawns are ALL stealthed... I suppose if you have NO spawns, then they are considered stealthed ;)
  857. }
  858. //-------------------------------------------------------------------------------------------------
  859. void SpawnBehavior::revealSlaves()
  860. {
  861. Object *currentSpawn;
  862. for( objectIDListIterator iter = m_spawnIDs.begin(); iter != m_spawnIDs.end(); iter++)
  863. {
  864. currentSpawn = TheGameLogic->findObjectByID( (*iter) );
  865. if( currentSpawn )
  866. {
  867. StealthUpdate *stealthUpdate = currentSpawn->getStealth();
  868. if( stealthUpdate )
  869. {
  870. stealthUpdate->markAsDetected();
  871. }
  872. }
  873. }
  874. }
  875. // ------------------------------------------------------------------------------------------------
  876. /** CRC */
  877. // ------------------------------------------------------------------------------------------------
  878. void SpawnBehavior::crc( Xfer *xfer )
  879. {
  880. // extend base class
  881. BehaviorModule::crc( xfer );
  882. } // end crc
  883. // ------------------------------------------------------------------------------------------------
  884. /** Xfer method
  885. * Version Info:
  886. * 1: Initial version
  887. * 2: Added m_initialBurstTimesInited to the save. jba.
  888. */
  889. // ------------------------------------------------------------------------------------------------
  890. void SpawnBehavior::xfer( Xfer *xfer )
  891. {
  892. AsciiString name;
  893. // version
  894. XferVersion currentVersion = 2;
  895. XferVersion version = currentVersion;
  896. xfer->xferVersion( &version, currentVersion );
  897. // extend base class
  898. BehaviorModule::xfer( xfer );
  899. if (version >= 2) {
  900. xfer->xferBool(&m_initialBurstTimesInited);
  901. }
  902. // spawn template
  903. name = m_spawnTemplate ? m_spawnTemplate->getName() : AsciiString::TheEmptyString;
  904. xfer->xferAsciiString( &name );
  905. if( xfer->getXferMode() == XFER_LOAD )
  906. {
  907. m_spawnTemplate = NULL;
  908. if( name.isEmpty() == FALSE )
  909. {
  910. m_spawnTemplate = TheThingFactory->findTemplate( name );
  911. if( m_spawnTemplate == NULL )
  912. {
  913. DEBUG_CRASH(( "SpawnBehavior::xfer - Unable to find template '%s'\n", name.str() ));
  914. throw SC_INVALID_DATA;
  915. } // end if
  916. } // end if
  917. } // end if
  918. // one shot countdown
  919. xfer->xferInt( &m_oneShotCountdown );
  920. // frames to wait
  921. xfer->xferInt( &m_framesToWait );
  922. // first batch count
  923. xfer->xferInt( &m_firstBatchCount );
  924. // replacement times
  925. if( xfer->getXferMode() == XFER_LOAD )
  926. m_replacementTimes.clear();
  927. xfer->xferSTLIntList( &m_replacementTimes );
  928. // spawn ids
  929. xfer->xferSTLObjectIDList( &m_spawnIDs );
  930. // active
  931. xfer->xferBool( &m_active );
  932. // aggregate health
  933. xfer->xferBool( &m_aggregateHealth );
  934. // spawn count
  935. xfer->xferInt( &m_spawnCount );
  936. // self tasking spawn count
  937. xfer->xferUnsignedInt( &m_selfTaskingSpawnCount );
  938. } // end xfer
  939. // ------------------------------------------------------------------------------------------------
  940. /** Load post process */
  941. // ------------------------------------------------------------------------------------------------
  942. void SpawnBehavior::loadPostProcess( void )
  943. {
  944. // extend base class
  945. BehaviorModule::loadPostProcess();
  946. } // end loadPostProcess