RailroadGuideAIUpdate.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602
  1. /*
  2. ** Command & Conquer Generals(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: RailroadBehavior.cpp //////////////////////////////////////////////////////////////
  24. // Author: Mark Lorenzen, Sept 2002
  25. // Desc: The railroad track following railroad carriage/locomotive logic module
  26. ///////////////////////////////////////////////////////////////////////////////////////////////////
  27. #include "PreRTS.h"
  28. #include "Common/Player.h"
  29. #include "Common/ThingFactory.h"
  30. #include "Common/ThingTemplate.h"
  31. #include "GameLogic/Locomotor.h"
  32. #include "GameLogic/Module/RailroadGuideAIUpdate.h"
  33. #include "GameLogic/Object.h"
  34. #include "GameLogic/PartitionManager.h"
  35. #include "GameLogic/Module/ContainModule.h"
  36. #include "GameLogic/Module/DemoTrapUpdate.h"
  37. #include "GameClient/Drawable.h"
  38. #include "GameClient/Statistics.h"
  39. ///#define RAILROAD_DESYNC_TEST
  40. #ifdef RAILROAD_DESYNC_TEST
  41. #include "winbase.h"
  42. #endif
  43. // TYPES //////////////////////////////////////////////////////////////////////////////////////////
  44. static const Int INVALID_PATH = -1;
  45. #define NORMAL_VEL_Z 0.25f
  46. #define NORMAL_MASS 50.0f
  47. #ifdef _INTERNAL
  48. // for occasional debugging...
  49. //#pragma optimize("", off)
  50. //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
  51. //#pragma message("NO COMMENTS, PLEASE ABOUT THIS PRAGMA BEING LEFT ON... IT IS FOR A SPECIAL TEST...")
  52. //#pragma message("IF QA EVER REPRODUCES A DESYNC (BELIEVED FIXED) I'LL NEED TO DEBUG WHILE PLAYING AGAINST")
  53. //#pragma message("THAT MACHINE WITHOUT QUITTING TO START A DEBUGGABLE VERSION...")
  54. //#pragma message("THIS WILL BE CORRECTED IN GOOD TIME. JUST TRUST ME, -ML")
  55. #endif
  56. #define FRAMES_UNPULLED_LONG_ENOUGH_TO_UNHITCH (2)
  57. void TrainTrack::incReference()
  58. {
  59. ++m_refCount;
  60. }
  61. Bool TrainTrack::releaseReference()
  62. {
  63. return ( --m_refCount == 0 );
  64. }
  65. // ------------------------------------------------------------------------------------------------
  66. // ------------------------------------------------------------------------------------------------
  67. RailroadBehaviorModuleData::RailroadBehaviorModuleData( void )
  68. {
  69. m_carriageTemplateNameData.clear();
  70. m_pathPrefixName.clear();
  71. m_CrashFXTemplateName.clear();
  72. m_isLocomotive = FALSE;
  73. m_runningGarrisonSpeedMax = 1.0f;
  74. m_killSpeedMin = 1.0f;
  75. m_speedMax = 4;
  76. m_acceleration = 1.01f;
  77. m_braking = 0.99f;
  78. m_friction = 0.97f;
  79. m_waitAtStationTime = 150;
  80. } // end RailroadBehaviorModuleData
  81. //-------------------------------------------------------------------------------------------------
  82. //-------------------------------------------------------------------------------------------------
  83. RailroadBehavior::RailroadBehavior( Thing *thing, const ModuleData *moduleData )
  84. : PhysicsBehavior( thing, moduleData )
  85. {
  86. const RailroadBehaviorModuleData *modData = getRailroadBehaviorModuleData();
  87. m_carriageTemplateNameIterator = 0;
  88. m_nextStationTask = DO_NOTHING;
  89. m_trailerID = INVALID_ID;
  90. conductorPullInfo.speed = 0;
  91. conductorPullInfo.m_direction = 1.0f;
  92. conductorPullInfo.m_mostRecentSpecialPointHandle = 0xfacade;
  93. conductorPullInfo.towHitchPosition.set(0,0,0);
  94. conductorPullInfo.trackDistance = 0;
  95. conductorPullInfo.currentWaypoint = 0xfacade;
  96. conductorPullInfo.previousWaypoint = 0xfacade;
  97. m_pullInfo.speed = 0.0f;
  98. m_pullInfo.m_direction = 1.0f;
  99. m_pullInfo.m_mostRecentSpecialPointHandle = 0xfacade;
  100. m_pullInfo.towHitchPosition.set(0,0,0);
  101. m_pullInfo.trackDistance = 0.0f;
  102. m_pullInfo.currentWaypoint = 0xfacade;
  103. m_pullInfo.previousWaypoint = 0xfacade;
  104. #ifdef RAILROAD_DESYNC_TEST
  105. _LARGE_INTEGER pc;
  106. QueryPerformanceCounter( &pc ); // absolutely, positively random every call!
  107. Real random = 100000.0f / (Real)pc.LowPart;
  108. conductorPullInfo.m_direction = random;
  109. m_pullInfo.m_direction = random;
  110. #endif
  111. m_runningSound = modData->m_runningSound;
  112. m_clicketyClackSound = modData->m_clicketyClackSound;
  113. m_whistleSound = modData->m_whistleSound;
  114. m_runningSound.setObjectID( getObject()->getID() );
  115. m_whistleSound.setObjectID( getObject()->getID() ) ;
  116. m_clicketyClackSound.setObjectID( getObject()->getID() ) ;
  117. m_track = NULL;
  118. m_currentPointHandle = 0xfacade;
  119. m_waitAtStationTimer = 0;
  120. m_anchorWaypointID = INVALID_WAYPOINT_ID;
  121. m_carriagesCreated = FALSE;
  122. m_hasEverBeenHitched = FALSE;
  123. m_trackDataLoaded = FALSE;
  124. m_waitingInWings = TRUE;
  125. m_endOfLine = FALSE;
  126. m_isLocomotive = modData->m_isLocomotive;
  127. m_isLeadCarraige = m_isLocomotive; // for now, I am the lead, only if I am the locomotive
  128. m_wantsToBeLeadCarraige = FALSE;
  129. m_disembark = FALSE;
  130. m_inTunnel = FALSE;
  131. m_conductorState = m_isLocomotive ? ACCELERATE : COAST;
  132. } // end RailroadBehavior
  133. //-------------------------------------------------------------------------------------------------
  134. //-------------------------------------------------------------------------------------------------
  135. RailroadBehavior::~RailroadBehavior( void )
  136. {
  137. TheAudio->removeAudioEvent( m_runningSound.getPlayingHandle() );// no more chugchug when I'm dead
  138. if( m_track != NULL )
  139. {
  140. if (m_track->releaseReference())
  141. delete m_track;
  142. m_track = NULL;
  143. }
  144. } // end ~RailroadBehavior
  145. // ------------------------------------------------------------------------------------------------
  146. // ------------------------------------------------------------------------------------------------
  147. Bool RailroadBehavior::isRailroad() const
  148. {
  149. if ( ! m_track )
  150. return FALSE;// I haven't even started yet!
  151. if (m_waitingInWings)
  152. return FALSE;
  153. if (m_endOfLine)
  154. return FALSE;
  155. if (m_isLeadCarraige)
  156. return TRUE;
  157. if (m_trailerID==INVALID_ID)
  158. return TRUE;
  159. //Explanation: I return that I am a railroad only if I am at one of the ends, otherwise I refuse to cooperate
  160. return FALSE;
  161. }
  162. // ------------------------------------------------------------------------------------------------
  163. //-------------------------------------------------------------------------------------------------
  164. void RailroadBehavior::onCollide( Object *other, const Coord3D *loc, const Coord3D *normal )
  165. {
  166. Object *obj = getObject();
  167. if ( ! obj)
  168. return; //sanity
  169. if ( ! other)
  170. return; //sanity
  171. if ( ! loc)
  172. return; //sanity
  173. if ( ! normal)
  174. return; //sanity
  175. if (m_waitingInWings)
  176. return ;
  177. if (m_endOfLine)
  178. return ;
  179. for (BehaviorModule** m = other->getBehaviorModules(); *m; ++m)
  180. {
  181. CollideModuleInterface* collide = (*m)->getCollide();
  182. if (!collide)
  183. continue;
  184. if( collide->isRailroad())
  185. {
  186. if ( m_isLocomotive )//yikes! I just rear ended a stranded train! Oh well...
  187. {
  188. other->kill();
  189. }
  190. else if ( m_isLeadCarraige ) //yikes! I just coasted into some other carriage
  191. {
  192. other->kill();
  193. obj->kill();//and I am dead, too
  194. }
  195. return ;//// its a train, folks
  196. }
  197. }
  198. if (other->isKindOf( KINDOF_STRUCTURE ) )// now be careful here, we ignore buildings, except for hostile, nasty ones that can blow us up
  199. {
  200. //If it is a civilian building like a tunnel or a train station, let it be
  201. //but if it is a faction building, kill it!
  202. if (other->isKindOf( KINDOF_FS_POWER ) ||
  203. other->isKindOf( KINDOF_FS_FACTORY ) ||
  204. other->isKindOf( KINDOF_FS_BASE_DEFENSE ) ||
  205. other->isKindOf( KINDOF_FS_TECHNOLOGY ) ||
  206. other->isKindOf( KINDOF_REBUILD_HOLE ) )
  207. {
  208. playImpactSound(other, other->getPosition());
  209. other->kill();
  210. return;
  211. }
  212. static NameKeyType key_DemoTrapUpdate = NAMEKEY("DemoTrapUpdate");
  213. DemoTrapUpdate *dtu = (DemoTrapUpdate*)other->findUpdateModule(key_DemoTrapUpdate);
  214. if( dtu )
  215. {
  216. if( ! BitTest( other-> getStatusBits(), OBJECT_STATUS_UNDER_CONSTRUCTION ) )
  217. obj->kill(); // it can only detonate on me if it is ready
  218. playImpactSound(other, other->getPosition());
  219. other->kill();
  220. return;
  221. }
  222. }
  223. PhysicsBehavior *theirPhys = other->getPhysics();
  224. if( ! theirPhys )
  225. return;
  226. // maybe we don't want to trample this unit?
  227. const RailroadBehaviorModuleData *modData = getRailroadBehaviorModuleData();
  228. if ( m_conductorState == WAIT_AT_STATION && (m_pullInfo.speed < modData->m_runningGarrisonSpeedMax) ) // they can grab on safely
  229. {
  230. AIUpdateInterface *ai = other->getAI();
  231. if (ai && ai->getEnterTarget() == obj) // other intends to garrison me.
  232. {
  233. return;
  234. }
  235. }
  236. if (other->getContainedBy() == getObject() )//I dont mash my own sweet passengers
  237. return;
  238. //if ( other->getModelConditionFlags().test( MODELCONDITION_RUBBLE ) == TRUE )
  239. // return; // I don't mess with rubble
  240. Bool victimIsInfantry = other->isKindOf( KINDOF_INFANTRY );
  241. const Coord3D *myDir = obj->getUnitDirectionVector2D();
  242. const Coord3D *myLoc = obj->getPosition();
  243. const Coord3D *theirLoc = other->getPosition();
  244. //---------------------------
  245. // if we made it this far, it is something we dont want to share space with
  246. Coord3D dlt;
  247. dlt.x = theirLoc->x - myLoc->x;
  248. dlt.y = theirLoc->y - myLoc->y;
  249. dlt.z = theirLoc->z - myLoc->z;
  250. //Alert all the players of recent disaster
  251. if ( ! m_whistleSound.isCurrentlyPlaying())
  252. m_whistleSound.setPlayingHandle(TheAudio->addAudioEvent( &m_whistleSound ));
  253. Real dist = (Real)sqrtf( dlt.x*dlt.x + dlt.y*dlt.y + dlt.z*dlt.z);
  254. Real usRadius = obj->getGeometryInfo().getMajorRadius();
  255. Real themRadius = other->getGeometryInfo().getMajorRadius();
  256. Real overlap = ((usRadius + themRadius) - dist) + 1;// the plus 1 makes them go just outside of me.
  257. dlt.normalize();
  258. if ( ! victimIsInfantry )
  259. {
  260. overlap/= 4;
  261. }
  262. dlt.scale( overlap);
  263. Coord3D newPos;
  264. newPos.x = theirLoc->x + dlt.x;
  265. newPos.y = theirLoc->y + dlt.y;
  266. newPos.z = theirLoc->z + dlt.z;
  267. other->setPosition( &newPos );
  268. AIUpdateInterface *ai = other->getAI();
  269. if ( ai )
  270. ai->aiIdle( CMD_FROM_AI );// this eliminates yadda by telling them to stop driving into me
  271. //---------------------------
  272. if ( m_conductorState == WAIT_AT_STATION || (m_conductorState == COAST && m_pullInfo.speed < modData->m_runningGarrisonSpeedMax))
  273. {
  274. ContainModuleInterface * contain = obj->getContain();
  275. if ( contain )
  276. {
  277. if (contain->isValidContainerFor( other, FALSE ))
  278. {
  279. return; // let them out
  280. }
  281. }
  282. else if ( victimIsInfantry )
  283. {
  284. return;//let those trying to board pass through unhindered
  285. }
  286. }
  287. //figure out the relative slope between them and me
  288. Coord3D delta = *theirLoc;
  289. delta.sub( myLoc );
  290. delta.normalize();
  291. Real dot = delta.x * myDir->x + delta.y * myDir->y + delta.z * myDir->z;
  292. if (other->isEffectivelyDead())
  293. {// we just run over debris, instead of shoving it around
  294. delta.scale( MIN(0.3f,m_pullInfo.speed * 0.66f) );
  295. }
  296. else
  297. {
  298. delta.scale( MIN(1.4f,m_pullInfo.speed * 0.66f) );// the faster I go, the harder I slam!
  299. //Absolute death to be hit by a train, no survival
  300. if ( m_pullInfo.speed >= modData->m_killSpeedMin ) // they can grab on safely
  301. {
  302. other->kill();
  303. theirPhys->setPitchRate(GameLogicRandomValueReal(-0.03f, 0.03f));
  304. theirPhys->setRollRate(GameLogicRandomValueReal(-0.03f, 0.03f));
  305. }
  306. else
  307. {
  308. playImpactSound(other, loc); //Play a bounce sound
  309. DamageInfo damageInfo;
  310. damageInfo.in.m_damageType = DAMAGE_CRUSH;
  311. damageInfo.in.m_deathType = DEATH_CRUSHED;
  312. damageInfo.in.m_sourceID = getObject()->getID();
  313. damageInfo.in.m_amount = m_pullInfo.speed * 10; // hurt!
  314. other->attemptDamage( &damageInfo );
  315. }
  316. }
  317. Coord3D heft = *theirLoc;
  318. heft.z = MAX(heft.z, TheTerrainLogic->getGroundHeight(heft.x, heft.y) + 2); // lift them off the ground
  319. other->setPosition(&heft);
  320. delta.z = GameLogicRandomValueReal(0.05f, m_pullInfo.speed/10); // for some fake heft
  321. delta.scale(dot);
  322. // This is a special check so that it wont hurl infantry clear across the map!
  323. if( ! ( victimIsInfantry && theirPhys->getVelocityMagnitude() > 5.0f ) )
  324. theirPhys->addVelocityTo( &delta );
  325. theirPhys->setAllowToFall( TRUE );
  326. theirPhys->setAllowBouncing( TRUE );
  327. theirPhys->setAllowAirborneFriction( TRUE );
  328. const Coord3D up = {0,0,1};
  329. Coord3D cross;
  330. myDir->crossProduct( myDir, &up, &cross );
  331. delta.normalize();
  332. Real deviationCOG = cross.x * delta.x + cross.y * delta.y + cross.z * delta.z;
  333. if (dot > 0)
  334. theirPhys->setYawRate( deviationCOG * -0.06f * m_pullInfo.speed);
  335. } // end RailroadBehavior:: on collide
  336. // ------------------------------------------------------------------------------------------------
  337. // ------------------------------------------------------------------------------------------------
  338. void RailroadBehavior::playImpactSound(Object *victim, const Coord3D *impactPosition)
  339. {
  340. AudioEventRTS impact;
  341. //AudioEventRTS *pImpact = &impact;
  342. PhysicsBehavior *theirPhys = victim->getPhysics();
  343. Bool hasBounceSound = FALSE;
  344. if ( theirPhys )
  345. {
  346. const AudioEventRTS* bsound = theirPhys->getBounceSound();
  347. if (bsound)
  348. {
  349. impact = *bsound;//copy theirs
  350. hasBounceSound = TRUE;
  351. }
  352. }
  353. if ( ! hasBounceSound )
  354. {
  355. const RailroadBehaviorModuleData *modData = getRailroadBehaviorModuleData();
  356. if (victim->isKindOf( KINDOF_INFANTRY ))
  357. {
  358. impact = modData->m_meatyImpactDefaultSound;//copy
  359. }
  360. else if (victim->isKindOf( KINDOF_HUGE_VEHICLE ) || victim->isKindOf( KINDOF_STRUCTURE ))
  361. {
  362. impact = modData->m_bigMetalImpactDefaultSound;//copy
  363. }
  364. else if (victim->isKindOf( KINDOF_VEHICLE ) )
  365. {
  366. impact = modData->m_smallMetalImpactDefaultSound;//copy
  367. }
  368. }
  369. if (impact.getEventName().isEmpty())
  370. return;
  371. Real vel = NORMAL_VEL_Z; //the max
  372. Real mass = NORMAL_MASS; //the max
  373. impact.setPosition(impactPosition);
  374. if ( theirPhys )
  375. {
  376. vel += fabs(theirPhys->getVelocity()->length());
  377. mass += fabs(theirPhys->getMass());
  378. vel /= 2;
  379. mass /= 2;//average of him and me
  380. impact.setPosition(victim->getPosition());
  381. }
  382. vel = MIN(NORMAL_VEL_Z, MAX(0, vel));
  383. mass = MIN(NORMAL_MASS, MAX(0, mass));
  384. Real volAdjust = NormalizeToRange(MuLaw(vel, NORMAL_VEL_Z, 500), -1, 1, 0.25, 1.0);
  385. volAdjust *= NormalizeToRange(MuLaw(mass, NORMAL_MASS, 500), -1, 1, 0.25, 1.0);
  386. impact.setVolume( volAdjust );
  387. // This sound really should only be played at the position where the collision occurs.
  388. // Therefore, set the player index of the sound to be the player index of the victim object.
  389. impact.setPlayerIndex( victim->getControllingPlayer()->getPlayerIndex() );
  390. TheAudio->addAudioEvent( &impact );
  391. }
  392. // ------------------------------------------------------------------------------------------------
  393. // ------------------------------------------------------------------------------------------------
  394. void RailroadBehavior::loadTrackData( void )
  395. {
  396. if ( m_track != NULL )
  397. return;// lets do this only once!
  398. //First we scan the map for the nearest waypoint
  399. Object *obj = getObject();
  400. const Coord3D *myPos = obj->getPosition();
  401. Coord3D delta;
  402. Real closestDistance = 99999.9f;
  403. // m_anchorWaypointID COULD HAVE BEEN RECORDED IN XFER, WHICH MEANS I LOADED MY TRACK DATA IN A PRIOR LIFE,
  404. // SO LETS JUST RE_INIT THE TRACK BASED ON THAT POINT, AUTOMAGICALLY
  405. Waypoint *anchorWaypoint = NULL;
  406. if ( m_anchorWaypointID == INVALID_WAYPOINT_ID )
  407. {
  408. Waypoint *anyWaypoint = TheTerrainLogic->getFirstWaypoint();
  409. while ( anyWaypoint )
  410. {
  411. //measure the distance from me to the waypoint
  412. delta.x = myPos->x - anyWaypoint->getLocation()->x;
  413. delta.y = myPos->y - anyWaypoint->getLocation()->y;
  414. delta.z = myPos->z - anyWaypoint->getLocation()->z;
  415. if (closestDistance > delta.length() )
  416. {
  417. closestDistance = delta.length();
  418. anchorWaypoint = anyWaypoint;
  419. m_anchorWaypointID = anchorWaypoint->getID();// save for XFER, later
  420. }
  421. anyWaypoint = anyWaypoint->getNext();
  422. }
  423. }
  424. else
  425. {
  426. anchorWaypoint = TheTerrainLogic->getWaypointByID( m_anchorWaypointID );
  427. }
  428. DEBUG_ASSERTCRASH( anchorWaypoint, ( "Railroad... couldn't find a waypoint close enough to be the anchor.\n You should put your train engine right on a waypoint,\n and make sure the path forms a valid track.") );
  429. if ( ! anchorWaypoint )
  430. return;
  431. m_track = NEW( TrainTrack );// this constructor inc's the refcount to 1
  432. // From now until the next carriage is added, this track is writable using getWritablePointList();
  433. // This method will return NULL when refcount is 2 or more
  434. // getPointList returns the list as const to any caller
  435. // each carriage must increment the reference when this pointer is passed to it,
  436. // any subsequent carriage (destructor) will delete this memory here if it releases refcount to zero
  437. Coord3D fromPos, toPos, fromToDelta;
  438. m_track->m_length = 0.0f;
  439. Waypoint *scanner = anchorWaypoint;
  440. Real distFromTo = 0.0f;
  441. //Let's start buliding our own track data from the waypoint data we find
  442. TrackPointList* track = m_track->getWritablePointList();
  443. TrackPoint trackPoint; // local workspace
  444. if ( scanner && track)
  445. {
  446. trackPoint.m_distanceFromPrev = 0;
  447. trackPoint.m_distanceFromFirst = 0;
  448. trackPoint.m_isFirstPoint = TRUE;
  449. trackPoint.m_isLastPoint = FALSE;
  450. trackPoint.m_isTunnelOrBridge = scanner->getName().endsWith("Tunnel");
  451. trackPoint.m_isStation = scanner->getName().endsWith("Station");
  452. trackPoint.m_isDisembark = scanner->getName().endsWith("Disembark");
  453. trackPoint.m_isPingPong = FALSE;
  454. trackPoint.m_position.set( scanner->getLocation() );
  455. trackPoint.m_handle = scanner->getID();
  456. track->push_back( trackPoint );
  457. }
  458. while ( scanner )
  459. {
  460. trackPoint.clear();// clean up the local workspace to make debugging more fun
  461. if ( scanner->getNumLinks() )
  462. {
  463. Waypoint *anotherWaypoint = scanner->getLink( 0 );
  464. // if scanner's link is valid, we'll add it to the track. now
  465. if ( anotherWaypoint != NULL )
  466. {
  467. //measure the track while we are at it
  468. fromPos = *scanner->getLocation();
  469. toPos = *anotherWaypoint->getLocation();
  470. fromToDelta.x = fromPos.x - toPos.x;
  471. fromToDelta.y = fromPos.y - toPos.y;
  472. fromToDelta.z = fromPos.z - toPos.z;
  473. distFromTo = fromToDelta.length();
  474. m_track->m_length += distFromTo;
  475. trackPoint.m_distanceFromPrev = distFromTo;
  476. trackPoint.m_distanceFromFirst = m_track->m_length;
  477. trackPoint.m_isFirstPoint = FALSE;
  478. trackPoint.m_isLastPoint = anotherWaypoint->getLink( 0 ) == NULL;
  479. trackPoint.m_isTunnelOrBridge = anotherWaypoint->getName().endsWith("Tunnel");
  480. trackPoint.m_isStation = anotherWaypoint->getName().endsWith("Station");
  481. trackPoint.m_isPingPong = scanner->getName().endsWith("PingPong");
  482. trackPoint.m_isDisembark = scanner->getName().endsWith("Disembark");
  483. trackPoint.m_position.set( anotherWaypoint->getLocation() );
  484. trackPoint.m_handle = scanner->getID();
  485. track->push_back( trackPoint );
  486. }
  487. scanner = anotherWaypoint;
  488. }
  489. else
  490. break; // since we have reached a non-linked waypoint
  491. if ( scanner == anchorWaypoint )
  492. {
  493. m_track->m_isLooping = TRUE;
  494. break; // it must be a looping track. Cool.
  495. }
  496. }
  497. } // end loadTrackData
  498. // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  499. UpdateSleepTime RailroadBehavior::update( void )
  500. {
  501. // load the waypoint data if not loaded
  502. if( m_trackDataLoaded == FALSE && m_isLocomotive )
  503. {
  504. loadTrackData();
  505. if ( m_track )
  506. createCarriages();
  507. m_trackDataLoaded = TRUE;
  508. }
  509. if ( ! m_track )
  510. {
  511. return UPDATE_SLEEP_NONE;
  512. }
  513. //Object *us = getObject();
  514. const RailroadBehaviorModuleData *modData = getRailroadBehaviorModuleData();
  515. if ( m_isLocomotive )
  516. {
  517. if ( m_conductorState == APPLY_BRAKES )
  518. {
  519. conductorPullInfo.speed *= modData->m_braking;
  520. if (fabs(conductorPullInfo.speed) < 0.01f)
  521. {
  522. conductorPullInfo.speed = 0;
  523. ///////////////////////////////////////( &m_hissySteamSound );
  524. m_waitAtStationTimer = modData->m_waitAtStationTime;
  525. m_conductorState = WAIT_AT_STATION;
  526. if ( m_disembark )
  527. {
  528. disembark();
  529. m_disembark = FALSE;
  530. }
  531. }
  532. }
  533. else if ( m_conductorState == WAIT_AT_STATION)
  534. {
  535. --m_waitAtStationTimer;
  536. if ( m_waitAtStationTimer <= 0)
  537. {
  538. m_conductorState = ACCELERATE;
  539. conductorPullInfo.speed = 0.05f * conductorPullInfo.m_direction;
  540. m_runningSound.setPlayingHandle(TheAudio->addAudioEvent( &m_runningSound ));
  541. }
  542. else if ( m_waitAtStationTimer == (modData->m_waitAtStationTime/4) )
  543. {
  544. m_whistleSound.setPlayingHandle(TheAudio->addAudioEvent( &m_whistleSound ));
  545. }
  546. }
  547. else if ( m_conductorState == ACCELERATE )
  548. {
  549. conductorPullInfo.speed += 0.02f * conductorPullInfo.m_direction; // push start multiplier
  550. conductorPullInfo.speed *= modData->m_acceleration;
  551. if ( conductorPullInfo.speed > modData->m_speedMax)
  552. {
  553. conductorPullInfo.speed = modData->m_speedMax;
  554. }
  555. else if ( conductorPullInfo.speed < -modData->m_speedMax)
  556. {
  557. conductorPullInfo.speed = -modData->m_speedMax;
  558. }
  559. if ( ! m_runningSound.isCurrentlyPlaying() )
  560. m_runningSound.setPlayingHandle(TheAudio->addAudioEvent( &m_runningSound ));
  561. }
  562. }
  563. if ( m_wantsToBeLeadCarraige > FRAMES_UNPULLED_LONG_ENOUGH_TO_UNHITCH )//if this flag survived until now, I have lost my puller
  564. {
  565. m_isLeadCarraige = TRUE;
  566. }
  567. if ( m_isLeadCarraige )
  568. {
  569. if ( m_conductorState == COAST )
  570. {
  571. conductorPullInfo.speed *= modData->m_friction;
  572. TheAudio->removeAudioEvent( m_runningSound.getPlayingHandle() );
  573. }
  574. conductorPullInfo.trackDistance += conductorPullInfo.speed ;
  575. // only normalize track position for a looping track, otherwise, let train exit by exceeding tracklength
  576. while ( (conductorPullInfo.trackDistance > m_track->m_length) && m_track->m_isLooping)
  577. conductorPullInfo.trackDistance -= m_track->m_length;
  578. while ( (conductorPullInfo.trackDistance < 0.0f ) && m_track->m_isLooping)
  579. conductorPullInfo.trackDistance += m_track->m_length;
  580. FindPosByPathDistance( &conductorPullInfo.towHitchPosition,
  581. conductorPullInfo.trackDistance,
  582. m_track->m_length);
  583. //let the conductor pull "me" while reseting my info, then...
  584. updatePositionTrackDistance( &conductorPullInfo, &m_pullInfo);
  585. //get pointer to my trailer
  586. Object *trailer = TheGameLogic->findObjectByID( m_trailerID );
  587. if ( trailer )
  588. {
  589. //call his pull trailer with my info;
  590. static NameKeyType key_RGUpdate = NAMEKEY("RailroadBehavior");
  591. RailroadBehavior *RGUpdate = (RailroadBehavior*)trailer->findUpdateModule(key_RGUpdate);
  592. if( RGUpdate )
  593. {
  594. RGUpdate->getPulled( &m_pullInfo );
  595. }
  596. }
  597. else
  598. {
  599. m_trailerID = INVALID_ID;// so I will forget about my trailer and designate myself as the caboose
  600. if ( m_endOfLine )
  601. TheGameLogic->destroyObject( getObject() );
  602. }
  603. }
  604. else if ( m_wantsToBeLeadCarraige <= FRAMES_UNPULLED_LONG_ENOUGH_TO_UNHITCH )// if I am not the lead carriage
  605. {
  606. m_wantsToBeLeadCarraige ++; // like every young carriage, I aspire to be the lead carriage some day
  607. // unless getpulled() set this false, I will be on the next update! Joy!
  608. }
  609. Drawable *draw = getObject()->getDrawable();
  610. if (draw)
  611. {
  612. if ( ! m_track->m_isLooping )
  613. {
  614. draw->setDrawableHidden( m_waitingInWings || m_endOfLine );
  615. }
  616. // TURN OFF SMOKE EFFECTS IF WE ARE IN A TUNNEL
  617. const Coord3D *drawPos = draw->getPosition();
  618. if (drawPos->z < TheTerrainLogic->getGroundHeight(drawPos->x, drawPos->y) - 3.0f )
  619. draw->setModelConditionState(MODELCONDITION_OVER_WATER);
  620. else
  621. draw->clearModelConditionState(MODELCONDITION_OVER_WATER);
  622. }
  623. return UPDATE_SLEEP_NONE;
  624. } // end update
  625. // ------------------------------------------------------------------------------------------------
  626. //-------------------------------------------------------------------------------------------------
  627. void RailroadBehavior::disembark(void)
  628. {
  629. ContainModuleInterface *contain = getObject()->getContain();
  630. if (contain)
  631. {
  632. contain->orderAllPassengersToExit( CMD_FROM_AI );
  633. }
  634. Object *trailer = TheGameLogic->findObjectByID( m_trailerID );
  635. if ( trailer )
  636. {
  637. static NameKeyType key_RGUpdate = NAMEKEY("RailroadBehavior");
  638. RailroadBehavior *RGUpdate = (RailroadBehavior*)trailer->findUpdateModule(key_RGUpdate);
  639. if( RGUpdate )
  640. {
  641. RGUpdate->disembark();
  642. }
  643. }
  644. }
  645. ///////////////////////////////////////////////////////////////////////////////////////////////////
  646. // PRIVATE ////////////////////////////////////////////////////////////////////////////////////////
  647. ///////////////////////////////////////////////////////////////////////////////////////////////////
  648. class PartitionFilterIsValidCarriage : public PartitionFilter
  649. {
  650. private:
  651. Object* m_obj;
  652. const RailroadBehaviorModuleData* m_data;
  653. public:
  654. PartitionFilterIsValidCarriage(Object* obj, const RailroadBehaviorModuleData* data) : m_obj(obj), m_data(data) { }
  655. #if defined(_DEBUG) || defined(_INTERNAL)
  656. virtual const char* debugGetName() { return "PartitionFilterIsValidCarriage"; }
  657. #endif
  658. virtual Bool allow(Object *objOther)
  659. {
  660. // must exist!
  661. if ( m_obj == NULL || objOther == NULL)
  662. return FALSE;
  663. //must not be me!
  664. if (m_obj == objOther)
  665. return FALSE;
  666. // must have railroady goodness
  667. static NameKeyType key_rb = NAMEKEY("RailroadBehavior");
  668. RailroadBehavior *rb = (RailroadBehavior*)objOther->findUpdateModule(key_rb);
  669. if( ! rb )
  670. return FALSE;
  671. if ( rb->hasEverBeenHitched() )// two of us can't pull you
  672. return FALSE;
  673. // must be our ally (well, maybe)
  674. if (m_obj->getRelationship(objOther) != ALLIES)
  675. return FALSE;
  676. // guess it's carriage-worthy!
  677. return TRUE;
  678. }
  679. };
  680. void RailroadBehavior::createCarriages( void )
  681. {
  682. if ( ! m_isLocomotive )
  683. {
  684. DEBUG_ASSERTCRASH(m_isLocomotive, ("a not locomotive attempted to create carriages"));
  685. return;
  686. }
  687. const RailroadBehaviorModuleData* md = getRailroadBehaviorModuleData();
  688. Object *self = getObject();
  689. //First we'll see if the map artist put some cars down on the track for us to find
  690. Real maxRadius = self->getGeometryInfo().getMajorRadius() * 2.0f;
  691. Coord3D myHitchLoc = *self->getPosition();
  692. Coord3D hitchOffset = *self->getUnitDirectionVector2D();//copy that
  693. hitchOffset.scale ( - maxRadius );// negative, since I want the back, not the front
  694. myHitchLoc.add( & hitchOffset );
  695. PartitionFilterIsValidCarriage pfivc(self, md);
  696. PartitionFilter *filters[] = { &pfivc, 0 };
  697. Object* xferCarriage = NULL;
  698. Object *closeCarriage = NULL;
  699. Object *firstCarriage = NULL;
  700. if ( m_trailerID != INVALID_ID )
  701. {
  702. xferCarriage = TheGameLogic->findObjectByID( m_trailerID );
  703. }
  704. if (xferCarriage != NULL)
  705. closeCarriage = xferCarriage;
  706. else
  707. closeCarriage = ThePartitionManager->getClosestObject( &myHitchLoc, maxRadius, FROM_CENTER_2D, filters);
  708. TemplateNameList list = md->m_carriageTemplateNameData;
  709. TemplateNameIterator iter = list.begin();
  710. if ( iter != list.end() )
  711. {
  712. const ThingTemplate* temp = TheThingFactory->findTemplate( *iter );
  713. if (temp)
  714. {
  715. if ( closeCarriage )
  716. firstCarriage = closeCarriage;
  717. else // or else let's use the defualt template list prvided in the INI
  718. {
  719. firstCarriage = TheThingFactory->newObject( temp, self->getTeam() );
  720. DEBUG_LOG(("%s Added a carriage, %s \n", self->getTemplate()->getName().str(),firstCarriage->getTemplate()->getName().str()));
  721. }
  722. if ( firstCarriage )
  723. {
  724. firstCarriage->setProducer(self);
  725. m_trailerID = firstCarriage->getID();
  726. static NameKeyType key_rb = NAMEKEY("RailroadBehavior");
  727. RailroadBehavior *rb = (RailroadBehavior*)firstCarriage->findUpdateModule(key_rb);
  728. if( rb )
  729. {
  730. if ( closeCarriage )
  731. rb->hitchNewCarriagebyProximity( self->getID(), m_track );
  732. else
  733. rb->hitchNewCarriagebyTemplate( self->getID(), list, ++iter, m_track );// ! increment iter here!
  734. }
  735. else
  736. {
  737. DEBUG_ASSERTCRASH( rb,
  738. ("%s is attempting to hitch carriage, %s without a RailroadBehavior... \nwhat kind of nutty conductor are you? ",
  739. self->getTemplate()->getName().str(),
  740. firstCarriage->getTemplate()->getName().str() ) );
  741. }
  742. }
  743. }
  744. }
  745. m_carriagesCreated = TRUE;
  746. }
  747. // ------------------------------------------------------------------------------------------------
  748. // ------------------------------------------------------------------------------------------------
  749. void RailroadBehavior::hitchNewCarriagebyTemplate( ObjectID locoID, const TemplateNameVector& list, TemplateNameIterator& iter, TrainTrack *track)
  750. {
  751. if ( m_isLocomotive )
  752. {
  753. DEBUG_ASSERTCRASH(m_isLocomotive, ("You can not hitch a locomotive in mid train, dude."));
  754. return;
  755. }
  756. Object *locomotive = TheGameLogic->findObjectByID( locoID );
  757. if ( !locomotive )// sanity
  758. return;
  759. m_track = track; //ALWAYS INCREFERENCE WHENEVER YOU INHERIT THIS POINTER
  760. m_track->incReference();//ALWAYS INCREFERENCE WHENEVER YOU INHERIT THIS POINTER
  761. m_hasEverBeenHitched = TRUE;// so no other trains try to hitch me onto them
  762. //Okay that's me, now for the next guy
  763. //---------------------------------------
  764. Object *newCarriage = NULL;
  765. if ( iter != list.end() )// this test is bogus
  766. {
  767. const ThingTemplate* temp = TheThingFactory->findTemplate( *iter );
  768. if (temp)
  769. {
  770. newCarriage = TheThingFactory->newObject( temp, locomotive->getTeam() ); // just a little worried about this...
  771. newCarriage->setProducer(locomotive);
  772. m_trailerID = newCarriage->getID();
  773. static NameKeyType key_rb = NAMEKEY("RailroadBehavior");
  774. RailroadBehavior *rb = (RailroadBehavior*)newCarriage->findUpdateModule(key_rb);
  775. if( rb )
  776. {
  777. rb->hitchNewCarriagebyTemplate( locoID, list, ++iter, m_track );
  778. }
  779. else
  780. {
  781. DEBUG_ASSERTCRASH( rb,
  782. ("%s could not hitch a %s without a RailroadBehavior... \nwhat kind of nutty conductor are you? \nThe next carriage would have been a %s.",
  783. locomotive->getTemplate()->getName().str(),
  784. newCarriage->getTemplate()->getName().str(),
  785. *iter
  786. ) );
  787. }
  788. }
  789. }
  790. }
  791. // ------------------------------------------------------------------------------------------------
  792. // ------------------------------------------------------------------------------------------------
  793. void RailroadBehavior::hitchNewCarriagebyProximity( ObjectID locoID, TrainTrack *track)
  794. {
  795. if ( m_isLocomotive )
  796. {
  797. DEBUG_ASSERTCRASH(m_isLocomotive, ("You can not hitch a locomotive in mid train, dude."));
  798. return;
  799. }
  800. Object *locomotive = TheGameLogic->findObjectByID( locoID );
  801. if ( !locomotive )// sanity
  802. return;
  803. m_track = track; //ALWAYS INCREFERENCE WHENEVER YOU INHERIT THIS POINTER
  804. m_track->incReference();//ALWAYS INCREFERENCE WHENEVER YOU INHERIT THIS POINTER
  805. m_hasEverBeenHitched = TRUE;// so no other trains try to hitch me onto them
  806. //Okay that's me, now for the next guy
  807. //---------------------------------------
  808. //First we'll see if the map artist put some cars down on the track for us to find
  809. const RailroadBehaviorModuleData* md = getRailroadBehaviorModuleData();
  810. Object *self = getObject();
  811. Real maxRadius = self->getGeometryInfo().getMajorRadius() * 2.0f;
  812. Coord3D myHitchLoc = *self->getPosition();
  813. Coord3D hitchOffset = *self->getUnitDirectionVector2D();//copy that
  814. hitchOffset.scale ( - maxRadius );// negative, since I want the back, not the front
  815. myHitchLoc.add( & hitchOffset );
  816. PartitionFilterIsValidCarriage pfivc(self, md);
  817. PartitionFilter *filters[] = { &pfivc, 0 };
  818. Object* xferCarriage = NULL;
  819. Object *closeCarriage = NULL;
  820. if ( m_trailerID != INVALID_ID )
  821. {
  822. xferCarriage = TheGameLogic->findObjectByID( m_trailerID );
  823. }
  824. if (xferCarriage != NULL)
  825. closeCarriage = xferCarriage;
  826. else
  827. closeCarriage = ThePartitionManager->getClosestObject( &myHitchLoc, maxRadius, FROM_CENTER_2D, filters);
  828. if ( closeCarriage )
  829. {
  830. closeCarriage->setProducer(self);
  831. m_trailerID = closeCarriage->getID();
  832. static NameKeyType key_rb = NAMEKEY("RailroadBehavior");
  833. RailroadBehavior *rb = (RailroadBehavior*)closeCarriage->findUpdateModule(key_rb);
  834. if( rb )
  835. rb->hitchNewCarriagebyProximity( self->getID(), m_track );
  836. else
  837. {
  838. DEBUG_ASSERTCRASH( rb,
  839. ("%s is attempting to hitch carriage, %s without a RailroadBehavior... \nwhat kind of nutty conductor are you? ",
  840. self->getTemplate()->getName().str(),
  841. closeCarriage->getTemplate()->getName().str() ) );
  842. }
  843. }
  844. }
  845. // ------------------------------------------------------------------------------------------------
  846. // ------------------------------------------------------------------------------------------------
  847. void RailroadBehavior::getPulled( PullInfo *info )
  848. {
  849. //ENFORCE MY STATUS AS A PULLEE, NOT A PULLER, and update my position, speed etc.
  850. m_wantsToBeLeadCarraige = 0;
  851. if ( ! m_track )
  852. {
  853. return;
  854. }
  855. conductorPullInfo = *info;//copy my puller to my conductor, so that if I ever get detached
  856. //( meaning that if this function stops getting called ), I will take over as the lead carriage!
  857. //Wheeeee!!
  858. info->previousWaypoint = info->currentWaypoint;
  859. updatePositionTrackDistance( info, &m_pullInfo );
  860. //get pointer to my trailer
  861. Object *trailer = TheGameLogic->findObjectByID( m_trailerID );
  862. if ( trailer )
  863. {
  864. //call his pull trailer with MY info;
  865. static NameKeyType key_RGUpdate = NAMEKEY("RailroadBehavior");
  866. RailroadBehavior *RGUpdate = (RailroadBehavior*)trailer->findUpdateModule(key_RGUpdate);
  867. if( RGUpdate )
  868. {
  869. RGUpdate->getPulled( &m_pullInfo ); //< this is MY info, not the one passed to me
  870. }
  871. }
  872. else
  873. {
  874. m_trailerID = INVALID_ID;// so I will forget about my trailer and designate myself as the caboose
  875. if ( m_endOfLine )
  876. TheGameLogic->destroyObject( getObject() );
  877. }
  878. }
  879. // ------------------------------------------------------------------------------------------------
  880. void alignToTerrain( Real angle, const Coord3D& pos, const Coord3D& normal, Matrix3D& mtx)
  881. {
  882. Coord3D x, y, z;
  883. z = normal;
  884. x.x = Cos( angle );
  885. x.y = Sin( angle );
  886. x.z = 0.0f;
  887. if (z.z != 0.0f)
  888. {
  889. x.z = -(x.x*z.x + x.y*z.y) / z.z;
  890. x.normalize();
  891. }
  892. DEBUG_ASSERTCRASH(fabs(x.x*z.x + x.y*z.y + x.z*z.z)<0.0001,("dot is not zero\n"));
  893. // now computing the y vector is trivial.
  894. y.crossProduct( &z, &x, &y );
  895. y.normalize();
  896. mtx.Set( x.x, y.x, z.x, pos.x,
  897. x.y, y.y, z.y, pos.y,
  898. x.z, y.z, z.z, pos.z );
  899. }
  900. // ------------------------------------------------------------------------------------------------
  901. // ------------------------------------------------------------------------------------------------
  902. void RailroadBehavior::updatePositionTrackDistance( PullInfo *pullerInfo, PullInfo *myInfo )
  903. {
  904. if ( ! m_track )
  905. {
  906. return;
  907. }
  908. Object *obj = BehaviorModule::getObject();
  909. if ( ! obj )
  910. return; //sanity
  911. // IF THIS HAS BEEN CALLED, AM AM GETTING PULLED BY SOMETHING,
  912. // my conductor, or another car
  913. Real hitchRadius = obj->getGeometryInfo().getMajorRadius();
  914. myInfo->trackDistance = pullerInfo->trackDistance - (hitchRadius * 2);
  915. myInfo->speed = pullerInfo->speed;// YES, if I am getting pulled, I must obey puller
  916. myInfo->m_direction = pullerInfo->m_direction;// YES, if I am getting pulled, I must obey puller
  917. // pullerInfo->previousWaypoint = pullerInfo->currentWaypoint;// to feed edge test in update
  918. // I THINK THE TURN_TO POINT SHOULD BE A BONE ON THE PREVIOUS CAR!!!!!!
  919. FindPosByPathDistance( &myInfo->towHitchPosition,
  920. myInfo->trackDistance, // the look ahead
  921. m_track->m_length);
  922. Coord3D carPosition;
  923. FindPosByPathDistance( &carPosition,
  924. myInfo->trackDistance,
  925. m_track->m_length, TRUE);
  926. Coord3D turnPos = *obj->getPosition();
  927. if (!m_inTunnel)
  928. turnPos.z = TheTerrainLogic->getGroundHeight( turnPos.x, turnPos.y );
  929. const Coord3D* dir = obj->getUnitDirectionVector2D();
  930. turnPos.x += dir->x * -hitchRadius;
  931. turnPos.y += dir->y * -hitchRadius;
  932. Coord3D trackPosDelta;
  933. trackPosDelta.x = carPosition.x - turnPos.x;
  934. trackPosDelta.y = carPosition.y - turnPos.y;
  935. trackPosDelta.z = 0;
  936. Real dx = pullerInfo->towHitchPosition.x - turnPos.x;
  937. Real dy = pullerInfo->towHitchPosition.y - turnPos.y;
  938. Real desiredAngle = atan2(dy, dx);
  939. Real relAngle = stdAngleDiff(desiredAngle, obj->getTransformMatrix()->Get_Z_Rotation());
  940. Matrix3D mtx;
  941. Matrix3D tmp(1);
  942. tmp.Translate(turnPos.x, turnPos.y, 0);
  943. tmp.Translate(trackPosDelta.x, trackPosDelta.y, 0);
  944. tmp.In_Place_Pre_Rotate_Z(relAngle );
  945. tmp.Translate(-turnPos.x, -turnPos.y, 0);
  946. mtx.mul(tmp, *obj->getTransformMatrix());
  947. //enforce ground elevation
  948. Coord3D normal ;
  949. Real enforceElevation = TheTerrainLogic->getGroundHeight( turnPos.x, turnPos.y, &normal );
  950. obj->setTransformMatrix(&mtx);
  951. if (!m_inTunnel)
  952. obj->setPositionZ( enforceElevation );
  953. obj->handlePartitionCellMaintenance();
  954. }
  955. //---------------------------------------------------------------------------------
  956. //---------------------------------------------------------------------------------
  957. void RailroadBehavior::destroyTheWholeTrainNow( void )
  958. {
  959. TheGameLogic->destroyObject( getObject());
  960. Object *trailer = TheGameLogic->findObjectByID( m_trailerID );
  961. if ( trailer )
  962. {
  963. static NameKeyType key_RGUpdate = NAMEKEY("RailroadBehavior");
  964. RailroadBehavior *RGUpdate = (RailroadBehavior*)trailer->findUpdateModule(key_RGUpdate);
  965. if( RGUpdate )
  966. {
  967. RGUpdate->destroyTheWholeTrainNow(); //< this is MY info, not the one passed to me
  968. }
  969. }
  970. }
  971. // ------------------------------------------------------------------------------------------------
  972. // ------------------------------------------------------------------------------------------------
  973. void RailroadBehavior::FindPosByPathDistance( Coord3D *pos, const Real dist, const Real length, Bool setState )
  974. {
  975. if ( ! m_track )
  976. return;
  977. m_waitingInWings = FALSE;
  978. Real actualDistance = dist;// WRAP TO NORMALIZE
  979. if ( m_track->m_isLooping )
  980. {
  981. while ( actualDistance < 0.0f )
  982. {
  983. actualDistance += length;
  984. }
  985. while ( actualDistance > length )
  986. {
  987. actualDistance -= length;
  988. }
  989. }
  990. else
  991. {
  992. if ( dist < 0 )
  993. {
  994. actualDistance = 0;
  995. m_waitingInWings = TRUE;
  996. }
  997. else if ( dist >= length )
  998. {
  999. actualDistance = length;
  1000. m_endOfLine = TRUE;
  1001. }
  1002. actualDistance = MAX(MIN(length,dist),0); // CLAMP TO NORMALIZE
  1003. }
  1004. pos->set( 0.0f, 0.0f, 0.0f );
  1005. const TrackPointList *pointList = m_track->getPointList();//read-only
  1006. if ( ! pointList )
  1007. return;
  1008. std::list<TrackPoint>::const_iterator pointIter = pointList->begin();
  1009. while ( pointIter != pointList->end() )
  1010. {
  1011. const TrackPoint *thisPoint = &(*pointIter);
  1012. ++pointIter;// next pointIter in this list, so then...
  1013. const TrackPoint *nextPoint = &(*pointIter);
  1014. if (thisPoint && thisPoint->m_distanceFromFirst < actualDistance)// I am after this point, and
  1015. {
  1016. Coord3D thisPointPos = thisPoint->m_position;
  1017. if (nextPoint && nextPoint->m_distanceFromFirst > actualDistance)
  1018. {
  1019. //I am between this point and the next
  1020. const Int handleFound = ((TrackPoint*)thisPoint)->getHandle();
  1021. Bool edge = (m_currentPointHandle != handleFound);
  1022. if ( setState )
  1023. {
  1024. m_inTunnel = thisPoint->m_isTunnelOrBridge;
  1025. if ( m_isLocomotive )// since only locomotives care about such things
  1026. {
  1027. // THE LOCOMOTIVE SNIFFS THE TRACK TO SMELL FOR THE NEXT STATION AND TUNNEL
  1028. if ( edge )
  1029. {
  1030. m_currentPointHandle = handleFound;
  1031. if ( thisPoint->m_isStation )
  1032. {
  1033. m_conductorState = APPLY_BRAKES;
  1034. m_disembark = FALSE;
  1035. TheAudio->removeAudioEvent(m_runningSound.getPlayingHandle());
  1036. }
  1037. else if ( thisPoint->m_isDisembark )
  1038. {
  1039. m_conductorState = APPLY_BRAKES;
  1040. m_disembark = TRUE;
  1041. TheAudio->removeAudioEvent(m_runningSound.getPlayingHandle());
  1042. }
  1043. else if ( thisPoint->m_isPingPong && conductorPullInfo.m_mostRecentSpecialPointHandle != handleFound )
  1044. {
  1045. conductorPullInfo.m_mostRecentSpecialPointHandle = handleFound;
  1046. m_conductorState = APPLY_BRAKES;
  1047. m_disembark = FALSE;
  1048. TheAudio->removeAudioEvent(m_runningSound.getPlayingHandle());
  1049. conductorPullInfo.m_direction = -conductorPullInfo.m_direction;
  1050. }
  1051. }
  1052. }
  1053. if ( edge && ! m_inTunnel )
  1054. {//play my clickety clack sound, `cause I just rode over a join IN the tracks
  1055. TheAudio->addAudioEvent( &m_clicketyClackSound );
  1056. m_clicketyClackSound.setPosition( getObject()->getPosition() );
  1057. m_clicketyClackSound.setVolume( (Real)conductorPullInfo.speed / 10.0f );//assumed max speed
  1058. }
  1059. }
  1060. Real difference = actualDistance - thisPoint->m_distanceFromFirst;
  1061. Coord3D delta = nextPoint->m_position;
  1062. delta.sub( &thisPointPos );
  1063. delta.normalize();
  1064. delta.scale( difference );
  1065. thisPointPos.add( &delta );
  1066. *pos = thisPointPos;//copy out
  1067. return;
  1068. }
  1069. else
  1070. *pos = thisPointPos;//copy out
  1071. }
  1072. }
  1073. //DEBUG_ASSERTCRASH(FALSE,("Railroad could not find a position on the path!"));
  1074. }
  1075. // ------------------------------------------------------------------------------------------------
  1076. /** CRC */
  1077. // ------------------------------------------------------------------------------------------------
  1078. void RailroadBehavior::crc( Xfer *xfer )
  1079. {
  1080. // extend base class
  1081. UpdateModule::crc( xfer );
  1082. } // end crc
  1083. // ------------------------------------------------------------------------------------------------
  1084. /** Xfer method
  1085. * Version Info:
  1086. * 1: Initial version
  1087. * 2: Added... like, everything.
  1088. **/
  1089. // ------------------------------------------------------------------------------------------------
  1090. void RailroadBehavior::xfer( Xfer *xfer )
  1091. {
  1092. // version
  1093. XferVersion currentVersion = 2;
  1094. XferVersion version = currentVersion;
  1095. xfer->xferVersion( &version, currentVersion );
  1096. // PLEASE NOTE:
  1097. // m_track and trackDataLoaded are indeed NOT xferred,
  1098. // since these are inited afresh within the update module,
  1099. if ( version >= 2 )
  1100. {
  1101. // extend base class
  1102. PhysicsBehavior::xfer( xfer );
  1103. //StationTask m_nextStationTask;
  1104. xfer->xferUser( &m_nextStationTask, sizeof( StationTask ) );
  1105. //ObjectID m_trailerID; ///< the ID of the object I am directly pulling
  1106. xfer->xferObjectID( &m_trailerID );
  1107. //Int m_currentPointHandle;
  1108. xfer->xferInt( &m_currentPointHandle );
  1109. //Int m_waitAtStationTimer;
  1110. xfer->xferInt( &m_waitAtStationTimer );
  1111. //Bool m_carriagesCreated; ///< TRUE once we have made all the cars in the train
  1112. xfer->xferBool( &m_carriagesCreated );
  1113. //Bool m_hasEverBeenHitched; /// has somebody ever hitched me? Remains true, even after puller dies.
  1114. xfer->xferBool( &m_hasEverBeenHitched );
  1115. //Bool m_waitingInWings; /// I have not entered the real track yet, so leave me alone
  1116. xfer->xferBool( &m_waitingInWings );
  1117. //Bool m_endOfLine; /// I have reached the end of a non looping track
  1118. xfer->xferBool( &m_endOfLine );
  1119. //Bool m_isLocomotive; ///< Am I a locomotive,
  1120. xfer->xferBool( &m_isLocomotive );
  1121. //Bool m_isLeadCarraige; ///< Am the carraige in front,
  1122. xfer->xferBool( &m_isLeadCarraige );
  1123. //Int m_wantsToBeLeadCarraige; ///< Am the carraige in front,
  1124. xfer->xferInt( &m_wantsToBeLeadCarraige );
  1125. //Bool m_disembark; ///< If I wait at a station, I should also evacuate everybody when I get theres
  1126. xfer->xferBool( &m_disembark );
  1127. //Bool m_inTunnel; ///< Am I in a tunnel, so I wil not snap to ground height, until the next waypoint,
  1128. xfer->xferBool( &m_inTunnel );
  1129. //ConductorState m_conductorState;
  1130. xfer->xferUser( &m_conductorState, sizeof( ConductorState ) );
  1131. xfer->xferUser( &m_anchorWaypointID, sizeof( WaypointID ) );
  1132. //PullInfo m_pullInfo;
  1133. m_pullInfo.xferPullInfo( xfer );
  1134. //PullInfo conductorPullInfo;
  1135. conductorPullInfo.xferPullInfo( xfer );
  1136. }
  1137. } // end xfer
  1138. void RailroadBehavior::PullInfo::xferPullInfo( Xfer *xfer )
  1139. {
  1140. XferVersion currentVersion = 1;
  1141. XferVersion version = currentVersion;
  1142. xfer->xferVersion( &version, currentVersion );
  1143. xfer->xferReal( &m_direction);
  1144. xfer->xferReal( &speed);
  1145. xfer->xferReal( &trackDistance);
  1146. xfer->xferCoord3D( &towHitchPosition );
  1147. xfer->xferInt( &m_mostRecentSpecialPointHandle );
  1148. xfer->xferUnsignedInt( &previousWaypoint );
  1149. xfer->xferUnsignedInt( &currentWaypoint );
  1150. }
  1151. // ------------------------------------------------------------------------------------------------
  1152. /** Load post process */
  1153. // ------------------------------------------------------------------------------------------------
  1154. void RailroadBehavior::loadPostProcess( void )
  1155. {
  1156. // extend base class
  1157. PhysicsBehavior::loadPostProcess();
  1158. //Bool m_trackDataLoaded; ///< have I TRIED to load track data, yet? I only try once!
  1159. m_trackDataLoaded = FALSE;
  1160. const RailroadBehaviorModuleData *modData = getRailroadBehaviorModuleData();
  1161. m_runningSound = modData->m_runningSound;
  1162. m_clicketyClackSound = modData->m_clicketyClackSound;
  1163. m_whistleSound = modData->m_whistleSound;
  1164. m_runningSound.setObjectID( getObject()->getID() );
  1165. m_whistleSound.setObjectID( getObject()->getID() ) ;
  1166. m_clicketyClackSound.setObjectID( getObject()->getID() ) ;
  1167. } // end loadPostProcess