Player.cpp 137 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557
  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: Player.cpp /////////////////////////////////////////////////////////
  24. //-----------------------------------------------------------------------------
  25. //
  26. // Westwood Studios Pacific.
  27. //
  28. // Confidential Information
  29. // Copyright (C) 2001 - All Rights Reserved
  30. //
  31. //-----------------------------------------------------------------------------
  32. //
  33. // Project: RTS3
  34. //
  35. // File name: Player.cpp
  36. //
  37. // Created: Steven Johnson, October 2001
  38. //
  39. // Desc: @todo
  40. //
  41. //-----------------------------------------------------------------------------
  42. #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
  43. #define DEFINE_SCIENCE_AVAILABILITY_NAMES
  44. #include "Common/ActionManager.h"
  45. #include "Common/BuildAssistant.h"
  46. #include "Common/CRCDebug.h"
  47. #include "Common/DisabledTypes.h"
  48. #include "Common/GameState.h"
  49. #include "Common/GlobalData.h"
  50. #include "Common/MessageStream.h"
  51. #include "Common/MiscAudio.h"
  52. #include "Common/PerfTimer.h"
  53. #include "Common/Player.h"
  54. #include "Common/PlayerList.h"
  55. #include "Common/PlayerTemplate.h"
  56. #include "Common/ProductionPrerequisite.h"
  57. #include "Common/Radar.h"
  58. #include "Common/ResourceGatheringManager.h"
  59. #include "Common/Team.h"
  60. #include "Common/ThingFactory.h"
  61. #include "Common/ThingTemplate.h"
  62. #include "Common/TunnelTracker.h"
  63. #include "Common/Upgrade.h"
  64. #include "Common/WellKnownKeys.h"
  65. #include "Common/Xfer.h"
  66. #include "Common/BitFlagsIO.h"
  67. #include "Common/SpecialPower.h"
  68. #include "GameClient/ControlBar.h"
  69. #include "GameClient/Drawable.h"
  70. #include "GameClient/Eva.h"
  71. #include "GameClient/GameClient.h"
  72. #include "GameClient/GameText.h"
  73. #include "GameLogic/AI.h"
  74. #include "GameLogic/AIPathfind.h"
  75. #include "GameLogic/AISkirmishPlayer.h"
  76. #include "GameLogic/ExperienceTracker.h"
  77. #include "GameLogic/Object.h"
  78. #include "GameLogic/Scripts.h"
  79. #include "GameLogic/PartitionManager.h"
  80. #include "GameLogic/SidesList.h"
  81. #include "GameLogic/Squad.h"
  82. #include "GameLogic/RankInfo.h"
  83. #include "GameLogic/ScriptEngine.h"
  84. #include "GameLogic/Weapon.h"
  85. #include "GameLogic/Module/AIUpdate.h"
  86. #include "GameLogic/Module/ContainModule.h"
  87. #include "GameLogic/Module/AutoDepositUpdate.h"
  88. #include "GameLogic/Module/StealthUpdate.h"
  89. #include "GameLogic/Module/SpecialPowerModule.h"
  90. #include "GameLogic/Module/SupplyTruckAIUpdate.h"
  91. #include "GameLogic/Module/BattlePlanUpdate.h"
  92. #include "GameLogic/Module/ProductionUpdate.h"
  93. #include "GameLogic/VictoryConditions.h"
  94. #include "GameNetwork/GameInfo.h"
  95. #ifdef _INTERNAL
  96. // for occasional debugging...
  97. //#pragma optimize("", off)
  98. //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
  99. #endif
  100. //Grey for neutral.
  101. #define NEUTRAL_PLAYER_COLOR 0xffffffff
  102. // ------------------------------------------------------------------------------------------------
  103. class ClosestKindOfData
  104. {
  105. public:
  106. ClosestKindOfData( void );
  107. //In
  108. KindOfMaskType m_setKindOf;
  109. KindOfMaskType m_clearKindOf;
  110. Object *m_source;
  111. //Out
  112. Object *m_closest;
  113. Real m_closestDistSq;
  114. };
  115. // ------------------------------------------------------------------------------------------------
  116. ClosestKindOfData::ClosestKindOfData( void )
  117. {
  118. m_setKindOf.clear();
  119. m_clearKindOf.clear();
  120. m_source = NULL;
  121. m_closest = NULL;
  122. m_closestDistSq = FLT_MAX;
  123. }
  124. // ------------------------------------------------------------------------------------------------
  125. static void findClosestKindOf( Object *obj, void *userData )
  126. {
  127. ClosestKindOfData *closestData = (ClosestKindOfData *)userData;
  128. if( ! obj->isKindOfMulti( closestData->m_setKindOf, closestData->m_clearKindOf ) )
  129. return; // Do nothing to the magic running total pointer man.
  130. // is this the closest one so far
  131. Real distSq = ThePartitionManager->getDistanceSquared( closestData->m_source, obj, FROM_CENTER_2D );
  132. if( distSq < closestData->m_closestDistSq )
  133. {
  134. closestData->m_closest = obj;
  135. closestData->m_closestDistSq = distSq;
  136. }
  137. }
  138. ///////////////////////////////////////////////////////////////////////////////////////////////////
  139. ///////////////////////////////////////////////////////////////////////////////////////////////////
  140. ///////////////////////////////////////////////////////////////////////////////////////////////////
  141. #ifdef DEBUG_CRC
  142. #define CRCDUMPBATTLEPLANBONUSES(x,y,z) dumpBattlePlanBonuses(x, #x, y, z, __FILE__, __LINE__, FALSE)
  143. #define DUMPBATTLEPLANBONUSES(x,y,z) dumpBattlePlanBonuses(x, #x, y, z, __FILE__, __LINE__, TRUE)
  144. AsciiString kindofMaskAsAsciiString(KindOfMaskType m)
  145. {
  146. AsciiString s;
  147. const char** kindofNames = KindOfMaskType::getBitNames();
  148. for (Int i=KINDOF_FIRST; i<KINDOF_COUNT; ++i)
  149. {
  150. if (m.test(i))
  151. {
  152. if (s.isNotEmpty())
  153. s.concat("|");
  154. s.concat(kindofNames[i]);
  155. }
  156. }
  157. if (s.isEmpty())
  158. s = "KINDOF_INVALID";
  159. return s;
  160. }
  161. void dumpBattlePlanBonuses(const BattlePlanBonuses *b, AsciiString name, const Player *p, const Object *o, AsciiString fname, Int line, Bool doDebugLog)
  162. {
  163. CRCDEBUG_LOG(("dumpBattlePlanBonuses() %s:%d %s\n Player %d(%ls) object %d(%s) armor:%g/%8.8X bombardment:%d, holdTheLine:%d, searchAndDestroy:%d sight:%g/%8.8X, valid:%s invalid:%s\n",
  164. fname.str(), line, name.str(),
  165. (p)?p->getPlayerIndex():-1, (p)?((Player *)p)->getPlayerDisplayName().str():L"<No Name>", (o)?o->getID():-1, (o)?o->getTemplate()->getName().str():"<No Name>",
  166. b->m_armorScalar, AS_INT(b->m_armorScalar),
  167. b->m_bombardment, b->m_holdTheLine, b->m_searchAndDestroy,
  168. b->m_sightRangeScalar, AS_INT(b->m_sightRangeScalar),
  169. kindofMaskAsAsciiString(b->m_validKindOf).str(),
  170. kindofMaskAsAsciiString(b->m_invalidKindOf).str()));
  171. if (!doDebugLog)
  172. return;
  173. DEBUG_LOG(("dumpBattlePlanBonuses() %s:%d %s\n Player %d(%ls) object %d(%s) armor:%g/%8.8X bombardment:%d, holdTheLine:%d, searchAndDestroy:%d sight:%g/%8.8X, valid:%s invalid:%s\n",
  174. fname.str(), line, name.str(),
  175. (p)?p->getPlayerIndex():-1, (p)?((Player *)p)->getPlayerDisplayName().str():L"<No Name>", (o)?o->getID():-1, (o)?o->getTemplate()->getName().str():"<No Name>",
  176. b->m_armorScalar, AS_INT(b->m_armorScalar),
  177. b->m_bombardment, b->m_holdTheLine, b->m_searchAndDestroy,
  178. b->m_sightRangeScalar, AS_INT(b->m_sightRangeScalar),
  179. kindofMaskAsAsciiString(b->m_validKindOf).str(),
  180. kindofMaskAsAsciiString(b->m_invalidKindOf).str()));
  181. }
  182. #else
  183. #define DUMPBATTLEPLANBONUSES(x,y,z) {}
  184. #define CRCDUMPBATTLEPLANBONUSES(x,y,z) {}
  185. #endif // DEBUG_CRC
  186. // ------------------------------------------------------------------------------------------------
  187. // ------------------------------------------------------------------------------------------------
  188. PlayerRelationMap::PlayerRelationMap( void )
  189. {
  190. } // end PlayerRelationMap
  191. // ------------------------------------------------------------------------------------------------
  192. // ------------------------------------------------------------------------------------------------
  193. PlayerRelationMap::~PlayerRelationMap( void )
  194. {
  195. // make sure the data is cleared
  196. m_map.clear();
  197. } // end ~PlayerRelationmap
  198. // ------------------------------------------------------------------------------------------------
  199. /** CRC */
  200. // ------------------------------------------------------------------------------------------------
  201. void PlayerRelationMap::crc( Xfer *xfer )
  202. {
  203. } // end crc
  204. // ------------------------------------------------------------------------------------------------
  205. /** Xfer method
  206. * Version Info:
  207. * 1: Initial version
  208. */
  209. // ------------------------------------------------------------------------------------------------
  210. void PlayerRelationMap::xfer( Xfer *xfer )
  211. {
  212. // version
  213. XferVersion currentVersion = 1;
  214. XferVersion version = currentVersion;
  215. xfer->xferVersion( &version, currentVersion );
  216. // player relation count
  217. PlayerRelationMapType::iterator playerRelationIt;
  218. UnsignedShort playerRelationCount = m_map.size();
  219. xfer->xferUnsignedShort( &playerRelationCount );
  220. // player relations
  221. Int playerIndex;
  222. Relationship r;
  223. if( xfer->getXferMode() == XFER_SAVE )
  224. {
  225. // go through all player relations
  226. for( playerRelationIt = m_map.begin(); playerRelationIt != m_map.end(); ++playerRelationIt )
  227. {
  228. // write player index
  229. playerIndex = (*playerRelationIt).first;
  230. xfer->xferInt( &playerIndex );
  231. // write relationship
  232. r = (*playerRelationIt).second;
  233. xfer->xferUser( &r, sizeof( Relationship ) );
  234. } // end for, playerRelationIt
  235. } // end if, save
  236. else
  237. {
  238. for( UnsignedShort i = 0; i < playerRelationCount; ++i )
  239. {
  240. // read player index
  241. xfer->xferInt( &playerIndex );
  242. // read relationship
  243. xfer->xferUser( &r, sizeof( Relationship ) );
  244. // assign relationship
  245. m_map[ playerIndex ] = r;
  246. } // end for, i
  247. } // end else, load
  248. } // end xfer
  249. // ------------------------------------------------------------------------------------------------
  250. /** Load post process */
  251. // ------------------------------------------------------------------------------------------------
  252. void PlayerRelationMap::loadPostProcess( void )
  253. {
  254. } // end loadPostProcess
  255. //=============================================================================
  256. Player::Player( Int playerIndex )
  257. {
  258. m_isPreorder = FALSE;
  259. m_isPlayerDead = FALSE;
  260. m_playerIndex = playerIndex;
  261. // allocate new relation map pools
  262. m_playerRelations = newInstance(PlayerRelationMap);
  263. m_teamRelations = newInstance(TeamRelationMap);
  264. m_upgradeList = NULL;
  265. m_pBuildList = NULL;
  266. m_ai = NULL;
  267. m_resourceGatheringManager = NULL;
  268. m_defaultTeam = NULL;
  269. m_radarCount = 0;
  270. m_disableProofRadarCount = 0;
  271. m_radarDisabled = FALSE;
  272. m_bombardBattlePlans = 0;
  273. m_holdTheLineBattlePlans = 0;
  274. m_searchAndDestroyBattlePlans = 0;
  275. m_tunnelSystem = NULL;
  276. m_playerTemplate = NULL;
  277. m_battlePlanBonuses = NULL;
  278. m_skillPointsModifier = 1.0f;
  279. //Added By Sadullah
  280. //Initializations inserted
  281. m_canBuildUnits = TRUE;
  282. m_canBuildBase = TRUE;
  283. m_cashBountyPercent = 0.0f;
  284. m_color = 0;
  285. m_currentSelection = NULL;
  286. m_rankLevel = 0;
  287. m_sciencePurchasePoints = 0;
  288. m_side = 0;
  289. m_baseSide = 0;
  290. m_skillPoints = 0;
  291. Int i;
  292. m_upgradeList = NULL;
  293. for(i = 0; i < NUM_HOTKEY_SQUADS; i++)
  294. {
  295. m_squads[i] = NULL;
  296. }
  297. //
  298. for (i = 0; i < MAX_PLAYER_COUNT; ++i)
  299. {
  300. m_attackedBy[i] = false;
  301. }
  302. m_attackedFrame = 0;
  303. m_unitsShouldHunt = FALSE;
  304. init( NULL );
  305. }
  306. //=============================================================================
  307. void Player::init(const PlayerTemplate* pt)
  308. {
  309. DEBUG_ASSERTCRASH(m_playerTeamPrototypes.size() == 0, ("Player::m_playerTeamPrototypes is not empty at game start!\n"));
  310. m_skillPointsModifier = 1.0f;
  311. m_attackedFrame = 0;
  312. m_isPreorder = FALSE;
  313. m_isPlayerDead = FALSE;
  314. m_radarCount = 0;
  315. m_disableProofRadarCount = 0;
  316. m_radarDisabled = FALSE;
  317. m_bombardBattlePlans = 0;
  318. m_holdTheLineBattlePlans = 0;
  319. m_searchAndDestroyBattlePlans = 0;
  320. if( m_battlePlanBonuses )
  321. {
  322. m_battlePlanBonuses->deleteInstance();
  323. m_battlePlanBonuses = NULL;
  324. }
  325. deleteUpgradeList();
  326. m_energy.init(this);
  327. m_stats.init();
  328. if (m_pBuildList != NULL)
  329. {
  330. m_pBuildList->deleteInstance();
  331. m_pBuildList = NULL;
  332. }
  333. m_defaultTeam = NULL;
  334. if (m_ai)
  335. {
  336. m_ai->deleteInstance();
  337. }
  338. m_ai = NULL;
  339. if( m_resourceGatheringManager )
  340. {
  341. m_resourceGatheringManager->deleteInstance();
  342. m_resourceGatheringManager = NULL;
  343. }
  344. for (Int i = 0; i < NUM_HOTKEY_SQUADS; ++i) {
  345. if (m_squads[i] != NULL) {
  346. m_squads[i]->deleteInstance();
  347. m_squads[i] = NULL;
  348. }
  349. m_squads[i] = newInstance(Squad);
  350. }
  351. if (m_currentSelection != NULL) {
  352. m_currentSelection->deleteInstance() ;
  353. m_currentSelection = NULL;
  354. }
  355. m_currentSelection = newInstance(Squad);
  356. if( m_tunnelSystem )
  357. {
  358. m_tunnelSystem->deleteInstance();
  359. m_tunnelSystem = NULL;
  360. }
  361. m_canBuildBase = true;
  362. m_canBuildUnits = true;
  363. m_observer = false;
  364. m_cashBountyPercent = 0.0f;
  365. m_listInScoreScreen = TRUE;
  366. m_unitsShouldHunt = FALSE;
  367. #if defined(_DEBUG) || defined(_INTERNAL)
  368. m_DEMO_ignorePrereqs = FALSE;
  369. m_DEMO_freeBuild = FALSE;
  370. #endif
  371. #if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE)
  372. m_DEMO_instantBuild = FALSE;
  373. #endif
  374. if (pt)
  375. {
  376. m_side = pt->getSide();
  377. m_baseSide = pt->getBaseSide();
  378. m_productionCostChanges = pt->getProductionCostChanges();
  379. m_productionTimeChanges = pt->getProductionTimeChanges();
  380. m_productionVeterancyLevels = pt->getProductionVeterancyLevels();
  381. m_color = pt->getPreferredColor()->getAsInt() | 0xff000000;
  382. m_nightColor = m_color;
  383. m_money = *pt->getMoney();
  384. m_money.setPlayerIndex(getPlayerIndex());
  385. m_handicap = *pt->getHandicap();
  386. if( m_money.countMoney() == 0 )
  387. {
  388. if ( TheGameInfo )
  389. {
  390. m_money = TheGameInfo->getStartingCash();
  391. }
  392. else
  393. {
  394. m_money = TheGlobalData->m_defaultStartingCash;
  395. }
  396. }
  397. m_playerDisplayName.clear();
  398. m_playerName.clear();
  399. m_playerNameKey = NAMEKEY_INVALID;
  400. m_playerType = PLAYER_COMPUTER;
  401. m_observer = pt->isObserver();
  402. m_isPlayerDead = m_observer; // observers are dead
  403. }
  404. else
  405. {
  406. // no player template? must be the neutral player!
  407. m_side = "";
  408. m_baseSide = "";
  409. m_productionCostChanges.clear();
  410. m_productionTimeChanges.clear();
  411. m_productionVeterancyLevels.clear();
  412. m_color = NEUTRAL_PLAYER_COLOR;
  413. m_nightColor = NEUTRAL_PLAYER_COLOR;
  414. m_money.init();
  415. m_handicap.init();
  416. m_playerDisplayName = UnicodeString::TheEmptyString;
  417. m_playerName = AsciiString::TheEmptyString;
  418. m_playerNameKey = NAMEKEY(AsciiString::TheEmptyString);
  419. m_playerType = PLAYER_COMPUTER;
  420. // neutral is always "allied" with self -- this is the only thing ever allied with neutral!
  421. setPlayerRelationship(this, ALLIES);
  422. }
  423. // reset each player
  424. m_scoreKeeper.reset(m_playerIndex);
  425. m_playerTemplate = pt;
  426. // reset rank info
  427. resetRank();
  428. m_sciencesDisabled.clear();
  429. m_sciencesHidden.clear();
  430. {
  431. SpecialPowerReadyTimerListIterator it = m_specialPowerReadyTimerList.begin();
  432. while(it != m_specialPowerReadyTimerList.end())
  433. {
  434. SpecialPowerReadyTimerType *sprt = &(*it);
  435. it = m_specialPowerReadyTimerList.erase( it );
  436. if(sprt)
  437. sprt->clear();
  438. }
  439. }
  440. KindOfPercentProductionChangeListIt it = m_kindOfPercentProductionChangeList.begin();
  441. while(it != m_kindOfPercentProductionChangeList.end())
  442. {
  443. KindOfPercentProductionChange *tof = *it;
  444. it = m_kindOfPercentProductionChangeList.erase( it );
  445. if(tof)
  446. tof->deleteInstance();
  447. }
  448. getAcademyStats()->init( this );
  449. //Always off at the beginning of a game! Only GameLogic::update has
  450. //the power to turn it on. Don't want to cause desyncs!
  451. m_logicalRetaliationModeEnabled = FALSE;
  452. }
  453. //=============================================================================
  454. Player::~Player()
  455. {
  456. m_defaultTeam = NULL;
  457. m_playerTemplate = NULL;
  458. for( PlayerTeamList::iterator it = m_playerTeamPrototypes.begin();
  459. it != m_playerTeamPrototypes.end(); ++it)
  460. {
  461. (*it)->friend_setOwningPlayer(NULL);
  462. }
  463. m_playerTeamPrototypes.clear(); // empty, but don't free the contents
  464. // delete the relation maps (the destructor clears the actual map if any data is present)
  465. m_teamRelations->deleteInstance();
  466. m_playerRelations->deleteInstance();
  467. for (Int i = 0; i < NUM_HOTKEY_SQUADS; ++i) {
  468. if (m_squads[i] != NULL) {
  469. m_squads[i]->deleteInstance();
  470. m_squads[i] = NULL;
  471. }
  472. }
  473. if (m_currentSelection != NULL) {
  474. m_currentSelection->deleteInstance();
  475. m_currentSelection = NULL;
  476. }
  477. if( m_battlePlanBonuses )
  478. {
  479. m_battlePlanBonuses->deleteInstance();
  480. m_battlePlanBonuses = NULL;
  481. }
  482. }
  483. //=============================================================================
  484. //DECLARE_PERF_TIMER(Player_getRelationship)
  485. Relationship Player::getRelationship(const Team *that) const
  486. {
  487. //USE_PERF_TIMER(Player_getRelationship)
  488. if (that)
  489. {
  490. // do we have an override for that particular team? if so, return it.
  491. if (!m_teamRelations->m_map.empty())
  492. {
  493. TeamRelationMapType::const_iterator it = m_teamRelations->m_map.find(that->getID());
  494. if (it != m_teamRelations->m_map.end())
  495. {
  496. return (*it).second;
  497. }
  498. }
  499. // hummm... well, do we have something for that team's player?
  500. if (!m_playerRelations->m_map.empty())
  501. {
  502. const Player* thatPlayer = that->getControllingPlayer();
  503. if (thatPlayer != NULL)
  504. {
  505. PlayerRelationMapType::const_iterator it = m_playerRelations->m_map.find(thatPlayer->getPlayerIndex());
  506. if (it != m_playerRelations->m_map.end())
  507. {
  508. return (*it).second;
  509. }
  510. }
  511. }
  512. }
  513. return NEUTRAL;
  514. }
  515. //=============================================================================
  516. void Player::setPlayerRelationship(const Player *that, Relationship r)
  517. {
  518. if (that != NULL)
  519. {
  520. // note that this creates the entry if it doesn't exist.
  521. m_playerRelations->m_map[that->getPlayerIndex()] = r;
  522. }
  523. }
  524. // ------------------------------------------------------------------------
  525. Bool Player::removePlayerRelationship(const Player *that)
  526. {
  527. if (!m_playerRelations->m_map.empty())
  528. {
  529. if (that == NULL)
  530. {
  531. m_playerRelations->m_map.clear();
  532. return true;
  533. }
  534. else
  535. {
  536. PlayerRelationMapType::iterator it = m_playerRelations->m_map.find(that->getPlayerIndex());
  537. if (it != m_playerRelations->m_map.end())
  538. {
  539. m_playerRelations->m_map.erase(it);
  540. return true;
  541. }
  542. }
  543. }
  544. return false;
  545. }
  546. //=============================================================================
  547. void Player::setTeamRelationship(const Team *that, Relationship r)
  548. {
  549. if (that != NULL)
  550. {
  551. // note that this creates the entry if it doesn't exist.
  552. m_teamRelations->m_map[that->getID()] = r;
  553. }
  554. }
  555. // ------------------------------------------------------------------------
  556. Bool Player::removeTeamRelationship(const Team *that)
  557. {
  558. if (!m_teamRelations->m_map.empty())
  559. {
  560. if (that == NULL)
  561. {
  562. m_teamRelations->m_map.clear();
  563. return true;
  564. }
  565. else
  566. {
  567. TeamRelationMapType::iterator it = m_teamRelations->m_map.find(that->getID());
  568. if (it != m_teamRelations->m_map.end())
  569. {
  570. m_teamRelations->m_map.erase(it);
  571. return true;
  572. }
  573. }
  574. }
  575. return false;
  576. }
  577. //=============================================================================
  578. void Player::setBuildList(BuildListInfo *pBuildList)
  579. {
  580. if (m_pBuildList != NULL)
  581. {
  582. m_pBuildList->deleteInstance();
  583. }
  584. m_pBuildList = pBuildList;
  585. }
  586. //=============================================================================
  587. void Player::addToBuildList(Object *obj)
  588. {
  589. BuildListInfo *newInfo = newInstance( BuildListInfo );
  590. newInfo->setObjectID(obj->getID());
  591. newInfo->setTemplateName(obj->getTemplate()->getName());
  592. newInfo->setLocation(*obj->getPosition());
  593. newInfo->setAngle(obj->getOrientation());
  594. newInfo->setNumRebuilds(0); // Can't rebuild.
  595. newInfo->setNextBuildList(m_pBuildList);
  596. m_pBuildList = newInfo;
  597. }
  598. //=============================================================================
  599. void Player::addToPriorityBuildList(AsciiString templateName, Coord3D *pos, Real angle)
  600. {
  601. BuildListInfo *newInfo = newInstance( BuildListInfo );
  602. newInfo->setTemplateName(templateName);
  603. newInfo->setLocation(*pos);
  604. newInfo->setAngle(angle);
  605. newInfo->markPriorityBuild();
  606. newInfo->setNumRebuilds(1); // Build once.
  607. newInfo->setNextBuildList(m_pBuildList);
  608. m_pBuildList = newInfo;
  609. }
  610. //=============================================================================
  611. void Player::update()
  612. {
  613. if (m_ai)
  614. m_ai->update();
  615. // Allow the teams this player owns to update themselves.
  616. for( PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); it != m_playerTeamPrototypes.end(); ++it )
  617. {
  618. for( DLINK_ITERATOR<Team> iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance() )
  619. {
  620. Team *team = iter.cur();
  621. if( !team )
  622. {
  623. continue;
  624. }
  625. team->updateGenericScripts();
  626. }
  627. }
  628. if( m_energy.getPowerSabotagedTillFrame() != 0 && TheGameLogic->getFrame() > m_energy.getPowerSabotagedTillFrame() )
  629. {
  630. m_energy.setPowerSabotagedTillFrame( 0 ); //Tells us we're no longer sabotaged for above check.
  631. onPowerBrownOutChange( !m_energy.hasSufficientPower() );
  632. }
  633. //Update the academy stats (this only checks applicable things that require a polling method)
  634. getAcademyStats()->update();
  635. //Kris: August 25, 2003 (DAY OF CODE LOCK -- NO NEW FEATURES, REALLY!)
  636. if( ThePlayerList->getLocalPlayer() == this )
  637. {
  638. UnsignedInt now = TheGameLogic->getFrame();
  639. //Only check and post the message once every second so we don't spam the message stream to account for lag.
  640. if( now % LOGICFRAMES_PER_SECOND == 0 )
  641. {
  642. if( TheGlobalData->m_clientRetaliationModeEnabled != isLogicalRetaliationModeEnabled() )
  643. {
  644. //Post a logical message that will switch the retaliation mode on or off.
  645. GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_ENABLE_RETALIATION_MODE );
  646. if( msg )
  647. {
  648. msg->appendIntegerArgument( getPlayerIndex() );
  649. msg->appendBooleanArgument( TheGlobalData->m_clientRetaliationModeEnabled );
  650. }
  651. }
  652. }
  653. }
  654. }
  655. //=============================================================================
  656. void Player::newMap()
  657. {
  658. if (m_ai)
  659. m_ai->newMap();
  660. }
  661. //=============================================================================
  662. void Player::setPlayerType(PlayerType t, Bool skirmish)
  663. {
  664. m_playerType = t;
  665. if (m_ai)
  666. {
  667. m_ai->deleteInstance();
  668. }
  669. m_ai = NULL;
  670. if (t == PLAYER_COMPUTER)
  671. {
  672. if (skirmish || TheAI->getAiData()->m_forceSkirmishAI) {
  673. // create AIPlayer and attach to this Player
  674. m_ai = newInstance(AISkirmishPlayer)( this );
  675. } else {
  676. // create AIPlayer and attach to this Player
  677. m_ai = newInstance(AIPlayer)( this );
  678. }
  679. }
  680. }
  681. //=============================================================================
  682. // This is called from PlayerList->newGame()
  683. //
  684. void Player::setDefaultTeam(void) {
  685. AsciiString tname;
  686. tname.set("team");
  687. tname.concat(m_playerName);
  688. Team *dt = TheTeamFactory->findTeam(tname);
  689. DEBUG_ASSERTCRASH(dt, ("no team"));
  690. if (dt) {
  691. m_defaultTeam = dt;
  692. dt->setActive();
  693. }
  694. }
  695. //=============================================================================
  696. // This is called from PlayerList->newGame()
  697. //
  698. void Player::initFromDict(const Dict* d)
  699. {
  700. AsciiString tmplname = d->getAsciiString(TheKey_playerFaction);
  701. const PlayerTemplate* pt = ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY(tmplname));
  702. DEBUG_ASSERTCRASH(pt != NULL, ("PlayerTemplate %s not found -- this is an obsolete map (please open and resave in WB)\n",tmplname.str()));
  703. init(pt);
  704. m_playerDisplayName = d->getUnicodeString(TheKey_playerDisplayName);
  705. AsciiString pname = d->getAsciiString(TheKey_playerName);
  706. m_playerName = pname;
  707. m_playerNameKey = NAMEKEY(pname);
  708. Bool exists;
  709. Bool skirmish = false;
  710. Bool forceHuman = false;
  711. if (d->getBool(TheKey_playerIsSkirmish, &exists))
  712. {
  713. // srj sez: check to ensure the map actually has a skirmish player... ordinarily it should, but
  714. // poorly-formed user maps might not, which would be bad, and could crash us later. so if it doesn't
  715. // actually have a skirmish player defined for this side, declare it nonskirmish... the player won't
  716. // really work, but it's better than crashing.
  717. for (Int spIdx = 0; spIdx < TheSidesList->getNumSkirmishSides(); ++spIdx)
  718. {
  719. AsciiString spTemplateName = TheSidesList->getSkirmishSideInfo(spIdx)->getDict()->getAsciiString(TheKey_playerFaction);
  720. const PlayerTemplate* spt = ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY(spTemplateName));
  721. if (spt && spt->getSide() == getSide())
  722. {
  723. skirmish = true;
  724. break;
  725. }
  726. }
  727. DEBUG_ASSERTCRASH(skirmish, ("Could not find skirmish player for side %s... quietly making into nonskirmish.", getSide().str()));
  728. if (!skirmish)
  729. forceHuman = true;
  730. }
  731. if (d->getBool(TheKey_playerIsHuman) || forceHuman)
  732. {
  733. setPlayerType(PLAYER_HUMAN, false);
  734. if (d->getBool(TheKey_playerIsPreorder, &exists))
  735. {
  736. m_isPreorder = TRUE;
  737. }
  738. if (TheSidesList->getNumSkirmishSides()>0) {
  739. // Human player gets scripts from CIVILIAN player.
  740. AsciiString mySide = "Civilian";
  741. Int i;
  742. Bool found = false;
  743. AsciiString qualTemplatePlayerName;
  744. for (i=0; i<TheSidesList->getNumSkirmishSides(); i++) {
  745. AsciiString templateName = TheSidesList->getSkirmishSideInfo(i)->getDict()->getAsciiString(TheKey_playerFaction);
  746. pt = ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY(templateName));
  747. if (pt && pt->getSide() == mySide) {
  748. qualTemplatePlayerName.format("%s%d", TheSidesList->getSkirmishSideInfo(i)->getDict()->getAsciiString(TheKey_playerName).str(), m_mpStartIndex);
  749. found = true;
  750. break;
  751. }
  752. }
  753. if (found && TheSidesList->getSkirmishSideInfo(i)->getScriptList()) {
  754. AsciiString qualifier;
  755. qualifier.format("%d", m_mpStartIndex);
  756. ScriptList *scripts = TheSidesList->getSkirmishSideInfo(i)->getScriptList()->duplicateAndQualify(
  757. qualifier, qualTemplatePlayerName, pname);
  758. if (TheSidesList->getSideInfo(getPlayerIndex())->getScriptList()) {
  759. TheSidesList->getSideInfo(getPlayerIndex())->getScriptList()->deleteInstance();
  760. }
  761. TheSidesList->getSideInfo(getPlayerIndex())->setScriptList(scripts);
  762. TheSidesList->getSkirmishSideInfo(i)->getScriptList()->deleteInstance();
  763. TheSidesList->getSkirmishSideInfo(i)->setScriptList(NULL);
  764. }
  765. }
  766. skirmish = false;
  767. }
  768. else
  769. {
  770. setPlayerType(PLAYER_COMPUTER, skirmish);
  771. }
  772. m_mpStartIndex = d->getInt(TheKey_multiplayerStartIndex, &exists);
  773. if (skirmish) {
  774. // Copy and qualify scripts, and teams.
  775. AsciiString mySide = getSide();
  776. Int i, skirmishNdx;
  777. Bool found = false;
  778. AsciiString qualTemplatePlayerName;
  779. for (skirmishNdx=0; skirmishNdx<TheSidesList->getNumSkirmishSides(); skirmishNdx++) {
  780. AsciiString templateName = TheSidesList->getSkirmishSideInfo(skirmishNdx)->getDict()->getAsciiString(TheKey_playerFaction);
  781. pt = ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY(templateName));
  782. if (pt && pt->getSide() == mySide) {
  783. qualTemplatePlayerName.format("%s%d", TheSidesList->getSkirmishSideInfo(skirmishNdx)->getDict()->getAsciiString(TheKey_playerName).str(), m_mpStartIndex);
  784. found = true;
  785. break;
  786. }
  787. }
  788. Int diffInt = d->getInt(TheKey_skirmishDifficulty, &exists);
  789. GameDifficulty difficulty = TheScriptEngine->getGlobalDifficulty();
  790. if (exists)
  791. {
  792. difficulty = (GameDifficulty) diffInt;
  793. }
  794. if (m_ai)
  795. {
  796. m_ai->setAIDifficulty(difficulty);
  797. }
  798. if (!found)
  799. {
  800. DEBUG_CRASH(("Could not find skirmish player for side %s", mySide.str()));
  801. } else {
  802. m_playerName = qualTemplatePlayerName;
  803. AsciiString qualifier;
  804. qualifier.format("%d", m_mpStartIndex);
  805. ScriptList *scripts = TheSidesList->getSkirmishSideInfo(skirmishNdx)->getScriptList()->duplicateAndQualify(
  806. qualifier, qualTemplatePlayerName, pname);
  807. ScriptList* slist = TheSidesList->getSideInfo(getPlayerIndex())->getScriptList();
  808. if (slist)
  809. {
  810. slist->deleteInstance();
  811. }
  812. TheSidesList->getSideInfo(getPlayerIndex())->setScriptList(scripts);
  813. for (i=0; i<TheSidesList->getNumTeams(); i++) {
  814. if (TheSidesList->getTeamInfo(i)->getDict()->getAsciiString(TheKey_teamOwner) == pname)
  815. {
  816. // Remove any teams in this player.
  817. TheSidesList->removeTeam(i);
  818. i--;
  819. }
  820. }
  821. // Now add teams.
  822. AsciiString originalPlayerName = TheSidesList->getSkirmishSideInfo(skirmishNdx)->getDict()->getAsciiString(TheKey_playerName);
  823. for (i=0; i<TheSidesList->getNumSkirmishTeams(); i++) {
  824. if (TheSidesList->getSkirmishTeamInfo(i)->getDict()->getAsciiString(TheKey_teamOwner) == originalPlayerName)
  825. {
  826. Dict teamDict(*TheSidesList->getSkirmishTeamInfo(i)->getDict());
  827. AsciiString teamName = teamDict.getAsciiString(TheKey_teamName);
  828. AsciiString newName;
  829. newName.format("%s%d", teamDict.getAsciiString(TheKey_teamName).str(), m_mpStartIndex);
  830. if (TheSidesList->findTeamInfo(newName)) continue;
  831. teamDict.setAsciiString(TheKey_teamOwner, pname);
  832. teamDict.setAsciiString(TheKey_teamName, newName);
  833. // qualify scripts.
  834. NameKeyType nameKeys[] =
  835. {
  836. TheKey_teamOnCreateScript,
  837. TheKey_teamOnIdleScript,
  838. TheKey_teamOnUnitDestroyedScript,
  839. TheKey_teamOnDestroyedScript,
  840. TheKey_teamEnemySightedScript,
  841. TheKey_teamAllClearScript,
  842. TheKey_teamProductionCondition
  843. };
  844. Int j;
  845. const Int numKeys = sizeof(nameKeys) / sizeof(NameKeyType);
  846. AsciiString tmpStr;
  847. for (j = 0; j < numKeys; ++j)
  848. {
  849. tmpStr = teamDict.getAsciiString(nameKeys[j], &exists);
  850. if (exists && !tmpStr.isEmpty())
  851. {
  852. newName.format("%s%d", tmpStr.str(), m_mpStartIndex);
  853. teamDict.setAsciiString(nameKeys[j], newName);
  854. }
  855. }
  856. // Now do the TheKey_teamGenericScriptHookN (where N can be from 0 to 15.)
  857. for (j = 0; j < MAX_GENERIC_SCRIPTS; ++j) {
  858. AsciiString keyName;
  859. keyName.format("%s%d", TheNameKeyGenerator->keyToName(TheKey_teamGenericScriptHook).str(), j);
  860. tmpStr = teamDict.getAsciiString(NAMEKEY(keyName), &exists);
  861. if (exists && !tmpStr.isEmpty())
  862. {
  863. newName.format("%s%d", tmpStr.str(), m_mpStartIndex);
  864. teamDict.setAsciiString(NAMEKEY(keyName), newName);
  865. }
  866. }
  867. // Done. Now add the team.
  868. TheSidesList->addTeam(&teamDict);
  869. }
  870. }
  871. }
  872. }
  873. if( m_resourceGatheringManager )
  874. {
  875. m_resourceGatheringManager->deleteInstance();
  876. m_resourceGatheringManager = NULL;
  877. }
  878. m_resourceGatheringManager = newInstance(ResourceGatheringManager);
  879. if( m_tunnelSystem )
  880. {
  881. m_tunnelSystem->deleteInstance();
  882. m_tunnelSystem = NULL;
  883. }
  884. m_tunnelSystem = newInstance(TunnelTracker);
  885. m_handicap.readFromDict(d);
  886. /// @todo Ack! the todo in PlayerList::reset() mentioning the need for a Player::reset() really needs to get done.
  887. m_playerRelations->m_map.clear(); // For now, it has been decided to just fix this one. Dear god me must reset.
  888. m_teamRelations->m_map.clear(); // For now, it has been decided to just fix this one. Dear god me must reset.
  889. Int i;
  890. for ( i = 0; i < MAX_PLAYER_COUNT; ++i ) // For now, it has been decided to just fix this one. Dear god me must reset.
  891. {
  892. m_attackedBy[i] = false;
  893. }
  894. Int c = d->getInt(TheKey_playerColor, &exists);
  895. if (exists)
  896. {
  897. m_color = c | 0xff000000;
  898. m_nightColor = m_color;
  899. }
  900. c = d->getInt(TheKey_playerNightColor, &exists);
  901. if (exists)
  902. {
  903. m_nightColor = c | 0xff000000;
  904. }
  905. Int m = d->getInt(TheKey_playerStartMoney, &exists);
  906. if (exists)
  907. m_money.deposit(m);
  908. for ( i = 0; i < NUM_HOTKEY_SQUADS; ++i ) {
  909. if (m_squads[i] != NULL)
  910. {
  911. m_squads[i]->deleteInstance();
  912. m_squads[i] = NULL;
  913. }
  914. m_squads[i] = newInstance( Squad );
  915. }
  916. if (m_currentSelection != NULL) {
  917. m_currentSelection->deleteInstance();
  918. m_currentSelection = NULL;
  919. }
  920. m_currentSelection = newInstance( Squad );
  921. }
  922. //=============================================================================
  923. void Player::becomingTeamMember(Object *obj, Bool yes)
  924. {
  925. if (!obj)
  926. return;
  927. // energy production/consumption hooks, note we ignore things that are UNDER_CONSTRUCTION
  928. if( !obj->getStatusBits().test( OBJECT_STATUS_UNDER_CONSTRUCTION ) )
  929. {
  930. obj->friend_adjustPowerForPlayer(yes);
  931. } // end if
  932. // when we capture a building, we need to see if there's an AutoDepositUpdate hooked to it,
  933. // if so, award the cash bonus
  934. if(this != ThePlayerList->getNeutralPlayer() && yes)
  935. {
  936. NameKeyType key_AutoDepositUpdate = NAMEKEY("AutoDepositUpdate");
  937. AutoDepositUpdate *adu = (AutoDepositUpdate *)obj->findUpdateModule(key_AutoDepositUpdate);
  938. if (adu != NULL) {
  939. adu->awardInitialCaptureBonus( this );
  940. }
  941. }
  942. if( getNumBattlePlansActive() > 0 && obj->areModulesReady() )
  943. {
  944. if( yes )
  945. {
  946. //We are entering a team with active battle plans so add it's bonuses now
  947. applyBattlePlanBonusesForObject( obj );
  948. }
  949. else
  950. {
  951. //We are leaving a team with active battle plans so remove them now.
  952. removeBattlePlanBonusesForObject( obj );
  953. }
  954. }
  955. if (obj->isKindOf(KINDOF_DOZER)
  956. && obj->getAIUpdateInterface()
  957. && obj->getAIUpdateInterface()->isIdle())
  958. {
  959. // Need to remove it from the pick a peasant button
  960. if (yes)
  961. TheInGameUI->addIdleWorker(obj);
  962. else
  963. TheInGameUI->removeIdleWorker(obj, getPlayerIndex());
  964. }
  965. }
  966. //=============================================================================
  967. void Player::becomingLocalPlayer(Bool yes)
  968. {
  969. if (yes)
  970. {
  971. // This changes the color of the little dot on the upper right side of the screen indicating
  972. // which team is under control.
  973. if( TheGameClient )
  974. {
  975. RGBColor rgb;
  976. rgb.setFromInt(m_color);
  977. TheGameClient->setTeamColor(REAL_TO_INT(rgb.red*255), REAL_TO_INT(rgb.green*255), REAL_TO_INT(rgb.blue*255));
  978. }
  979. if( ThePartitionManager )
  980. {
  981. ObjectIterator *iter = ThePartitionManager->iterateAllObjects();
  982. for( Object* object = iter->first(); object; object = iter->next() )
  983. {
  984. // Added support for updating the perceptions of garrisoned buildings containing enemy stealth units.
  985. // When changing teams, it is necessary to update this information.
  986. ContainModuleInterface *contain = object->getContain();
  987. if( contain )
  988. {
  989. contain->recalcApparentControllingPlayer();
  990. TheRadar->removeObject( object );
  991. TheRadar->addObject( object );
  992. }
  993. if( object->isKindOf( KINDOF_DISGUISER ) )
  994. {
  995. //KM -- August 2002:
  996. //Added support for disguised objects, based on relationships, we either show the real color or the disguised color.
  997. Drawable *draw = object->getDrawable();
  998. if( draw )
  999. {
  1000. StealthUpdate *update = object->getStealth();
  1001. if( update && update->isDisguised() )
  1002. {
  1003. Player *disguisedPlayer = ThePlayerList->getNthPlayer( update->getDisguisedPlayerIndex() );
  1004. if( getRelationship( object->getTeam() ) != ALLIES && isPlayerActive() )
  1005. {
  1006. //Neutrals and enemies will see this disguised unit as the team it's disguised as.
  1007. if (TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT)
  1008. draw->setIndicatorColor( disguisedPlayer->getPlayerNightColor());
  1009. else
  1010. draw->setIndicatorColor( disguisedPlayer->getPlayerColor() );
  1011. }
  1012. else
  1013. {
  1014. //Otherwise, the color will show up as the team it really belongs to.
  1015. if (TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT)
  1016. draw->setIndicatorColor(object->getNightIndicatorColor());
  1017. else
  1018. draw->setIndicatorColor( object->getIndicatorColor() );
  1019. }
  1020. TheRadar->removeObject( object );
  1021. TheRadar->addObject( object );
  1022. }
  1023. }
  1024. }
  1025. }
  1026. iter->deleteInstance();
  1027. }
  1028. if( TheControlBar )
  1029. TheControlBar->markUIDirty();
  1030. }
  1031. else
  1032. {
  1033. // nothing to do
  1034. }
  1035. }
  1036. //-------------------------------------------------------------------------------------------------
  1037. /** Is this player a skirmish ai player? */
  1038. //-------------------------------------------------------------------------------------------------
  1039. Bool Player::isSkirmishAIPlayer( void )
  1040. {
  1041. return m_ai ? m_ai->isSkirmishAI() : false;
  1042. }
  1043. //----------------------------------------------------------------------------------------------------------
  1044. /**
  1045. * Find a good spot to fire a superweapon.
  1046. */
  1047. Bool Player::computeSuperweaponTarget(const SpecialPowerTemplate *power, Coord3D *retPos, Int playerNdx, Real weaponRadius)
  1048. {
  1049. if (m_ai) {
  1050. return m_ai->computeSuperweaponTarget(power, retPos, playerNdx, weaponRadius);
  1051. }
  1052. return FALSE;
  1053. }
  1054. //-------------------------------------------------------------------------------------------------
  1055. /** Get this player's current enemy. NOTE - Can be NULL. */
  1056. //-------------------------------------------------------------------------------------------------
  1057. Player *Player::getCurrentEnemy( void )
  1058. {
  1059. return m_ai?m_ai->getAiEnemy():NULL;
  1060. }
  1061. //-------------------------------------------------------------------------------------------------
  1062. // PlayerObjectFindInfo is used to find a player's object. For example, we iterate through
  1063. // to find a player's command center, or a specific building capable of firing the specified
  1064. // special power.
  1065. //
  1066. // if he has none, return null.
  1067. // if he has multiple, return one arbitrarily.
  1068. //-------------------------------------------------------------------------------------------------
  1069. //-------------------------------------------------------------------------------------------------
  1070. // Iterator data struct
  1071. //-------------------------------------------------------------------------------------------------
  1072. struct PlayerObjectFindInfo
  1073. {
  1074. Player* player;
  1075. Object* obj;
  1076. SpecialPowerType spType;
  1077. const ThingTemplate *thing;
  1078. UnsignedInt lowestReadyFrame;
  1079. UnsignedInt highestPercentage;
  1080. UnsignedInt numReady;
  1081. };
  1082. //-------------------------------------------------------------------------------------------------
  1083. // Iterator function
  1084. // Find the first available command center that is naturally ours (not captured from enemy).
  1085. //-------------------------------------------------------------------------------------------------
  1086. static void doFindCommandCenter(Object* obj, void* userData)
  1087. {
  1088. if (!obj)
  1089. return;
  1090. PlayerObjectFindInfo* info = (PlayerObjectFindInfo*)userData;
  1091. if (info->obj == NULL
  1092. && obj->isKindOf(KINDOF_COMMANDCENTER)
  1093. && obj->getTemplate()->getDefaultOwningSide() == info->player->getSide()
  1094. && !obj->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION)
  1095. && !obj->testStatus(OBJECT_STATUS_SOLD))
  1096. {
  1097. info->obj = obj;
  1098. }
  1099. }
  1100. //-------------------------------------------------------------------------------------------------
  1101. // Iterator function
  1102. // Find first object capable of firing specified special power right now.
  1103. //-------------------------------------------------------------------------------------------------
  1104. static void doFindSpecialPowerSourceObject( Object *obj, void *userData )
  1105. {
  1106. PlayerObjectFindInfo* info = (PlayerObjectFindInfo*)userData;
  1107. if( info->lowestReadyFrame == 0 )
  1108. {
  1109. //We already found the best case scenario, so no need to iterate any more.
  1110. return;
  1111. }
  1112. if( !obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION )
  1113. && !obj->testStatus( OBJECT_STATUS_SOLD )
  1114. && !obj->isEffectivelyDead() )
  1115. {
  1116. if( info->spType == SPECIAL_INVALID && obj->hasAnySpecialPower() )
  1117. {
  1118. //We just care about find an object that has *any* shortcut capable special power.
  1119. //Iterate through the special power modules and look for one.
  1120. SpecialPowerModuleInterface *spmInterface = obj->findAnyShortcutSpecialPowerModuleInterface();
  1121. if( spmInterface && !spmInterface->isScriptOnly() )
  1122. {
  1123. info->obj = obj;
  1124. info->lowestReadyFrame = 0;
  1125. return;
  1126. }
  1127. }
  1128. else if( obj->hasSpecialPower( info->spType ) )
  1129. {
  1130. SpecialPowerModuleInterface *spmInterface = obj->findSpecialPowerModuleInterface( info->spType );
  1131. if( spmInterface && !spmInterface->isScriptOnly() )
  1132. {
  1133. UnsignedInt readyFrame = spmInterface->getReadyFrame();
  1134. #if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE)
  1135. // Everything is ready if timers are debug off'd
  1136. if( ! TheGlobalData->m_specialPowerUsesDelay )
  1137. readyFrame = 0;
  1138. #endif
  1139. // A disabled guy should only be considered as a last resort. We need it to be counted
  1140. // so that a disabled button can appear on the shortcut.
  1141. if( obj->isDisabled() )
  1142. readyFrame = UINT_MAX - 10;
  1143. if( readyFrame < TheGameLogic->getFrame())
  1144. {
  1145. //This special power is ready now and matches, so simply return the
  1146. //first one.
  1147. info->obj = obj;
  1148. info->lowestReadyFrame = 0;
  1149. return;
  1150. }
  1151. else if( readyFrame < info->lowestReadyFrame )
  1152. {
  1153. //This special power isn't ready, but it is going to be ready sooner than any others
  1154. //we checked (or it's the first one we checked).
  1155. info->obj = obj;
  1156. info->lowestReadyFrame = readyFrame;
  1157. return;
  1158. }
  1159. }
  1160. }
  1161. }
  1162. }
  1163. //-------------------------------------------------------------------------------------------------
  1164. // Iterator function
  1165. // Count number of specified special powers that are ready to fire now.
  1166. //-------------------------------------------------------------------------------------------------
  1167. static void doCountSpecialPowersReady( Object *obj, void *userData )
  1168. {
  1169. PlayerObjectFindInfo* info = (PlayerObjectFindInfo*)userData;
  1170. if( !obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION )
  1171. && !obj->testStatus( OBJECT_STATUS_SOLD )
  1172. && !obj->isEffectivelyDead() )
  1173. {
  1174. if( obj->hasSpecialPower( info->spType ) )
  1175. {
  1176. SpecialPowerModuleInterface *spmInterface = obj->findSpecialPowerModuleInterface( info->spType );
  1177. if( spmInterface && !spmInterface->isScriptOnly() )
  1178. {
  1179. if( spmInterface->getSpecialPowerTemplate()->isSharedNSync() && info->numReady == 1 )
  1180. {
  1181. //Shared powers don't stack after the first one is counted.
  1182. return;
  1183. }
  1184. UnsignedInt readyFrame = spmInterface->getReadyFrame();
  1185. #if defined(_DEBUG) || defined(_INTERNAL) || defined(_ALLOW_DEBUG_CHEATS_IN_RELEASE)
  1186. // Everything is ready if timers are debug off'd
  1187. if( ! TheGlobalData->m_specialPowerUsesDelay )
  1188. readyFrame = 0;
  1189. #endif
  1190. // A disabled guy should only be considered as a last resort. We do not want him counted here
  1191. // so that Disabled guys do not go in to the number on the shortcut button.
  1192. if( obj->isDisabled() )
  1193. readyFrame = UINT_MAX - 10;
  1194. if( readyFrame < TheGameLogic->getFrame())
  1195. {
  1196. //This special power is ready now and matches, so simply return the
  1197. //first one.
  1198. info->numReady++;
  1199. }
  1200. }
  1201. }
  1202. }
  1203. }
  1204. //-------------------------------------------------------------------------------------------------
  1205. static void doFindMostReadyWeaponForThing( Object *obj, void *userData )
  1206. {
  1207. PlayerObjectFindInfo* info = (PlayerObjectFindInfo*)userData;
  1208. if( info->highestPercentage >= 100 )
  1209. {
  1210. //We already found the best case scenario, so no need to iterate any more.
  1211. return;
  1212. }
  1213. if( info->thing->isEquivalentTo( obj->getTemplate() ) )
  1214. {
  1215. if( !obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION )
  1216. && !obj->testStatus( OBJECT_STATUS_SOLD )
  1217. && !obj->isEffectivelyDead() )
  1218. {
  1219. if( obj->hasAnyWeapon() )
  1220. {
  1221. UnsignedInt percentage = obj->getMostPercentReadyToFireAnyWeapon();
  1222. if( percentage > info->highestPercentage )
  1223. {
  1224. //This weapon is more ready than any others we've checked.
  1225. info->obj = obj;
  1226. info->highestPercentage = percentage;
  1227. return;
  1228. }
  1229. }
  1230. }
  1231. }
  1232. }
  1233. //-------------------------------------------------------------------------------------------------
  1234. static void doFindMostReadySpecialPowerForThing( Object *obj, void *userData )
  1235. {
  1236. PlayerObjectFindInfo* info = (PlayerObjectFindInfo*)userData;
  1237. if( info->highestPercentage >= 100 )
  1238. {
  1239. //We already found the best case scenario, so no need to iterate any more.
  1240. return;
  1241. }
  1242. if( info->thing->isEquivalentTo( obj->getTemplate() ) )
  1243. {
  1244. if( !obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION )
  1245. && !obj->testStatus( OBJECT_STATUS_SOLD )
  1246. && !obj->isEffectivelyDead() )
  1247. {
  1248. // search the modules for the one with the matching template
  1249. for( BehaviorModule** m = obj->getBehaviorModules(); *m; ++m )
  1250. {
  1251. SpecialPowerModuleInterface* sp = (*m)->getSpecialPower();
  1252. if (!sp)
  1253. continue;
  1254. UnsignedInt percentage = sp->getPercentReady();
  1255. if( percentage > info->highestPercentage )
  1256. {
  1257. //This weapon is more ready than any others we've checked.
  1258. info->obj = obj;
  1259. info->highestPercentage = percentage;
  1260. }
  1261. }
  1262. }
  1263. }
  1264. }
  1265. //-------------------------------------------------------------------------------------------------
  1266. static void doFindExistingObjectWithThingTemplate( Object *obj, void *userData )
  1267. {
  1268. PlayerObjectFindInfo* info = (PlayerObjectFindInfo*)userData;
  1269. if( info->obj )
  1270. {
  1271. //We already found a matching obj, so return
  1272. return;
  1273. }
  1274. if( info->thing->isEquivalentTo( obj->getTemplate() ) )
  1275. {
  1276. if( !obj->testStatus( OBJECT_STATUS_UNDER_CONSTRUCTION )
  1277. && !obj->testStatus( OBJECT_STATUS_SOLD )
  1278. && !obj->isEffectivelyDead() )
  1279. {
  1280. //We found one.
  1281. info->obj = obj;
  1282. }
  1283. }
  1284. }
  1285. //-------------------------------------------------------------------------------------------------
  1286. Object* Player::findNaturalCommandCenter()
  1287. {
  1288. PlayerObjectFindInfo info;
  1289. info.player = this;
  1290. info.obj = NULL;
  1291. iterateObjects(doFindCommandCenter, &info);
  1292. return info.obj;
  1293. }
  1294. //-------------------------------------------------------------------------------------------------
  1295. Object* Player::findMostReadyShortcutSpecialPowerOfType( SpecialPowerType spType )
  1296. {
  1297. PlayerObjectFindInfo info;
  1298. info.player = this;
  1299. info.obj = NULL;
  1300. info.spType = spType;
  1301. info.lowestReadyFrame = 0xffffffff;
  1302. iterateObjects( doFindSpecialPowerSourceObject, &info );
  1303. return info.obj;
  1304. }
  1305. //-------------------------------------------------------------------------------------------------
  1306. Object* Player::findMostReadyShortcutWeaponForThing( const ThingTemplate *thing, UnsignedInt &mostReadyPercentage )
  1307. {
  1308. PlayerObjectFindInfo info;
  1309. info.player = this;
  1310. info.obj = NULL;
  1311. info.thing = thing;
  1312. info.highestPercentage = 0;
  1313. iterateObjects( doFindMostReadyWeaponForThing, &info );
  1314. mostReadyPercentage = info.highestPercentage;
  1315. return info.obj;
  1316. }
  1317. //-------------------------------------------------------------------------------------------------
  1318. Object* Player::findMostReadyShortcutSpecialPowerForThing( const ThingTemplate *thing, UnsignedInt &mostReadyPercentage )
  1319. {
  1320. PlayerObjectFindInfo info;
  1321. info.player = this;
  1322. info.obj = NULL;
  1323. info.thing = thing;
  1324. info.highestPercentage = 0;
  1325. iterateObjects( doFindMostReadySpecialPowerForThing, &info );
  1326. mostReadyPercentage = info.highestPercentage;
  1327. return info.obj;
  1328. }
  1329. //-------------------------------------------------------------------------------------------------
  1330. Object* Player::findAnyExistingObjectWithThingTemplate( const ThingTemplate *thing )
  1331. {
  1332. PlayerObjectFindInfo info;
  1333. info.player = this;
  1334. info.obj = NULL;
  1335. info.thing = thing;
  1336. iterateObjects( doFindExistingObjectWithThingTemplate, &info );
  1337. return info.obj;
  1338. }
  1339. //-------------------------------------------------------------------------------------------------
  1340. // Finds a short-cut firing special power of any type arbitrarily.
  1341. //-------------------------------------------------------------------------------------------------
  1342. Bool Player::hasAnyShortcutSpecialPower()
  1343. {
  1344. PlayerObjectFindInfo info;
  1345. info.player = this;
  1346. info.obj = NULL;
  1347. info.spType = SPECIAL_INVALID; //Invalid dictates that we don't care about the type.
  1348. info.lowestReadyFrame = 0xffffffff;
  1349. iterateObjects( doFindSpecialPowerSourceObject, &info );
  1350. return info.obj;
  1351. }
  1352. //-------------------------------------------------------------------------------------------------
  1353. Int Player::countReadyShortcutSpecialPowersOfType( SpecialPowerType spType )
  1354. {
  1355. PlayerObjectFindInfo info;
  1356. info.spType = spType;
  1357. info.numReady = 0;
  1358. iterateObjects( doCountSpecialPowersReady, &info );
  1359. return info.numReady;
  1360. }
  1361. //-------------------------------------------------------------------------------------------------
  1362. /** Difficulty level for this player */
  1363. //-------------------------------------------------------------------------------------------------
  1364. GameDifficulty Player::getPlayerDifficulty(void) const
  1365. {
  1366. if (m_ai)
  1367. {
  1368. return m_ai->getAIDifficulty();
  1369. }
  1370. return TheScriptEngine->getGlobalDifficulty();
  1371. }
  1372. //-------------------------------------------------------------------------------------------------
  1373. /** Do any bridges need repair, and if so repair them. */
  1374. //-------------------------------------------------------------------------------------------------
  1375. Bool Player::checkBridges(Object *unit, Waypoint *way)
  1376. {
  1377. return m_ai?m_ai->checkBridges(unit, way):false;
  1378. }
  1379. //-------------------------------------------------------------------------------------------------
  1380. /** Do any bridges need repair, and if so repair them. */
  1381. //-------------------------------------------------------------------------------------------------
  1382. Bool Player::getAiBaseCenter(Coord3D *pos)
  1383. {
  1384. return m_ai?m_ai->getBaseCenter(pos):false;
  1385. }
  1386. //-------------------------------------------------------------------------------------------------
  1387. /** Repair bridge or structure. */
  1388. //-------------------------------------------------------------------------------------------------
  1389. void Player::repairStructure(ObjectID structureID)
  1390. {
  1391. if (m_ai)
  1392. {
  1393. m_ai->repairStructure(structureID);
  1394. }
  1395. }
  1396. //-------------------------------------------------------------------------------------------------
  1397. /** A unit was just created and is ready to control */
  1398. //-------------------------------------------------------------------------------------------------
  1399. void Player::onUnitCreated( Object *factory, Object *unit )
  1400. {
  1401. // When a a unit is completed, it becomes "real" as far as scripting is
  1402. // concerned. jba.
  1403. TheScriptEngine->notifyOfObjectCreationOrDestruction();
  1404. // increment our scorekeeper
  1405. m_scoreKeeper.addObjectBuilt(unit);
  1406. // ai notification callback
  1407. if( m_ai )
  1408. m_ai->onUnitProduced( factory, unit );
  1409. } // end onUnitCreated
  1410. //-------------------------------------------------------------------------------------------------
  1411. /** Is the nearest supply source safe? */
  1412. //-------------------------------------------------------------------------------------------------
  1413. Bool Player::isSupplySourceSafe( Int minSupplies )
  1414. {
  1415. // ai query
  1416. if( m_ai )
  1417. return m_ai->isSupplySourceSafe( minSupplies );
  1418. return true;
  1419. } // isSupplySourceSafe
  1420. //-------------------------------------------------------------------------------------------------
  1421. /** Is a supply source attacked? */
  1422. //-------------------------------------------------------------------------------------------------
  1423. Bool Player::isSupplySourceAttacked( void )
  1424. {
  1425. // ai query
  1426. if( m_ai )
  1427. return m_ai->isSupplySourceAttacked( );
  1428. return false;
  1429. } // isSupplySourceSafe
  1430. //-------------------------------------------------------------------------------------------------
  1431. /** Set delay between team production */
  1432. //-------------------------------------------------------------------------------------------------
  1433. void Player::setTeamDelaySeconds(Int delay )
  1434. {
  1435. // ai action
  1436. if( m_ai )
  1437. m_ai->setTeamDelaySeconds( delay );
  1438. } // guardSupplyCenter
  1439. //-------------------------------------------------------------------------------------------------
  1440. /** Guard supply center */
  1441. //-------------------------------------------------------------------------------------------------
  1442. void Player::guardSupplyCenter( Team *team, Int minSupplies )
  1443. {
  1444. // ai action
  1445. if( m_ai )
  1446. m_ai->guardSupplyCenter( team, minSupplies );
  1447. } // guardSupplyCenter
  1448. //-------------------------------------------------------------------------------------------------
  1449. /** A team is about to be destroyed */
  1450. //-------------------------------------------------------------------------------------------------
  1451. void Player::preTeamDestroy( const Team *team )
  1452. {
  1453. // ai notification callback
  1454. if( m_ai )
  1455. m_ai->aiPreTeamDestroy( team );
  1456. } // preTeamDestroy
  1457. //-------------------------------------------------------------------------------------------------
  1458. /// a structuer was just created, but is under construction
  1459. //-------------------------------------------------------------------------------------------------
  1460. void Player::onStructureCreated( Object *builder, Object *structure )
  1461. {
  1462. } // end onStructureCreated
  1463. //-------------------------------------------------------------------------------------------------
  1464. /// a structure that was under construction has become completed
  1465. //-------------------------------------------------------------------------------------------------
  1466. void Player::onStructureConstructionComplete( Object *builder, Object *structure, Bool isRebuild )
  1467. {
  1468. // When a a structure is completed, it becomes "real" as far as scripting is
  1469. // concerned. jba.
  1470. TheScriptEngine->notifyOfObjectCreationOrDestruction();
  1471. // Update the pathfind footprint. Sometimes when rubble has to be removed
  1472. // to build, the initial footprint while building is goofy. jba.
  1473. TheAI->pathfinder()->removeObjectFromPathfindMap(structure);
  1474. TheAI->pathfinder()->addObjectToPathfindMap(structure);
  1475. // increment our scorekeeper
  1476. if (isRebuild == FALSE) {
  1477. m_scoreKeeper.addObjectBuilt(structure);
  1478. m_scoreKeeper.addMoneySpent(structure->getTemplate()->calcCostToBuild(this));
  1479. }
  1480. structure->friend_adjustPowerForPlayer(TRUE);
  1481. // ai notification callback
  1482. if( m_ai )
  1483. m_ai->onStructureProduced( builder, structure );
  1484. // the GUI needs to re-evaluate the information being displayed to the user now
  1485. if( TheControlBar )
  1486. TheControlBar->markUIDirty();
  1487. // This object may require us to play some EVA sounds.
  1488. Player *localPlayer = ThePlayerList->getLocalPlayer();
  1489. if( structure->hasSpecialPower( SPECIAL_PARTICLE_UPLINK_CANNON ) ||
  1490. structure->hasSpecialPower( SUPW_SPECIAL_PARTICLE_UPLINK_CANNON ) ||
  1491. structure->hasSpecialPower( LAZR_SPECIAL_PARTICLE_UPLINK_CANNON ) )
  1492. {
  1493. if ( localPlayer == structure->getControllingPlayer() )
  1494. {
  1495. TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_ParticleCannon);
  1496. }
  1497. else if ( localPlayer->getRelationship(structure->getTeam()) != ENEMIES )
  1498. {
  1499. // Note: treating NEUTRAL as ally. Is this correct?
  1500. TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_ParticleCannon);
  1501. }
  1502. else
  1503. {
  1504. TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_ParticleCannon);
  1505. }
  1506. }
  1507. if( structure->hasSpecialPower( SPECIAL_NEUTRON_MISSILE ) ||
  1508. structure->hasSpecialPower( NUKE_SPECIAL_NEUTRON_MISSILE ) ||
  1509. structure->hasSpecialPower( SUPW_SPECIAL_NEUTRON_MISSILE ) )
  1510. {
  1511. if ( localPlayer == structure->getControllingPlayer() )
  1512. {
  1513. TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_Nuke);
  1514. }
  1515. else if ( localPlayer->getRelationship(structure->getTeam()) != ENEMIES )
  1516. {
  1517. // Note: treating NEUTRAL as ally. Is this correct?
  1518. TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_Nuke);
  1519. }
  1520. else
  1521. {
  1522. TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_Nuke);
  1523. }
  1524. }
  1525. if (structure->hasSpecialPower(SPECIAL_SCUD_STORM))
  1526. {
  1527. if ( localPlayer == structure->getControllingPlayer() )
  1528. {
  1529. TheEva->setShouldPlay(EVA_SuperweaponDetected_Own_ScudStorm);
  1530. }
  1531. else if ( localPlayer->getRelationship(structure->getTeam()) != ENEMIES )
  1532. {
  1533. // Note: treating NEUTRAL as ally. Is this correct?
  1534. TheEva->setShouldPlay(EVA_SuperweaponDetected_Ally_ScudStorm);
  1535. }
  1536. else
  1537. {
  1538. TheEva->setShouldPlay(EVA_SuperweaponDetected_Enemy_ScudStorm);
  1539. }
  1540. }
  1541. } // end onStructureConstructionComplete
  1542. //=============================================================================
  1543. void Player::onStructureUndone(Object *structure)
  1544. {
  1545. m_scoreKeeper.removeObjectBuilt(structure);
  1546. } // end onStructureUndone
  1547. //=============================================================================
  1548. void Player::addTeamToList(TeamPrototype* team)
  1549. {
  1550. for( PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin();
  1551. it != m_playerTeamPrototypes.end(); ++it )
  1552. {
  1553. if (team == *it)
  1554. return; // already present
  1555. }
  1556. m_playerTeamPrototypes.push_back(team);
  1557. }
  1558. //=============================================================================
  1559. void Player::removeTeamFromList(TeamPrototype* team)
  1560. {
  1561. for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin();
  1562. it != m_playerTeamPrototypes.end(); ++it)
  1563. {
  1564. if (team == *it)
  1565. {
  1566. m_playerTeamPrototypes.erase(it);
  1567. return;
  1568. }
  1569. }
  1570. }
  1571. //=============================================================================
  1572. void Player::healAllObjects()
  1573. {
  1574. for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin();
  1575. it != m_playerTeamPrototypes.end(); ++it)
  1576. {
  1577. (*it)->healAllObjects();
  1578. }
  1579. }
  1580. //=============================================================================
  1581. void Player::iterateObjects( ObjectIterateFunc func, void *userData ) const
  1582. {
  1583. for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin();
  1584. it != m_playerTeamPrototypes.end(); ++it)
  1585. {
  1586. (*it)->iterateObjects( func, userData );
  1587. }
  1588. }
  1589. //=============================================================================
  1590. void Player::countObjectsByThingTemplate(Int numTmplates, const ThingTemplate* const * things, Bool ignoreDead, Int *counts, Bool ignoreUnderConstruction ) const
  1591. {
  1592. Int i;
  1593. for (i = 0; i < numTmplates; ++i)
  1594. counts[i] = 0;
  1595. for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin();
  1596. it != m_playerTeamPrototypes.end();
  1597. ++it)
  1598. {
  1599. (*it)->countObjectsByThingTemplate(numTmplates, things, ignoreDead, counts, ignoreUnderConstruction);
  1600. }
  1601. }
  1602. //=============================================================================
  1603. Int Player::countBuildings(void)
  1604. {
  1605. int retVal = 0;
  1606. for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin();
  1607. it != m_playerTeamPrototypes.end(); ++it)
  1608. {
  1609. retVal += (*it)->countBuildings();
  1610. }
  1611. return retVal;
  1612. }
  1613. //=============================================================================
  1614. Int Player::countObjects(KindOfMaskType setMask, KindOfMaskType clearMask)
  1615. {
  1616. int retVal = 0;
  1617. for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin();
  1618. it != m_playerTeamPrototypes.end(); ++it)
  1619. {
  1620. retVal += (*it)->countObjects(setMask, clearMask);
  1621. }
  1622. return retVal;
  1623. }
  1624. //=============================================================================
  1625. Object *Player::findClosestByKindOf( Object *queryObject, KindOfMaskType setMask, KindOfMaskType clearMask )
  1626. {
  1627. if( queryObject == NULL )
  1628. return NULL;
  1629. ClosestKindOfData data;
  1630. data.m_setKindOf = setMask;
  1631. data.m_clearKindOf = clearMask;
  1632. data.m_source = queryObject;
  1633. // Magic presto! data ends up with the answer in it!
  1634. iterateObjects( findClosestKindOf, &data );
  1635. return data.m_closest;
  1636. }
  1637. //=============================================================================
  1638. Bool Player::hasAnyBuildings(void) const
  1639. {
  1640. for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin();
  1641. it != m_playerTeamPrototypes.end(); ++it)
  1642. {
  1643. if ((*it)->hasAnyBuildings()) {
  1644. return true;
  1645. }
  1646. }
  1647. return false;
  1648. }
  1649. //=============================================================================
  1650. Bool Player::hasAnyBuildings(KindOfMaskType kindOf) const
  1651. {
  1652. for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin();
  1653. it != m_playerTeamPrototypes.end(); ++it)
  1654. {
  1655. if ((*it)->hasAnyBuildings(kindOf)) {
  1656. return true;
  1657. }
  1658. }
  1659. return false;
  1660. }
  1661. //=============================================================================
  1662. Bool Player::hasAnyUnits(void) const
  1663. {
  1664. for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin();
  1665. it != m_playerTeamPrototypes.end(); ++it)
  1666. {
  1667. if ((*it)->hasAnyUnits()) {
  1668. return true;
  1669. }
  1670. }
  1671. return false;
  1672. }
  1673. //=============================================================================
  1674. Bool Player::hasAnyObjects(void) const
  1675. {
  1676. for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin();
  1677. it != m_playerTeamPrototypes.end(); ++it)
  1678. {
  1679. if ((*it)->hasAnyObjects()) {
  1680. return true;
  1681. }
  1682. }
  1683. return false;
  1684. }
  1685. //=============================================================================
  1686. Bool Player::hasAnyBuildFacility(void) const
  1687. {
  1688. for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin();
  1689. it != m_playerTeamPrototypes.end(); ++it)
  1690. {
  1691. if ((*it)->hasAnyBuildFacility())
  1692. return true;
  1693. }
  1694. return false;
  1695. }
  1696. //=============================================================================
  1697. void Player::updateTeamStates(void)
  1698. {
  1699. for (PlayerTeamList::const_iterator it = m_playerTeamPrototypes.begin();
  1700. it != m_playerTeamPrototypes.end(); ++it)
  1701. {
  1702. (*it)->updateState();
  1703. }
  1704. }
  1705. //=============================================================================
  1706. Bool Player::isLocalPlayer() const
  1707. {
  1708. return this == ThePlayerList->getLocalPlayer();
  1709. }
  1710. //=============================================================================
  1711. void Player::setListInScoreScreen(Bool listInScoreScreen)
  1712. {
  1713. m_listInScoreScreen = listInScoreScreen;
  1714. }
  1715. //=============================================================================
  1716. Bool Player::getListInScoreScreen()
  1717. {
  1718. return m_listInScoreScreen;
  1719. }
  1720. //=============================================================================
  1721. UnsignedInt Player::getSupplyBoxValue()
  1722. {
  1723. /// @todo This would be the hookup for difficulty level modifiers and special economy buildings
  1724. return TheGlobalData->m_baseValuePerSupplyBox;
  1725. }
  1726. //=============================================================================
  1727. Real Player::getProductionCostChangePercent( AsciiString buildTemplateName ) const
  1728. {
  1729. ProductionChangeMap::const_iterator it = m_productionCostChanges.find(NAMEKEY(buildTemplateName));
  1730. if (it != m_productionCostChanges.end())
  1731. {
  1732. return (*it).second;
  1733. }
  1734. return 0.0f;
  1735. }
  1736. //=============================================================================
  1737. Real Player::getProductionTimeChangePercent( AsciiString buildTemplateName ) const
  1738. {
  1739. ProductionChangeMap::const_iterator it = m_productionTimeChanges.find(NAMEKEY(buildTemplateName));
  1740. if (it != m_productionTimeChanges.end())
  1741. {
  1742. return (*it).second;
  1743. }
  1744. return 0.0f;
  1745. }
  1746. //=============================================================================
  1747. VeterancyLevel Player::getProductionVeterancyLevel( AsciiString buildTemplateName ) const
  1748. {
  1749. NameKeyType templateNameKey = NAMEKEY(buildTemplateName);
  1750. ProductionVeterancyMap::const_iterator it = m_productionVeterancyLevels.find(templateNameKey);
  1751. if (it != m_productionVeterancyLevels.end())
  1752. {
  1753. return (*it).second;
  1754. }
  1755. return LEVEL_FIRST;
  1756. }
  1757. //=============================================================================
  1758. void Player::friend_setSkillset(Int skillSet)
  1759. {
  1760. if (m_ai) {
  1761. m_ai->selectSkillset(skillSet);
  1762. }
  1763. }
  1764. //=============================================================================
  1765. void Player::setUnitsShouldHunt(Bool unitsShouldHunt, CommandSourceType source)
  1766. {
  1767. m_unitsShouldHunt = unitsShouldHunt;
  1768. Coord3D pos;
  1769. ThePartitionManager->getMostValuableLocation(getPlayerIndex(), ALLOW_ENEMIES, VOT_CashValue, &pos);
  1770. for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin();
  1771. it != m_playerTeamPrototypes.end(); ++it) {
  1772. for (DLINK_ITERATOR<Team> iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) {
  1773. Team *team = iter.cur();
  1774. if (!team) {
  1775. continue;
  1776. }
  1777. for (DLINK_ITERATOR<Object> iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) {
  1778. Object *obj = iterObj.cur();
  1779. if (!obj) {
  1780. continue;
  1781. }
  1782. KindOfMaskType disqualifyingKindofs;
  1783. disqualifyingKindofs.set(KINDOF_DOZER);
  1784. disqualifyingKindofs.set(KINDOF_HARVESTER);
  1785. disqualifyingKindofs.set(KINDOF_IGNORES_SELECT_ALL);
  1786. if (obj->isAnyKindOf( disqualifyingKindofs )) {
  1787. continue; // Harvesters, dozers etc.
  1788. }
  1789. obj->leaveGroup();
  1790. AIUpdateInterface *ai = obj->getAIUpdateInterface();
  1791. if (ai) {
  1792. if (unitsShouldHunt) {
  1793. ai->aiHunt(source);
  1794. } else {
  1795. ai->aiIdle(source);
  1796. }
  1797. }
  1798. }
  1799. }
  1800. }
  1801. }
  1802. //=============================================================================
  1803. void Player::killPlayer(void)
  1804. {
  1805. for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin(); it != m_playerTeamPrototypes.end(); ++it) {
  1806. for (DLINK_ITERATOR<Team> iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) {
  1807. Team *team = iter.cur();
  1808. if (!team) {
  1809. continue;
  1810. }
  1811. team->evacuateTeam(); // force containers on team to dump contents
  1812. }
  1813. }
  1814. m_isPlayerDead = TRUE; // this is so OCLs don't ever again spawn useful units for us.
  1815. for (it = m_playerTeamPrototypes.begin(); it != m_playerTeamPrototypes.end(); ++it) {
  1816. for (DLINK_ITERATOR<Team> iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) {
  1817. Team *team = iter.cur();
  1818. if (!team) {
  1819. continue;
  1820. }
  1821. team->killTeam();
  1822. }
  1823. }
  1824. if (TheGameLogic->isInSinglePlayerGame()) {
  1825. if (getPlayerType()==PLAYER_COMPUTER) {
  1826. // This is an AI player in a solo mission - leave him alive so he can be used later. jba.
  1827. m_isPlayerDead = FALSE; // this is so we can later spawn useful units for us.
  1828. return;
  1829. }
  1830. }
  1831. if (isLocalPlayer() && !TheGameLogic->isInShellGame())
  1832. {
  1833. becomingLocalPlayer(TRUE); // recalc disguises, etc
  1834. if (TheControlBar )
  1835. {
  1836. if (isPlayerActive())
  1837. {
  1838. TheControlBar->setControlBarSchemeByPlayer(this);
  1839. }
  1840. else
  1841. {
  1842. TheControlBar->setControlBarSchemeByPlayerTemplate(ThePlayerTemplateStore->findPlayerTemplate(NAMEKEY("FactionObserver")));
  1843. }
  1844. }
  1845. }
  1846. m_money.withdraw(m_money.countMoney()); // force $$$ to 0 on death
  1847. }
  1848. //=============================================================================
  1849. void Player::setObjectsEnabled(AsciiString templateTypeToAffect, Bool enable)
  1850. {
  1851. for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin();
  1852. it != m_playerTeamPrototypes.end(); ++it) {
  1853. for (DLINK_ITERATOR<Team> iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) {
  1854. Team *team = iter.cur();
  1855. if (!team) {
  1856. continue;
  1857. }
  1858. for (DLINK_ITERATOR<Object> iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) {
  1859. Object *obj = iterObj.cur();
  1860. if (!obj) {
  1861. continue;
  1862. }
  1863. if (obj->getTemplate()->getName().compare(templateTypeToAffect) == 0)
  1864. {
  1865. obj->setScriptStatus( OBJECT_STATUS_SCRIPT_DISABLED, !enable );
  1866. }
  1867. }
  1868. }
  1869. }
  1870. }
  1871. //=============================================================================
  1872. void Player::transferAssetsFromThat(Player *that)
  1873. {
  1874. Team *defaultTeam = getDefaultTeam();
  1875. if (!defaultTeam) {
  1876. return;
  1877. }
  1878. std::list<Object *> objsToTransfer;
  1879. // let's not transfer beacons
  1880. const ThingTemplate *beaconTemplate = TheThingFactory->findTemplate( that->getPlayerTemplate()->getBeaconTemplate() );
  1881. // transfer all his units.
  1882. for (PlayerTeamList::iterator it = that->m_playerTeamPrototypes.begin();
  1883. it != that->m_playerTeamPrototypes.end(); ++it)
  1884. {
  1885. for (DLINK_ITERATOR<Team> iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance())
  1886. {
  1887. Team *team = iter.cur();
  1888. if (!team)
  1889. {
  1890. continue;
  1891. }
  1892. for (DLINK_ITERATOR<Object> iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance())
  1893. {
  1894. Object *obj = iterObj.cur();
  1895. if (!obj || obj->getTemplate()->isEquivalentTo(beaconTemplate)) // don't transfer NULL objs or beacons
  1896. {
  1897. continue;
  1898. }
  1899. objsToTransfer.push_back(obj);
  1900. }
  1901. }
  1902. }
  1903. for (std::list<Object *>::iterator itObjs = objsToTransfer.begin(); itObjs != objsToTransfer.end(); ++itObjs) {
  1904. (*itObjs)->setTeam(defaultTeam);
  1905. }
  1906. // transfer all his money
  1907. UnsignedInt allMoney = that->getMoney()->countMoney();
  1908. that->getMoney()->withdraw(allMoney);
  1909. getMoney()->deposit(allMoney);
  1910. }
  1911. //=============================================================================
  1912. void Player::garrisonAllUnits(CommandSourceType source)
  1913. {
  1914. PartitionFilterAcceptByKindOf f1(MAKE_KINDOF_MASK(KINDOF_STRUCTURE), KINDOFMASK_NONE);
  1915. PartitionFilter *filters[] = { &f1, NULL };
  1916. Coord3D pos = {50.0, 50.0, 50.0};
  1917. /// @todo srj -- we should really use iterateAllObjects() here instead, but I have no time to
  1918. // test such a change... make someday
  1919. ObjectIterator *iterBuilding = ThePartitionManager->iterateObjectsInRange(&pos, 1e9f, FROM_CENTER_3D, filters, ITER_SORTED_NEAR_TO_FAR);
  1920. MemoryPoolObjectHolder hold(iterBuilding);
  1921. for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin();
  1922. it != m_playerTeamPrototypes.end(); ++it) {
  1923. for (DLINK_ITERATOR<Team> iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) {
  1924. Team *team = iter.cur();
  1925. if (!team) {
  1926. continue;
  1927. }
  1928. for (DLINK_ITERATOR<Object> iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) {
  1929. Object *obj = iterObj.cur();
  1930. if (!obj) {
  1931. continue;
  1932. }
  1933. AIUpdateInterface *ai = obj->getAIUpdateInterface();
  1934. if (!ai) {
  1935. continue;
  1936. }
  1937. for (Object *theBuilding = iterBuilding->first(); theBuilding; theBuilding = iterBuilding->next())
  1938. {
  1939. ContainModuleInterface *contain = theBuilding->getContain();
  1940. if (contain)
  1941. {
  1942. PlayerMaskType player = contain->getPlayerWhoEntered();
  1943. if (!((player == 0) || (player == obj->getControllingPlayer()->getPlayerMask()))) {
  1944. continue;
  1945. }
  1946. }
  1947. if( !TheActionManager->canEnterObject( obj, theBuilding, source, CHECK_CAPACITY ) )
  1948. {
  1949. continue;
  1950. }
  1951. ai->aiEnter(theBuilding, source);
  1952. }
  1953. }
  1954. }
  1955. }
  1956. }
  1957. //=============================================================================
  1958. void Player::ungarrisonAllUnits(CommandSourceType source)
  1959. {
  1960. for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin();
  1961. it != m_playerTeamPrototypes.end(); ++it) {
  1962. for (DLINK_ITERATOR<Team> iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance()) {
  1963. Team *team = iter.cur();
  1964. if (!team) {
  1965. continue;
  1966. }
  1967. for (DLINK_ITERATOR<Object> iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance()) {
  1968. Object *obj = iterObj.cur();
  1969. if (!obj) {
  1970. continue;
  1971. }
  1972. AIUpdateInterface *ai = obj->getAIUpdateInterface();
  1973. if (!ai) {
  1974. continue;
  1975. }
  1976. // Tell everything that has stuff in it to kick them all out. You can't tell the people to get
  1977. // out of what they are in, because they may not know, or they may be two transports deep, and their
  1978. // transport may not know where they are.
  1979. // And check for building so you don't unload transports in the ungarrison command
  1980. if( obj->isKindOf( KINDOF_STRUCTURE ) )
  1981. ai->aiEvacuate( FALSE, source);
  1982. }
  1983. }
  1984. }
  1985. }
  1986. //=============================================================================
  1987. void Player::setUnitsShouldIdleOrResume(Bool idle)
  1988. {
  1989. for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin();
  1990. it != m_playerTeamPrototypes.end(); ++it)
  1991. {
  1992. for (DLINK_ITERATOR<Team> iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance())
  1993. {
  1994. Team *team = iter.cur();
  1995. if (!team)
  1996. continue;
  1997. for (DLINK_ITERATOR<Object> iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance())
  1998. {
  1999. Object *obj = iterObj.cur();
  2000. if (!obj)
  2001. continue;
  2002. if (obj->isKindOf(KINDOF_STRUCTURE))
  2003. continue;
  2004. AIUpdateInterface *ai = obj->getAIUpdateInterface();
  2005. if (!ai)
  2006. continue;
  2007. if (idle)
  2008. {
  2009. // force it to move to its position to make it stop.
  2010. ai->aiMoveToPosition(obj->getPosition(), CMD_FROM_SCRIPT);
  2011. }
  2012. else
  2013. {
  2014. // Here is the special bit for this exit style, force wanting on SupplyTruck types
  2015. if (ai->isIdle())
  2016. {
  2017. SupplyTruckAIInterface* supplyTruckAI = ai->getSupplyTruckAIInterface();
  2018. if( supplyTruckAI )
  2019. supplyTruckAI->setForceWantingState(true);
  2020. }
  2021. }
  2022. }
  2023. }
  2024. }
  2025. }
  2026. //-------------------------------------------------------------------------------
  2027. void sellBuildings( Object *obj, void *userData )
  2028. {
  2029. if( obj->isFactionStructure() || obj->isKindOf( KINDOF_COMMANDCENTER ) || obj->isKindOf( KINDOF_FS_POWER ) )
  2030. {
  2031. TheBuildAssistant->sellObject( obj );
  2032. }
  2033. }
  2034. //=============================================================================
  2035. void Player::sellEverythingUnderTheSun()
  2036. {
  2037. iterateObjects( sellBuildings, NULL );
  2038. }
  2039. //=============================================================================
  2040. Bool Player::allowedToBuild(const ThingTemplate *tmplate) const
  2041. {
  2042. if (!m_canBuildBase && tmplate->isKindOf(KINDOF_STRUCTURE)) {
  2043. return false;
  2044. }
  2045. if (!m_canBuildUnits && !tmplate->isKindOf(KINDOF_STRUCTURE)) {
  2046. return false;
  2047. }
  2048. return true;
  2049. }
  2050. //=============================================================================
  2051. void Player::buildSpecificTeam( TeamPrototype *teamProto)
  2052. {
  2053. if (m_ai)
  2054. {
  2055. // Do a priority build.
  2056. m_ai->buildSpecificAITeam(teamProto, true);
  2057. }
  2058. }
  2059. //=============================================================================
  2060. void Player::buildBaseDefense(Bool flank)
  2061. {
  2062. if (m_ai)
  2063. {
  2064. // Do a priority build.
  2065. m_ai->buildAIBaseDefense(flank);
  2066. }
  2067. }
  2068. //=============================================================================
  2069. void Player::buildBaseDefenseStructure(const AsciiString &thingName, Bool flank)
  2070. {
  2071. if (m_ai)
  2072. {
  2073. // Do a priority build.
  2074. m_ai->buildAIBaseDefenseStructure(thingName, flank);
  2075. }
  2076. }
  2077. //=============================================================================
  2078. void Player::buildSpecificBuilding(const AsciiString &thingName)
  2079. {
  2080. if (m_ai)
  2081. {
  2082. // Do a priority build.
  2083. m_ai->buildSpecificAIBuilding(thingName);
  2084. }
  2085. }
  2086. //=============================================================================
  2087. void Player::buildBySupplies(Int minimumCash, const AsciiString &thingName)
  2088. {
  2089. if (m_ai)
  2090. {
  2091. m_ai->buildBySupplies(minimumCash, thingName);
  2092. }
  2093. }
  2094. //=============================================================================
  2095. void Player::buildSpecificBuildingNearestTeam( const AsciiString &thingName, const Team *team )
  2096. {
  2097. if( m_ai )
  2098. {
  2099. m_ai->buildSpecificBuildingNearestTeam( thingName, team );
  2100. }
  2101. }
  2102. //=============================================================================
  2103. void Player::buildUpgrade( const AsciiString &upgrade)
  2104. {
  2105. if (m_ai)
  2106. {
  2107. m_ai->buildUpgrade(upgrade);
  2108. }
  2109. }
  2110. //=============================================================================
  2111. void Player::recruitSpecificTeam( TeamPrototype *teamProto, Real recruitRadius)
  2112. {
  2113. if (m_ai)
  2114. {
  2115. // Do a priority build.
  2116. m_ai->recruitSpecificAITeam(teamProto, recruitRadius);
  2117. }
  2118. }
  2119. //=============================================================================
  2120. // Calculates the closest construction zone location based on a template. Gets plassed to aiPlayer
  2121. //=============================================================================
  2122. Bool Player::calcClosestConstructionZoneLocation( const ThingTemplate *constructTemplate, Coord3D *location )
  2123. {
  2124. if( m_ai )
  2125. {
  2126. return m_ai->calcClosestConstructionZoneLocation( constructTemplate, location );
  2127. }
  2128. return FALSE;
  2129. }
  2130. //=============================================================================
  2131. void Player::doBountyForKill(const Object* killer, const Object* victim)
  2132. {
  2133. if (!killer || !victim)
  2134. return;
  2135. // srj sez: per dustin, no experience (et al) for killing things under construction.
  2136. if (victim->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION))
  2137. return;
  2138. Int costToBuild = victim->getTemplate()->calcCostToBuild(victim->getControllingPlayer());
  2139. Int bounty = REAL_TO_INT_CEIL(costToBuild * m_cashBountyPercent);
  2140. if( bounty )
  2141. {
  2142. getMoney()->deposit( bounty );
  2143. m_scoreKeeper.addMoneyEarned( bounty );
  2144. //Display cash income floating over the recipient.
  2145. UnicodeString moneyString;
  2146. moneyString.format( TheGameText->fetch( "GUI:AddCash" ), bounty );
  2147. Coord3D pos;
  2148. pos.zero();
  2149. pos.add( killer->getPosition() );
  2150. pos.z += 10.0f; //add a little z to make it show up above the unit.
  2151. TheInGameUI->addFloatingText( moneyString, &pos, GameMakeColor( 255, 255, 0, 255 ) );
  2152. }
  2153. }
  2154. //=============================================================================
  2155. Bool Player::hasPrereqsForScience(ScienceType t) const
  2156. {
  2157. return TheScienceStore->playerHasPrereqsForScience(this, t);
  2158. }
  2159. //=============================================================================
  2160. /// returns TRUE if the player gained/lost levels as a result.
  2161. Bool Player::addSkillPoints(Int delta)
  2162. {
  2163. delta = REAL_TO_INT_CEIL(m_skillPointsModifier * INT_TO_REAL(delta));
  2164. if( delta == 0 )
  2165. return false;
  2166. Int levelCap = min( TheGameLogic->getRankLevelLimit(), TheRankInfoStore->getRankLevelCount() );
  2167. Int pointCap = TheRankInfoStore->getRankInfo(levelCap)->m_skillPointsNeeded; // Cap at lowest point of cap level, not highest.
  2168. Bool levelGained = FALSE;
  2169. m_skillPoints = min( pointCap, (m_skillPoints + delta) );
  2170. while( m_skillPoints >= m_levelUp )
  2171. {
  2172. // LevelUp gets increased as a side effect of setRankLevel, and this won't infinitely loop,
  2173. // because when there are no more levels to be gained, m_levelUp is set to INT_MAX.
  2174. setRankLevel( m_rankLevel + 1 );
  2175. levelGained = TRUE;
  2176. }
  2177. return levelGained;
  2178. }
  2179. //=============================================================================
  2180. /// returns TRUE if the player gained/lost levels as a result.
  2181. Bool Player::addSkillPointsForKill(const Object* killer, const Object* victim)
  2182. {
  2183. if (!killer || !victim)
  2184. return false;
  2185. // srj sez: per dustin, no experience (et al) for killing things under construction.
  2186. if (victim->testStatus(OBJECT_STATUS_UNDER_CONSTRUCTION))
  2187. return false;
  2188. Int victimLevel = victim->getVeterancyLevel();
  2189. Int skillValue = victim->getTemplate()->getSkillPointValue(victimLevel);
  2190. return addSkillPoints(skillValue);
  2191. }
  2192. //=============================================================================
  2193. void Player::resetSciences()
  2194. {
  2195. m_sciences.clear();
  2196. if (getPlayerTemplate())
  2197. m_sciences = getPlayerTemplate()->getIntrinsicSciences();
  2198. for (Int i = 1; i <= m_rankLevel; ++i)
  2199. {
  2200. const RankInfo* rank = TheRankInfoStore->getRankInfo(i);
  2201. if (rank)
  2202. {
  2203. for (ScienceVec::const_iterator it = rank->m_sciencesGranted.begin(); it != rank->m_sciencesGranted.end(); ++it)
  2204. {
  2205. addScience(*it);
  2206. }
  2207. }
  2208. }
  2209. for (ScienceVec::const_iterator it = m_sciences.begin(); it != m_sciences.end(); ++it)
  2210. TheScriptEngine->notifyOfAcquiredScience(getPlayerIndex(), *it);
  2211. }
  2212. //=============================================================================
  2213. /// returns TRUE if sciences were gained/lost.
  2214. Bool Player::addScience(ScienceType science)
  2215. {
  2216. if (hasScience(science))
  2217. return false;
  2218. //DEBUG_LOG(("Adding Science %s\n",TheScienceStore->getInternalNameForScience(science).str()));
  2219. m_sciences.push_back(science);
  2220. // 'wake up' any special powers controlled by, well, stuff
  2221. for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin();
  2222. it != m_playerTeamPrototypes.end(); ++it)
  2223. {
  2224. for (DLINK_ITERATOR<Team> iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance())
  2225. {
  2226. Team *team = iter.cur();
  2227. if (!team)
  2228. continue;
  2229. for (DLINK_ITERATOR<Object> iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance())
  2230. {
  2231. Object *obj = iterObj.cur();
  2232. if (!obj)
  2233. continue;
  2234. for (BehaviorModule** m = obj->getBehaviorModules(); *m; ++m)
  2235. {
  2236. SpecialPowerModuleInterface* sp = (*m)->getSpecialPower();
  2237. if (!sp)
  2238. continue;
  2239. if (sp->getRequiredScience() == science)
  2240. {
  2241. // Turn on the power, and set it to be instantly ready, because that is cool.
  2242. sp->onSpecialPowerCreation();
  2243. sp->setReadyFrame( TheGameLogic->getFrame() );
  2244. }
  2245. }
  2246. }
  2247. }
  2248. TheControlBar->markUIDirty();// Refresh the UI to show new cameos, etc
  2249. }
  2250. // notify the script engine
  2251. TheScriptEngine->notifyOfAcquiredScience(getPlayerIndex(), science);
  2252. return true;
  2253. }
  2254. //=============================================================================
  2255. void Player::addSciencePurchasePoints(Int delta)
  2256. {
  2257. //DEBUG_LOG(("Adding SciencePurchasePoints %d -> %d\n",m_sciencePurchasePoints,m_sciencePurchasePoints+delta));
  2258. Int oldSPP = m_sciencePurchasePoints;
  2259. m_sciencePurchasePoints += delta;
  2260. if (m_sciencePurchasePoints < 0)
  2261. m_sciencePurchasePoints = 0;
  2262. if (oldSPP != m_sciencePurchasePoints && TheControlBar != NULL)
  2263. TheControlBar->onPlayerSciencePurchasePointsChanged(this);
  2264. }
  2265. //=============================================================================
  2266. Bool Player::attemptToPurchaseScience(ScienceType science)
  2267. {
  2268. if (!isCapableOfPurchasingScience(science))
  2269. {
  2270. DEBUG_CRASH(("isCapableOfPurchasingScience: need other prereqs/points to purchase, request is ignored!\n"));
  2271. return false;
  2272. }
  2273. Int cost = TheScienceStore->getSciencePurchaseCost(science);
  2274. addSciencePurchasePoints(-cost);
  2275. addScience(science);
  2276. getAcademyStats()->recordGeneralsPointsSpent( cost );
  2277. if( ThePlayerList->getLocalPlayer() == this )
  2278. {
  2279. TheControlBar->markUIDirty();
  2280. }
  2281. return true;
  2282. }
  2283. //=============================================================================
  2284. Bool Player::grantScience(ScienceType science)
  2285. {
  2286. if (!TheScienceStore->isScienceGrantable(science))
  2287. {
  2288. DEBUG_CRASH(("Cannot grant science %s, since it is marked as nonGrantable.\n",TheScienceStore->getInternalNameForScience(science).str()));
  2289. return false; // it's not grantable, so tough, can't have it, even via this method.
  2290. }
  2291. return addScience(science);
  2292. }
  2293. //=============================================================================
  2294. Bool Player::isCapableOfPurchasingScience(ScienceType science) const
  2295. {
  2296. if (science == SCIENCE_INVALID)
  2297. {
  2298. return false;
  2299. }
  2300. if (hasScience(science))
  2301. {
  2302. return false;
  2303. }
  2304. if( isScienceDisabled( science ) || isScienceHidden( science ) )
  2305. {
  2306. return false;
  2307. }
  2308. if (!hasPrereqsForScience(science))
  2309. {
  2310. return false;
  2311. }
  2312. Int cost = TheScienceStore->getSciencePurchaseCost(science);
  2313. // purchase cost of zero means "not purchasable!"
  2314. if (cost == 0 || cost > getSciencePurchasePoints())
  2315. {
  2316. return false;
  2317. }
  2318. return true;
  2319. }
  2320. //=============================================================================
  2321. void Player::resetRank()
  2322. {
  2323. m_rankLevel = 1;
  2324. m_skillPoints = 0;
  2325. const RankInfo* nextRank = TheRankInfoStore->getRankInfo(m_rankLevel+1);
  2326. m_levelUp = nextRank ? nextRank->m_skillPointsNeeded : INT_MAX;
  2327. m_levelDown = 0;
  2328. m_sciences.clear();
  2329. m_sciencePurchasePoints = getPlayerTemplate() ? getPlayerTemplate()->getIntrinsicSciencePurchasePoints() : 0;
  2330. const RankInfo* curRank = TheRankInfoStore->getRankInfo(m_rankLevel);
  2331. m_sciencePurchasePoints += curRank ? curRank->m_sciencePurchasePointsGranted : 0;
  2332. m_generalName = TheGameText? TheGameText->fetch("SCIENCE:GeneralName"):UnicodeString::TheEmptyString;
  2333. resetSciences();
  2334. }
  2335. //=============================================================================
  2336. /// returns TRUE if rank level really changed.
  2337. Bool Player::setRankLevel(Int newLevel)
  2338. {
  2339. if (newLevel < 1)
  2340. newLevel = 1;
  2341. else if (newLevel > TheRankInfoStore->getRankLevelCount())
  2342. newLevel = TheRankInfoStore->getRankLevelCount();
  2343. if (newLevel > TheGameLogic->getRankLevelLimit())
  2344. newLevel = TheGameLogic->getRankLevelLimit();
  2345. if (newLevel == m_rankLevel)
  2346. return false;
  2347. //DEBUG_LOG(("Set Rank Level %d -> %d\n",m_rankLevel,newLevel));
  2348. Int oldSPP = m_sciencePurchasePoints;
  2349. if (newLevel < m_rankLevel)
  2350. {
  2351. // when downgrading in rank, you lose everything. oh well...
  2352. resetRank();
  2353. }
  2354. for (Int i = m_rankLevel + 1; i <= newLevel; ++i)
  2355. {
  2356. const RankInfo* rank = TheRankInfoStore->getRankInfo(i);
  2357. DEBUG_ASSERTCRASH(rank, ("rank should never be null here"));
  2358. if (rank)
  2359. {
  2360. //addSciencePurchasePoints(rank->m_sciencePurchasePointsGranted);
  2361. // do this directly, so we can defer the UI notification till the end
  2362. m_sciencePurchasePoints += rank->m_sciencePurchasePointsGranted;
  2363. if (m_sciencePurchasePoints < 0)
  2364. m_sciencePurchasePoints = 0;
  2365. if (m_skillPoints < rank->m_skillPointsNeeded)
  2366. m_skillPoints = rank->m_skillPointsNeeded;
  2367. for (ScienceVec::const_iterator it = rank->m_sciencesGranted.begin(); it != rank->m_sciencesGranted.end(); ++it)
  2368. {
  2369. addScience(*it);
  2370. }
  2371. m_levelDown = rank->m_skillPointsNeeded;
  2372. }
  2373. }
  2374. const RankInfo* nextRank = TheRankInfoStore->getRankInfo(newLevel + 1);
  2375. m_levelUp = nextRank ? nextRank->m_skillPointsNeeded : INT_MAX;
  2376. m_rankLevel = newLevel;
  2377. DEBUG_ASSERTCRASH(m_skillPoints >= m_levelDown && m_skillPoints < m_levelUp, ("hmm, wrong"));
  2378. //DEBUG_LOG(("Rank %d, Skill %d, down %d, up %d\n",m_rankLevel,m_skillPoints, m_levelDown, m_levelUp));
  2379. if (TheControlBar != NULL)
  2380. {
  2381. if( m_levelUp )
  2382. {
  2383. //Play an EVA sound
  2384. if (isLocalPlayer())
  2385. TheEva->setShouldPlay( EVA_GeneralLevelUp );
  2386. }
  2387. // notify of rank-change first
  2388. TheControlBar->onPlayerRankChanged(this);
  2389. // then of SPP change, if any
  2390. if (oldSPP != m_sciencePurchasePoints)
  2391. TheControlBar->onPlayerSciencePurchasePointsChanged(this);
  2392. }
  2393. return true;
  2394. }
  2395. //=============================================================================
  2396. Bool Player::hasScience(ScienceType t) const
  2397. {
  2398. return std::find(m_sciences.begin(), m_sciences.end(), t) != m_sciences.end();
  2399. }
  2400. //=============================================================================
  2401. Bool Player::isScienceDisabled( ScienceType t ) const
  2402. {
  2403. return std::find( m_sciencesDisabled.begin(), m_sciencesDisabled.end(), t ) != m_sciencesDisabled.end();
  2404. }
  2405. //=============================================================================
  2406. Bool Player::isScienceHidden( ScienceType t ) const
  2407. {
  2408. return std::find( m_sciencesHidden.begin(), m_sciencesHidden.end(), t ) != m_sciencesHidden.end();
  2409. }
  2410. //=============================================================================
  2411. void Player::setScienceAvailability( ScienceType science, ScienceAvailabilityType type )
  2412. {
  2413. ScienceType sType;
  2414. ScienceVec::iterator it;
  2415. Bool found = false;
  2416. //First remove it from disabled sciences if it's there.
  2417. for( it = m_sciencesDisabled.begin(); it != m_sciencesDisabled.end(); ++it )
  2418. {
  2419. sType = *it;
  2420. if( sType == science )
  2421. {
  2422. m_sciencesDisabled.erase( it );
  2423. found = true;
  2424. break;
  2425. }
  2426. }
  2427. if( !found )
  2428. {
  2429. //If still not found, remove it from hidden sciences if it's there.
  2430. for( it = m_sciencesHidden.begin(); it != m_sciencesHidden.end(); ++it )
  2431. {
  2432. sType = *it;
  2433. if( sType == science )
  2434. {
  2435. m_sciencesHidden.erase( it );
  2436. found = true;
  2437. break;
  2438. }
  2439. }
  2440. }
  2441. //At this point, this science shouldn't be disabled nor hidden!
  2442. if( type == SCIENCE_DISABLED )
  2443. {
  2444. //Add science to disabled vec.
  2445. m_sciencesDisabled.push_back( science );
  2446. }
  2447. else if( type == SCIENCE_HIDDEN )
  2448. {
  2449. //Add science to hidden vec.
  2450. m_sciencesHidden.push_back( science );
  2451. }
  2452. else if( type == SCIENCE_AVAILABLE )
  2453. {
  2454. //Do nothing, because being available means that the science isn't in one of the hidden or disabled vecs.
  2455. }
  2456. }
  2457. //=============================================================================
  2458. ScienceAvailabilityType Player::getScienceAvailabilityTypeFromString( const AsciiString& name )
  2459. {
  2460. for( Int i = 0; i < SCIENCE_AVAILABILITY_COUNT; i++ )
  2461. {
  2462. if( !name.compareNoCase( ScienceAvailabilityNames[ i ] ) )
  2463. {
  2464. return (ScienceAvailabilityType)i;
  2465. }
  2466. }
  2467. return SCIENCE_AVAILABILITY_INVALID;
  2468. }
  2469. namespace
  2470. {
  2471. // ------------------------------------------------------------------------------------------------
  2472. // For countExisting
  2473. struct TypeCountData
  2474. {
  2475. UnsignedInt count;
  2476. const ThingTemplate *type;
  2477. NameKeyType linkKey;
  2478. Bool checkProductionInterface;
  2479. };
  2480. }
  2481. // ------------------------------------------------------------------------------------------------
  2482. /** Count all the units of a given type that exist or are in any production queues for a player */
  2483. // ------------------------------------------------------------------------------------------------
  2484. static void countExisting( Object *obj, void *userData )
  2485. {
  2486. // Don't care about dead objects
  2487. if ( obj->isEffectivelyDead() )
  2488. return;
  2489. TypeCountData *typeCountData = (TypeCountData *)userData;
  2490. // Compare templates
  2491. if ( typeCountData->type->isEquivalentTo( obj->getTemplate() ) ||
  2492. ( typeCountData->linkKey != NAMEKEY_INVALID && obj->getTemplate() != NULL && typeCountData->linkKey == obj->getTemplate()->getMaxSimultaneousLinkKey() ) )
  2493. {
  2494. typeCountData->count++;
  2495. }
  2496. // Also consider objects that have a production update interface
  2497. if ( typeCountData->checkProductionInterface )
  2498. {
  2499. ProductionUpdateInterface *pui = ProductionUpdate::getProductionUpdateInterfaceFromObject( obj );
  2500. if( pui )
  2501. {
  2502. // add the count of this type that are in the queue
  2503. typeCountData->count += pui->countUnitTypeInQueue( typeCountData->type );
  2504. } // end if
  2505. }
  2506. } // end countInProduction
  2507. //=============================================================================
  2508. // Make sure that building another of this unit/structure/object won't exceed MaxSimultaneousOfType()
  2509. Bool Player::canBuildMoreOfType( const ThingTemplate *whatToBuild ) const
  2510. {
  2511. // make sure we're not maxed out for this type of unit.
  2512. UnsignedInt maxSimultaneousOfType = whatToBuild->getMaxSimultaneousOfType();
  2513. if (maxSimultaneousOfType != 0)
  2514. {
  2515. TypeCountData typeCountData;
  2516. typeCountData.count = 0;
  2517. typeCountData.type = whatToBuild;
  2518. typeCountData.linkKey = whatToBuild->getMaxSimultaneousLinkKey();
  2519. // Assumption: Things with a KINDOF_STRUCTURE flag can never be built from
  2520. // a factory (ProductionUpdateInterface), because the building can't move
  2521. // out of the factory. When we do our Starcraft port and have flying Terran
  2522. // buildings, we'll have to change this ;-)
  2523. // Remember: To ASSUME makes an ASS out of U and ME.
  2524. typeCountData.checkProductionInterface = !whatToBuild->isKindOf( KINDOF_STRUCTURE );
  2525. iterateObjects( countExisting, &typeCountData );
  2526. if( typeCountData.count >= maxSimultaneousOfType )
  2527. return false;
  2528. }
  2529. return true;
  2530. }
  2531. //=============================================================================
  2532. Bool Player::canBuild(const ThingTemplate *tmplate) const
  2533. {
  2534. if (!tmplate)
  2535. return false;
  2536. if (!allowedToBuild(tmplate))
  2537. return false;
  2538. if (tmplate->getBuildable() == BSTATUS_NO)
  2539. return false;
  2540. if (tmplate->getBuildable() == BSTATUS_IGNORE_PREREQUISITES)
  2541. return true;
  2542. if (tmplate->getBuildable() == BSTATUS_ONLY_BY_AI && getPlayerType() != PLAYER_COMPUTER)
  2543. return false;
  2544. // else BSTATUS tmplate->getBuildable() == BSTATUS_YES
  2545. {
  2546. // we must satisfy all of the prereqs
  2547. Bool prereqsOK = true;
  2548. for (Int i = 0; i < tmplate->getPrereqCount(); i++)
  2549. {
  2550. const ProductionPrerequisite *pre = tmplate->getNthPrereq(i);
  2551. if (pre->isSatisfied(this) == false )
  2552. prereqsOK = false;
  2553. }
  2554. #if defined(_DEBUG) || defined(_INTERNAL)
  2555. if (ignoresPrereqs())
  2556. prereqsOK = true;
  2557. #endif
  2558. if (!prereqsOK)
  2559. return false;
  2560. }
  2561. if ( !canBuildMoreOfType( tmplate ) )
  2562. return false;
  2563. return true;
  2564. }
  2565. //=================================================================================================
  2566. Bool Player::canAffordBuild( const ThingTemplate *whatToBuild ) const
  2567. {
  2568. // make sure we have enough money to build this
  2569. const Money *money = getMoney();
  2570. if( whatToBuild->calcCostToBuild( this ) <= money->countMoney() )
  2571. {
  2572. return true;
  2573. }
  2574. return false;
  2575. }
  2576. //=================================================================================================
  2577. void Player::deleteUpgradeList( void )
  2578. {
  2579. Upgrade *next;
  2580. // delete all of the upgrades we have
  2581. while( m_upgradeList )
  2582. {
  2583. next = m_upgradeList->friend_getNext();
  2584. m_upgradeList->deleteInstance();
  2585. m_upgradeList = next;
  2586. } // end while
  2587. // This doesn't call removeUpgrade, so clear these ourselves.
  2588. m_upgradesInProgress.clear();
  2589. m_upgradesCompleted.clear();
  2590. } // end deleteUpgradeList
  2591. //=================================================================================================
  2592. /** Find an upgrade in our list of upgrades with matching name key */
  2593. //=================================================================================================
  2594. Upgrade *Player::findUpgrade( const UpgradeTemplate *upgradeTemplate )
  2595. {
  2596. Upgrade *upgrade;
  2597. for( upgrade = m_upgradeList; upgrade; upgrade = upgrade->friend_getNext() )
  2598. if( upgrade->getTemplate() == upgradeTemplate )
  2599. return upgrade;
  2600. return NULL;
  2601. } // end findUpgrade
  2602. //=================================================================================================
  2603. /** Does the player have this completed upgrade */
  2604. //=================================================================================================
  2605. Bool Player::hasUpgradeComplete( const UpgradeTemplate *upgradeTemplate )
  2606. {
  2607. UpgradeMaskType testMask = upgradeTemplate->getUpgradeMask();
  2608. return hasUpgradeComplete( testMask );
  2609. }
  2610. //=================================================================================================
  2611. /**
  2612. Does the player have this completed upgrade. This form is exposed so Objects can do quick lookups.
  2613. */
  2614. //=================================================================================================
  2615. Bool Player::hasUpgradeComplete( UpgradeMaskType testMask )
  2616. {
  2617. return m_upgradesCompleted.testForAll( testMask );
  2618. }
  2619. //=================================================================================================
  2620. /** Does the player have this upgrade In Production*/
  2621. //=================================================================================================
  2622. Bool Player::hasUpgradeInProduction( const UpgradeTemplate *upgradeTemplate )
  2623. {
  2624. UpgradeMaskType testMask = upgradeTemplate->getUpgradeMask();
  2625. return m_upgradesInProgress.testForAll( testMask );
  2626. }
  2627. //=================================================================================================
  2628. /** Give the player an upgrade or change status on an existing upgrade entry */
  2629. //=================================================================================================
  2630. Upgrade *Player::addUpgrade( const UpgradeTemplate *upgradeTemplate, UpgradeStatusType status )
  2631. {
  2632. Upgrade *u = findUpgrade( upgradeTemplate );
  2633. // if no upgrade instance found, make a new one
  2634. if( u == NULL )
  2635. {
  2636. // make new one
  2637. u = newInstance(Upgrade)( upgradeTemplate );
  2638. // tie to list
  2639. u->friend_setPrev( NULL );
  2640. u->friend_setNext( m_upgradeList );
  2641. if( m_upgradeList )
  2642. m_upgradeList->friend_setPrev( u );
  2643. m_upgradeList = u;
  2644. } // end if
  2645. // set the new status for the upgrade
  2646. u->setStatus( status );
  2647. // Update our Bitmasks
  2648. UpgradeMaskType newMask = upgradeTemplate->getUpgradeMask();
  2649. if( status == UPGRADE_STATUS_IN_PRODUCTION )
  2650. {
  2651. m_upgradesInProgress.set( newMask );
  2652. }
  2653. else if( status == UPGRADE_STATUS_COMPLETE )
  2654. {
  2655. m_upgradesInProgress.clear( newMask );
  2656. m_upgradesCompleted.set( newMask );
  2657. onUpgradeCompleted( upgradeTemplate );
  2658. }
  2659. if( ThePlayerList->getLocalPlayer() == this )
  2660. {
  2661. TheControlBar->markUIDirty();
  2662. }
  2663. return u;
  2664. } // end addUpgrade
  2665. //=================================================================================================
  2666. /**
  2667. An upgrade just finished, do things like tell all objects to recheck UpgradeModules
  2668. */
  2669. void Player::onUpgradeCompleted( const UpgradeTemplate *upgradeTemplate )
  2670. {
  2671. for (PlayerTeamList::iterator it = m_playerTeamPrototypes.begin();
  2672. it != m_playerTeamPrototypes.end(); ++it)
  2673. {
  2674. for (DLINK_ITERATOR<Team> iter = (*it)->iterate_TeamInstanceList(); !iter.done(); iter.advance())
  2675. {
  2676. Team *team = iter.cur();
  2677. if( team == NULL )
  2678. {
  2679. continue;
  2680. }
  2681. for (DLINK_ITERATOR<Object> iterObj = team->iterate_TeamMemberList(); !iterObj.done(); iterObj.advance())
  2682. {
  2683. Object *obj = iterObj.cur();
  2684. if( obj == NULL )
  2685. {
  2686. continue;
  2687. }
  2688. // Dear copy-paste monkeys, the meat of this iterate-all-player-objects loop goes twixt the MEAT comments
  2689. obj->updateUpgradeModules();
  2690. // end MEAT
  2691. }
  2692. }
  2693. }
  2694. }
  2695. //=================================================================================================
  2696. /** Remove upgrade from a player */
  2697. //=================================================================================================
  2698. void Player::removeUpgrade( const UpgradeTemplate *upgradeTemplate )
  2699. {
  2700. Upgrade *upgrade = findUpgrade( upgradeTemplate );
  2701. if( upgrade )
  2702. {
  2703. if( upgrade->friend_getNext() )
  2704. upgrade->friend_getNext()->friend_setPrev( upgrade->friend_getPrev() );
  2705. if( upgrade->friend_getPrev() )
  2706. upgrade->friend_getPrev()->friend_setNext( upgrade->friend_getNext() );
  2707. else
  2708. m_upgradeList = upgrade->friend_getNext();
  2709. // Clear this upgrade's bits from our mind
  2710. UpgradeMaskType oldMask = upgradeTemplate->getUpgradeMask();
  2711. m_upgradesInProgress.clear( oldMask );
  2712. m_upgradesCompleted.clear( oldMask );
  2713. if( upgrade->getStatus() == UPGRADE_STATUS_COMPLETE )
  2714. onUpgradeRemoved();
  2715. if( ThePlayerList->getLocalPlayer() == this )
  2716. {
  2717. TheControlBar->markUIDirty();
  2718. }
  2719. } // end if
  2720. } // end removeUpgrade
  2721. //-------------------------------------------------------------------------------------------------
  2722. Bool Player::okToPlayRadarEdgeSound( void )
  2723. {
  2724. return (
  2725. ! TheVictoryConditions->hasSinglePlayerBeenDefeated( this )
  2726. && ! m_isPlayerDead
  2727. && ! TheInGameUI->isClientQuiet()
  2728. && TheGameLogic->isInGameLogicUpdate()
  2729. && TheGameLogic->getFrame() > 0 );
  2730. }
  2731. //-------------------------------------------------------------------------------------------------
  2732. /** The parameter object has just aquired a radar */
  2733. //-------------------------------------------------------------------------------------------------
  2734. void Player::addRadar( Bool disableProof )
  2735. {
  2736. Bool hadRadar = hasRadar();
  2737. // increment count
  2738. ++m_radarCount;
  2739. if( disableProof )
  2740. ++m_disableProofRadarCount;// Disable proof is also in the normal refcount
  2741. if( !hadRadar && hasRadar() && okToPlayRadarEdgeSound() )
  2742. {
  2743. // This player just got radar, so play the "You have Radar!" sound
  2744. AudioEventRTS soundToPlay = TheAudio->getMiscAudio()->m_radarOnlineSound;
  2745. soundToPlay.setPlayerIndex(getPlayerIndex());
  2746. TheAudio->addAudioEvent(&soundToPlay);
  2747. }
  2748. } // end addRadar
  2749. //-------------------------------------------------------------------------------------------------
  2750. /** The parameter object has is taking its radar away from the player */
  2751. //-------------------------------------------------------------------------------------------------
  2752. void Player::removeRadar( Bool disableProof )
  2753. {
  2754. Bool hadRadar = hasRadar();
  2755. // decrement count
  2756. DEBUG_ASSERTCRASH( m_radarCount > 0, ("removeRadar: An Object is taking its radar away, but the player radar count says they don't have radar!\n") );
  2757. --m_radarCount;
  2758. if( disableProof )
  2759. --m_disableProofRadarCount;// Disable proof is also in the normal refcount
  2760. if( hadRadar && !hasRadar() && okToPlayRadarEdgeSound() )
  2761. {
  2762. // This player just lost radar, so play the "You lost Radar!" sound
  2763. AudioEventRTS soundToPlay = TheAudio->getMiscAudio()->m_radarOfflineSound;
  2764. soundToPlay.setPlayerIndex(getPlayerIndex());
  2765. TheAudio->addAudioEvent(&soundToPlay);
  2766. }
  2767. } // end removeRadar
  2768. //-------------------------------------------------------------------------------------------------
  2769. void Player::disableRadar()
  2770. {
  2771. Bool hadRadar = hasRadar();
  2772. m_radarDisabled = TRUE;
  2773. if( hadRadar
  2774. && !hasRadar() && okToPlayRadarEdgeSound() )
  2775. {
  2776. // This player just lost radar, so play the "You lost Radar!" sound
  2777. AudioEventRTS soundToPlay = TheAudio->getMiscAudio()->m_radarOfflineSound;
  2778. soundToPlay.setPlayerIndex(getPlayerIndex());
  2779. TheAudio->addAudioEvent(&soundToPlay);
  2780. }
  2781. }
  2782. //-------------------------------------------------------------------------------------------------
  2783. void Player::enableRadar()
  2784. {
  2785. Bool hadRadar = hasRadar();
  2786. m_radarDisabled = FALSE;
  2787. if( !hadRadar && hasRadar() && okToPlayRadarEdgeSound() )
  2788. {
  2789. // This player just got radar, so play the "You have Radar!" sound
  2790. AudioEventRTS soundToPlay = TheAudio->getMiscAudio()->m_radarOnlineSound;
  2791. soundToPlay.setPlayerIndex(getPlayerIndex());
  2792. TheAudio->addAudioEvent(&soundToPlay);
  2793. }
  2794. }
  2795. //-------------------------------------------------------------------------------------------------
  2796. //-------------------------------------------------------------------------------------------------
  2797. Bool Player::hasRadar() const
  2798. {
  2799. if( m_radarDisabled && (m_disableProofRadarCount == 0) )
  2800. return FALSE;// Nope, no matter how many you have, if I say no, you don't have it
  2801. // Otherwise, check if I actually do have it.
  2802. return m_radarCount > 0;
  2803. }
  2804. //-------------------------------------------------------------------------------------------------
  2805. //------------------------------------------------------------------------------------------------
  2806. static void doPowerDisable( Object *obj, void *userData )
  2807. {
  2808. Bool disabling = *((Bool*)userData);
  2809. if( obj && obj->isKindOf(KINDOF_POWERED) )
  2810. {
  2811. if( disabling )
  2812. obj->setDisabled( DISABLED_UNDERPOWERED ); //set disabled has a pauseAllSpecialPowers that prevents double pausing
  2813. else
  2814. obj->clearDisabled( DISABLED_UNDERPOWERED );
  2815. }
  2816. }
  2817. //-------------------------------------------------------------------------------------------------
  2818. //-------------------------------------------------------------------------------------------------
  2819. void Player::onPowerBrownOutChange( Bool brownOut )
  2820. {
  2821. // Everything that changes due to Player's power supply goes in here.
  2822. if( brownOut )
  2823. disableRadar();
  2824. else
  2825. enableRadar(); //This doesn't give radar necessarily, it just removes the restriction
  2826. iterateObjects( doPowerDisable, &brownOut );// This function is so cool.
  2827. }
  2828. //-------------------------------------------------------------------------------------------------
  2829. //-------------------------------------------------------------------------------------------------
  2830. // SEVERAL OBJECTS (LIKE MULTIPLE COMMAND CENTERS) MAY HAVE MATCHING SETS OF SPECIAL POWERS
  2831. // THIS KEEPS THEM IN SYNC SO IT LOOKS LIKE EACH SPECIAL POWER IS SHARED BETWEEN ALL
  2832. void Player::addNewSharedSpecialPowerTimer( const SpecialPowerTemplate *temp, UnsignedInt frame )
  2833. {
  2834. SpecialPowerReadyTimerType newTimer;
  2835. newTimer.m_templateID = temp->getID();
  2836. newTimer.m_readyFrame = frame;
  2837. m_specialPowerReadyTimerList.push_back( newTimer );
  2838. }
  2839. void Player::resetOrStartSpecialPowerReadyFrame( const SpecialPowerTemplate *temp )
  2840. {
  2841. UnsignedInt lookupID = temp->getID();
  2842. UnsignedInt now = TheGameLogic->getFrame();
  2843. SpecialPowerReadyTimerType *timer;
  2844. SpecialPowerReadyTimerListIterator it;
  2845. for( it = m_specialPowerReadyTimerList.begin(); it != m_specialPowerReadyTimerList.end(); ++it )
  2846. {
  2847. timer = &(*it);
  2848. if ( timer->m_templateID == lookupID )
  2849. {
  2850. timer->m_readyFrame = now + temp->getReloadTime();
  2851. return;
  2852. }
  2853. }
  2854. addNewSharedSpecialPowerTimer( temp, now );
  2855. }
  2856. void Player::expressSpecialPowerReadyFrame( const SpecialPowerTemplate *temp, UnsignedInt frame )
  2857. {
  2858. SpecialPowerReadyTimerType *timer;
  2859. SpecialPowerReadyTimerListIterator it;
  2860. for( it = m_specialPowerReadyTimerList.begin(); it != m_specialPowerReadyTimerList.end(); ++it )
  2861. {
  2862. timer = &(*it);
  2863. if ( timer->m_templateID == temp->getID() )
  2864. {
  2865. timer->m_readyFrame = frame;
  2866. return;
  2867. }
  2868. }
  2869. addNewSharedSpecialPowerTimer( temp, frame );
  2870. }
  2871. //-------------------------------------------------------------------------------------------------
  2872. UnsignedInt Player::getOrStartSpecialPowerReadyFrame( const SpecialPowerTemplate *temp)
  2873. {
  2874. UnsignedInt lookupID = temp->getID();
  2875. UnsignedInt now = TheGameLogic->getFrame();
  2876. SpecialPowerReadyTimerType *timer;
  2877. SpecialPowerReadyTimerListIterator it;
  2878. UnsignedInt count = 0;
  2879. UnsignedInt timerID = 0xfacade;
  2880. for( it = m_specialPowerReadyTimerList.begin(); it != m_specialPowerReadyTimerList.end(); ++it )
  2881. {
  2882. timer = &(*it);
  2883. ++count;
  2884. timerID = timer->m_templateID;
  2885. if ( timerID == lookupID )
  2886. {
  2887. return timer->m_readyFrame;
  2888. }
  2889. }
  2890. addNewSharedSpecialPowerTimer( temp, now );
  2891. return now;
  2892. }
  2893. //-------------------------------------------------------------------------------------------------
  2894. //-------------------------------------------------------------------------------------------------
  2895. void Player::friend_applyDifficultyBonusesForObject(Object* obj, Bool apply) const
  2896. {
  2897. if (TheGameLogic->isInSinglePlayerGame())
  2898. {
  2899. Real healthFactor = TheGlobalData->m_soloPlayerHealthBonusForDifficulty[getPlayerType()][getPlayerDifficulty()];
  2900. if (healthFactor != 1.0f)
  2901. {
  2902. BodyModuleInterface* body = obj->getBodyModule();
  2903. if (apply)
  2904. body->setMaxHealth(body->getMaxHealth() * healthFactor, PRESERVE_RATIO);
  2905. else
  2906. body->setMaxHealth(body->getMaxHealth() / healthFactor, PRESERVE_RATIO);
  2907. }
  2908. static const WeaponBonusConditionType wbonus[PLAYERTYPE_COUNT][DIFFICULTY_COUNT] =
  2909. {
  2910. {
  2911. WEAPONBONUSCONDITION_SOLO_HUMAN_EASY,
  2912. WEAPONBONUSCONDITION_SOLO_HUMAN_NORMAL,
  2913. WEAPONBONUSCONDITION_SOLO_HUMAN_HARD
  2914. },
  2915. {
  2916. WEAPONBONUSCONDITION_SOLO_AI_EASY,
  2917. WEAPONBONUSCONDITION_SOLO_AI_NORMAL,
  2918. WEAPONBONUSCONDITION_SOLO_AI_HARD
  2919. }
  2920. };
  2921. if (apply)
  2922. obj->setWeaponBonusCondition(wbonus[getPlayerType()][getPlayerDifficulty()]);
  2923. else
  2924. obj->clearWeaponBonusCondition(wbonus[getPlayerType()][getPlayerDifficulty()]);
  2925. }
  2926. }
  2927. //-------------------------------------------------------------------------------------------------
  2928. //-------------------------------------------------------------------------------------------------
  2929. Bool Player::doesObjectQualifyForBattlePlan( Object *obj ) const
  2930. {
  2931. if( m_battlePlanBonuses && obj )
  2932. {
  2933. if( obj->isAnyKindOf( m_battlePlanBonuses->m_validKindOf ) )
  2934. {
  2935. if( !obj->isAnyKindOf( m_battlePlanBonuses->m_invalidKindOf ) )
  2936. {
  2937. return true;
  2938. }
  2939. }
  2940. }
  2941. return false;
  2942. }
  2943. //-------------------------------------------------------------------------------------------------
  2944. // note, bonus is an in-out parm.
  2945. void Player::changeBattlePlan( BattlePlanStatus plan, Int delta, BattlePlanBonuses *bonus )
  2946. {
  2947. DUMPBATTLEPLANBONUSES(bonus, this, NULL);
  2948. Bool addBonus = false;
  2949. Bool removeBonus = false;
  2950. switch( plan )
  2951. {
  2952. case PLANSTATUS_BOMBARDMENT:
  2953. {
  2954. m_bombardBattlePlans += delta;
  2955. if( m_bombardBattlePlans == 1 && delta == 1 )
  2956. {
  2957. addBonus = true;
  2958. }
  2959. else if( m_bombardBattlePlans == 0 && delta == -1 )
  2960. {
  2961. removeBonus = true;
  2962. }
  2963. break;
  2964. }
  2965. case PLANSTATUS_HOLDTHELINE:
  2966. {
  2967. m_holdTheLineBattlePlans += delta;
  2968. if( m_holdTheLineBattlePlans == 1 && delta == 1 )
  2969. {
  2970. addBonus = true;
  2971. }
  2972. else if( m_holdTheLineBattlePlans == 0 && delta == -1 )
  2973. {
  2974. removeBonus = true;
  2975. }
  2976. break;
  2977. }
  2978. case PLANSTATUS_SEARCHANDDESTROY:
  2979. {
  2980. m_searchAndDestroyBattlePlans += delta;
  2981. if( m_searchAndDestroyBattlePlans == 1 && delta == 1 )
  2982. {
  2983. addBonus = true;
  2984. }
  2985. else if( m_searchAndDestroyBattlePlans == 0 && delta == -1 )
  2986. {
  2987. removeBonus = true;
  2988. }
  2989. break;
  2990. }
  2991. }
  2992. if( addBonus )
  2993. {
  2994. applyBattlePlanBonusesForPlayerObjects( bonus );
  2995. }
  2996. else if( removeBonus )
  2997. {
  2998. //First, inverse the bonuses
  2999. bonus->m_armorScalar = 1.0f / __max( bonus->m_armorScalar, 0.01f );
  3000. bonus->m_sightRangeScalar = 1.0f / __max( bonus->m_sightRangeScalar, 0.01f );
  3001. if( bonus->m_bombardment > 0 )
  3002. {
  3003. bonus->m_bombardment = -1;
  3004. }
  3005. if( bonus->m_holdTheLine > 0 )
  3006. {
  3007. bonus->m_holdTheLine = -1;
  3008. }
  3009. if( bonus->m_searchAndDestroy > 0 )
  3010. {
  3011. bonus->m_searchAndDestroy = -1;
  3012. }
  3013. applyBattlePlanBonusesForPlayerObjects( bonus );
  3014. }
  3015. }
  3016. //-------------------------------------------------------------------------------------------------
  3017. Int Player::getBattlePlansActiveSpecific( BattlePlanStatus plan ) const
  3018. {
  3019. switch( plan )
  3020. {
  3021. case PLANSTATUS_BOMBARDMENT:
  3022. {
  3023. return m_bombardBattlePlans;
  3024. }
  3025. case PLANSTATUS_HOLDTHELINE:
  3026. {
  3027. return m_holdTheLineBattlePlans;
  3028. }
  3029. case PLANSTATUS_SEARCHANDDESTROY:
  3030. {
  3031. return m_searchAndDestroyBattlePlans;
  3032. }
  3033. }
  3034. return 0;
  3035. }
  3036. //------------------------------------------------------------------------------------------------
  3037. static void localApplyBattlePlanBonusesToObject( Object *obj, void *userData )
  3038. {
  3039. const BattlePlanBonuses* bonus = (const BattlePlanBonuses*)userData;
  3040. Object *objectToValidate = obj;
  3041. Object *objectToModify = obj;
  3042. DEBUG_LOG(("localApplyBattlePlanBonusesToObject() - looking at object %d (%s)\n",
  3043. (objectToValidate)?objectToValidate->getID():INVALID_ID,
  3044. (objectToValidate)?objectToValidate->getTemplate()->getName().str():"<No Object>"));
  3045. //First check if the obj is a projectile -- if so split the
  3046. //object so that the producer is validated, not the projectile.
  3047. Bool isProjectile = obj->isKindOf( KINDOF_PROJECTILE );
  3048. if( isProjectile )
  3049. {
  3050. objectToValidate = TheGameLogic->findObjectByID( obj->getProducerID() );
  3051. DEBUG_LOG(("Object is a projectile - looking at object %d (%s) instead\n",
  3052. (objectToValidate)?objectToValidate->getID():INVALID_ID,
  3053. (objectToValidate)?objectToValidate->getTemplate()->getName().str():"<No Object>"));
  3054. }
  3055. if( objectToValidate && objectToValidate->isAnyKindOf( bonus->m_validKindOf ) )
  3056. {
  3057. DEBUG_LOG(("Is valid kindof\n"));
  3058. if( !objectToValidate->isAnyKindOf( bonus->m_invalidKindOf ) )
  3059. {
  3060. DEBUG_LOG(("Is not invalid kindof\n"));
  3061. //Quite the trek eh? Now we can apply the bonuses!
  3062. if( !isProjectile )
  3063. {
  3064. DEBUG_LOG(("Is not projectile. Armor scalar is %g\n", bonus->m_armorScalar));
  3065. //Really important to not apply certain bonuses like health augmentation to projectiles!
  3066. if( bonus->m_armorScalar != 1.0f )
  3067. {
  3068. BodyModuleInterface *body = objectToModify->getBodyModule();
  3069. body->applyDamageScalar( bonus->m_armorScalar );
  3070. CRCDEBUG_LOG(("Applying armor scalar of %g (%8.8X) to object %d (%ls) owned by player %d\n",
  3071. bonus->m_armorScalar, AS_INT(bonus->m_armorScalar), objectToModify->getID(),
  3072. objectToModify->getTemplate()->getDisplayName().str(),
  3073. objectToModify->getControllingPlayer()->getPlayerIndex()));
  3074. DEBUG_LOG(("After apply, armor scalar is %g\n", body->getDamageScalar()));
  3075. }
  3076. if( bonus->m_sightRangeScalar != 1.0f )
  3077. {
  3078. objectToModify->setVisionRange( obj->getVisionRange() * bonus->m_sightRangeScalar );
  3079. objectToModify->setShroudClearingRange( obj->getShroudClearingRange() * bonus->m_sightRangeScalar );
  3080. }
  3081. }
  3082. if( bonus->m_bombardment > 0 )
  3083. {
  3084. objectToModify->setWeaponBonusCondition( WEAPONBONUSCONDITION_BATTLEPLAN_BOMBARDMENT );
  3085. }
  3086. else
  3087. {
  3088. objectToModify->clearWeaponBonusCondition( WEAPONBONUSCONDITION_BATTLEPLAN_BOMBARDMENT );
  3089. }
  3090. if( bonus->m_holdTheLine > 0 )
  3091. {
  3092. objectToModify->setWeaponBonusCondition( WEAPONBONUSCONDITION_BATTLEPLAN_HOLDTHELINE );
  3093. }
  3094. else
  3095. {
  3096. objectToModify->clearWeaponBonusCondition( WEAPONBONUSCONDITION_BATTLEPLAN_HOLDTHELINE );
  3097. }
  3098. if( bonus->m_searchAndDestroy > 0 )
  3099. {
  3100. objectToModify->setWeaponBonusCondition( WEAPONBONUSCONDITION_BATTLEPLAN_SEARCHANDDESTROY );
  3101. }
  3102. else
  3103. {
  3104. objectToModify->clearWeaponBonusCondition( WEAPONBONUSCONDITION_BATTLEPLAN_SEARCHANDDESTROY );
  3105. }
  3106. }
  3107. }
  3108. }
  3109. //-------------------------------------------------------------------------------------------------
  3110. //New object or converted object gaining our current battle plan bonuses.
  3111. //-------------------------------------------------------------------------------------------------
  3112. void Player::applyBattlePlanBonusesForObject( Object *obj ) const
  3113. {
  3114. localApplyBattlePlanBonusesToObject( obj, m_battlePlanBonuses );
  3115. }
  3116. //-------------------------------------------------------------------------------------------------
  3117. //Object has just left our team, so remove it's bonuses!
  3118. //-------------------------------------------------------------------------------------------------
  3119. void Player::removeBattlePlanBonusesForObject( Object *obj ) const
  3120. {
  3121. //Copy bonuses, and invert them.
  3122. BattlePlanBonuses* bonus = newInstance(BattlePlanBonuses);
  3123. *bonus = *m_battlePlanBonuses;
  3124. bonus->m_armorScalar = 1.0f / __max( bonus->m_armorScalar, 0.01f );
  3125. bonus->m_sightRangeScalar = 1.0f / __max( bonus->m_sightRangeScalar, 0.01f );
  3126. bonus->m_bombardment = -ALL_PLANS; //Safe to remove as it clears the weapon bonus flag
  3127. bonus->m_searchAndDestroy = -ALL_PLANS; //Safe to remove as it clears the weapon bonus flag
  3128. bonus->m_holdTheLine = -ALL_PLANS; //Safe to remove as it clears the weapon bonus flag
  3129. DUMPBATTLEPLANBONUSES(bonus, this, obj);
  3130. localApplyBattlePlanBonusesToObject( obj, bonus );
  3131. bonus->deleteInstance();
  3132. }
  3133. //-------------------------------------------------------------------------------------------------
  3134. //Battle plan bonuses changing, so apply to all of our objects!
  3135. //-------------------------------------------------------------------------------------------------
  3136. void Player::applyBattlePlanBonusesForPlayerObjects( const BattlePlanBonuses *bonus )
  3137. {
  3138. DUMPBATTLEPLANBONUSES(bonus, this, NULL);
  3139. //Only allocate the battle plan bonuses if we actually use it!
  3140. if( !m_battlePlanBonuses )
  3141. {
  3142. DEBUG_LOG(("Allocating new m_battlePlanBonuses\n"));
  3143. m_battlePlanBonuses = newInstance( BattlePlanBonuses );
  3144. *m_battlePlanBonuses = *bonus;
  3145. }
  3146. else
  3147. {
  3148. DEBUG_LOG(("Adding bonus into existing m_battlePlanBonuses\n"));
  3149. DUMPBATTLEPLANBONUSES(m_battlePlanBonuses, this, NULL);
  3150. //Just apply the differences by multiplying the scalars together (kindofs won't change)
  3151. //These bonuses are used for new objects that are created or objects that are transferred
  3152. //to our team.
  3153. m_battlePlanBonuses->m_armorScalar *= bonus->m_armorScalar;
  3154. m_battlePlanBonuses->m_sightRangeScalar *= bonus->m_sightRangeScalar;
  3155. m_battlePlanBonuses->m_bombardment += bonus->m_bombardment;
  3156. m_battlePlanBonuses->m_bombardment = MAX( 0, m_battlePlanBonuses->m_bombardment );
  3157. m_battlePlanBonuses->m_holdTheLine += bonus->m_holdTheLine;
  3158. m_battlePlanBonuses->m_holdTheLine = MAX( 0, m_battlePlanBonuses->m_holdTheLine );
  3159. m_battlePlanBonuses->m_searchAndDestroy += bonus->m_searchAndDestroy;
  3160. m_battlePlanBonuses->m_searchAndDestroy = MAX( 0, m_battlePlanBonuses->m_searchAndDestroy );
  3161. }
  3162. DUMPBATTLEPLANBONUSES(m_battlePlanBonuses, this, NULL);
  3163. iterateObjects( localApplyBattlePlanBonusesToObject, (void*)bonus );
  3164. }
  3165. //-------------------------------------------------------------------------------------------------
  3166. /** Create a hotkey team based on this GameMessage */
  3167. //-------------------------------------------------------------------------------------------------
  3168. void Player::processCreateTeamGameMessage(Int hotkeyNum, GameMessage *msg) {
  3169. // GameMessage arguments are the object ID's of the objects that are to be in this team.
  3170. if ((hotkeyNum < 0) || (hotkeyNum >= NUM_HOTKEY_SQUADS)) {
  3171. DEBUG_CRASH(("processCreateTeamGameMessage got an invalid hotkey number"));
  3172. return;
  3173. }
  3174. m_squads[hotkeyNum]->clearSquad();
  3175. UnsignedByte numArgs = msg->getArgumentCount();
  3176. for (UnsignedByte i = 0; i < numArgs; ++i) {
  3177. ObjectID objID = msg->getArgument(i)->objectID;
  3178. Object *obj = TheGameLogic->findObjectByID(objID);
  3179. if (obj != NULL) {
  3180. // first, remove it from any other hotkey squads it is in.
  3181. removeObjectFromHotkeySquad(obj);
  3182. m_squads[hotkeyNum]->addObject(obj);
  3183. }
  3184. }
  3185. }
  3186. //-------------------------------------------------------------------------------------------------
  3187. /** Select a hotkey team based on this GameMessage */
  3188. //-------------------------------------------------------------------------------------------------
  3189. void Player::processSelectTeamGameMessage(Int hotkeyNum, GameMessage *msg) {
  3190. if ((hotkeyNum < 0) || (hotkeyNum >= NUM_HOTKEY_SQUADS)) {
  3191. DEBUG_CRASH(("processSelectTeamGameMessage got an invalid hotkey number"));
  3192. return;
  3193. }
  3194. if (m_squads[hotkeyNum] == NULL) {
  3195. return;
  3196. }
  3197. m_currentSelection->clearSquad();
  3198. VecObjectPtr objectList = m_squads[hotkeyNum]->getLiveObjects();
  3199. Int numObjs = objectList.size();
  3200. for (Int i = 0; i < numObjs; ++i)
  3201. {
  3202. m_currentSelection->addObject(objectList[i]);
  3203. }
  3204. if( numObjs > 0 )
  3205. {
  3206. getAcademyStats()->recordControlGroupsUsed();
  3207. }
  3208. }
  3209. //-------------------------------------------------------------------------------------------------
  3210. /** Select a hotkey team based on this GameMessage */
  3211. //-------------------------------------------------------------------------------------------------
  3212. void Player::processAddTeamGameMessage(Int hotkeyNum, GameMessage *msg) {
  3213. if ((hotkeyNum < 0) || (hotkeyNum >= NUM_HOTKEY_SQUADS)) {
  3214. DEBUG_CRASH(("processAddTeamGameMessage got an invalid hotkey number"));
  3215. return;
  3216. }
  3217. if (m_squads[hotkeyNum] == NULL) {
  3218. return;
  3219. }
  3220. if (m_currentSelection == NULL) {
  3221. m_currentSelection = newInstance( Squad );
  3222. }
  3223. VecObjectPtr objectList = m_squads[hotkeyNum]->getLiveObjects();
  3224. Int numObjs = objectList.size();
  3225. for (Int i = 0; i < numObjs; ++i) {
  3226. m_currentSelection->addObject(objectList[i]);
  3227. }
  3228. }
  3229. //-------------------------------------------------------------------------------------------------
  3230. /** Select a hotkey team based on this GameMessage */
  3231. //-------------------------------------------------------------------------------------------------
  3232. void Player::getCurrentSelectionAsAIGroup(AIGroup *group) {
  3233. if (m_currentSelection != NULL) {
  3234. m_currentSelection->aiGroupFromSquad(group);
  3235. }
  3236. }
  3237. //-------------------------------------------------------------------------------------------------
  3238. /** Select a hotkey team based on this GameMessage */
  3239. //-------------------------------------------------------------------------------------------------
  3240. void Player::setCurrentlySelectedAIGroup(AIGroup *group) {
  3241. if (m_currentSelection == NULL) {
  3242. m_currentSelection = newInstance( Squad );
  3243. }
  3244. m_currentSelection->clearSquad();
  3245. if (group != NULL) {
  3246. m_currentSelection->squadFromAIGroup(group, true);
  3247. }
  3248. }
  3249. //-------------------------------------------------------------------------------------------------
  3250. /** Select a hotkey team based on this GameMessage */
  3251. //-------------------------------------------------------------------------------------------------
  3252. Squad *Player::getHotkeySquad(Int squadNumber)
  3253. {
  3254. if ((squadNumber >= 0) && (squadNumber < NUM_HOTKEY_SQUADS)) {
  3255. return m_squads[squadNumber];
  3256. }
  3257. return NULL;
  3258. }
  3259. //-------------------------------------------------------------------------------------------------
  3260. /** return the hotkey squad that a unit is in, or NO_HOTKEY_SQUAD if it isn't in one */
  3261. //-------------------------------------------------------------------------------------------------
  3262. Int Player::getSquadNumberForObject(const Object *objToFind) const
  3263. {
  3264. for (Int i = 0; i < NUM_HOTKEY_SQUADS; ++i) {
  3265. if (m_squads[i]->isOnSquad(objToFind)) {
  3266. return i;
  3267. }
  3268. }
  3269. return NO_HOTKEY_SQUAD;
  3270. }
  3271. //-------------------------------------------------------------------------------------------------
  3272. /** Remove an object from any hotkey squads its on. (Should never be more than one, but do them */
  3273. /** all for good measure. */
  3274. //-------------------------------------------------------------------------------------------------
  3275. void Player::removeObjectFromHotkeySquad(Object *objToRemove)
  3276. {
  3277. for (Int i = 0; i < NUM_HOTKEY_SQUADS; ++i) {
  3278. if (!m_squads[i]) {
  3279. continue;
  3280. }
  3281. m_squads[i]->removeObject(objToRemove);
  3282. }
  3283. }
  3284. //-------------------------------------------------------------------------------------------------
  3285. /** Select a hotkey team based on this GameMessage */
  3286. //-------------------------------------------------------------------------------------------------
  3287. void Player::addAIGroupToCurrentSelection(AIGroup *group) {
  3288. if (group == NULL) {
  3289. return;
  3290. }
  3291. if (m_currentSelection == NULL) {
  3292. m_currentSelection = newInstance( Squad );
  3293. }
  3294. VecObjectID objectIDVec = group->getAllIDs();
  3295. Int numObjs = objectIDVec.size();
  3296. for (Int i = 0; i < numObjs; ++i) {
  3297. m_currentSelection->addObjectID(objectIDVec[i]);
  3298. }
  3299. }
  3300. //-------------------------------------------------------------------------------------------------
  3301. /** addTypeOfProductionCostChange adds a production change to the typeof list */
  3302. //-------------------------------------------------------------------------------------------------
  3303. void Player::addKindOfProductionCostChange( KindOfMaskType kindOf, Real percent )
  3304. {
  3305. KindOfPercentProductionChangeListIt it = m_kindOfPercentProductionChangeList.begin();
  3306. while(it != m_kindOfPercentProductionChangeList.end())
  3307. {
  3308. KindOfPercentProductionChange *tof = *it;
  3309. if( tof->m_percent == percent && tof->m_kindOf == kindOf)
  3310. {
  3311. tof->m_ref++;
  3312. return;
  3313. }
  3314. ++it;
  3315. }
  3316. KindOfPercentProductionChange *newTof = newInstance( KindOfPercentProductionChange );
  3317. newTof->m_kindOf = kindOf;
  3318. newTof->m_percent = percent;
  3319. newTof->m_ref = 1;
  3320. m_kindOfPercentProductionChangeList.push_back(newTof);
  3321. }
  3322. //-------------------------------------------------------------------------------------------------
  3323. /** addTypeOfProductionCostChange adds a production change to the typeof list */
  3324. //-------------------------------------------------------------------------------------------------
  3325. void Player::removeKindOfProductionCostChange( KindOfMaskType kindOf, Real percent )
  3326. {
  3327. KindOfPercentProductionChangeListIt it = m_kindOfPercentProductionChangeList.begin();
  3328. while(it != m_kindOfPercentProductionChangeList.end())
  3329. {
  3330. KindOfPercentProductionChange* tof = *it;
  3331. if( tof->m_percent == percent && tof->m_kindOf == kindOf)
  3332. {
  3333. tof->m_ref--;
  3334. if(tof->m_ref == 0)
  3335. {
  3336. m_kindOfPercentProductionChangeList.erase( it );
  3337. if(tof)
  3338. tof->deleteInstance();
  3339. }
  3340. return;
  3341. }
  3342. ++it;
  3343. }
  3344. DEBUG_ASSERTCRASH(FALSE, ("removeKindOfProductionCostChange was called with kindOf=%d and percent=%f. We could not find the entry in the list with these variables. CLH.",kindOf, percent));
  3345. }
  3346. //-------------------------------------------------------------------------------------------------
  3347. /** getProductionCostChangeBasedOnKindOf gets the cost percentage change based off of Kindof Mask */
  3348. //-------------------------------------------------------------------------------------------------
  3349. Real Player::getProductionCostChangeBasedOnKindOf( KindOfMaskType kindOf ) const
  3350. {
  3351. Real start = 1.0f;
  3352. KindOfPercentProductionChangeListIt it = m_kindOfPercentProductionChangeList.begin();
  3353. while(it != m_kindOfPercentProductionChangeList.end())
  3354. {
  3355. KindOfPercentProductionChange *tof = *it;
  3356. if(TEST_KINDOFMASK_MULTI(kindOf, tof->m_kindOf, KINDOFMASK_NONE))
  3357. {
  3358. start *= (1 + tof->m_percent);
  3359. }
  3360. ++it;
  3361. }
  3362. return (start);
  3363. }
  3364. //-------------------------------------------------------------------------------------------------
  3365. /** setAttackedBy */
  3366. //-------------------------------------------------------------------------------------------------
  3367. void Player::setAttackedBy( Int playerNdx )
  3368. {
  3369. DEBUG_ASSERTCRASH(playerNdx >= 0, ("Player::setAttackedBy Player index is %d", playerNdx));
  3370. m_attackedBy[playerNdx] = true;
  3371. m_attackedFrame = TheGameLogic->getFrame();
  3372. }
  3373. //-------------------------------------------------------------------------------------------------
  3374. /** getAttackedBy */
  3375. //-------------------------------------------------------------------------------------------------
  3376. Bool Player::getAttackedBy( Int playerNdx ) const
  3377. {
  3378. return m_attackedBy[playerNdx];
  3379. }
  3380. // ------------------------------------------------------------------------------------------------
  3381. // Little wrapper function so I can use it in iterateObjects, which is cool.
  3382. struct VisionSpiedStruct
  3383. {
  3384. Bool setting;
  3385. KindOfMaskType whichUnits;
  3386. PlayerIndex byWhom;
  3387. };
  3388. static void iterator_setUnitsVisionSpied( Object *obj, void * voidData)
  3389. {
  3390. VisionSpiedStruct *data = (VisionSpiedStruct *)voidData;
  3391. // I feel I have to disapprove of the naming of this gathering of cell functions. It is called by death,
  3392. // alliance change, containment, spy change, and dynamic view range as well as partition cell change.
  3393. if( obj && obj->isAnyKindOf(data->whichUnits) )
  3394. obj->setVisionSpied(data->setting, data->byWhom);
  3395. }
  3396. // ------------------------------------------------------------------------------------------------
  3397. void Player::setUnitsVisionSpied( Bool setting, KindOfMaskType whichUnits, PlayerIndex byWhom )
  3398. {
  3399. VisionSpiedStruct data;
  3400. data.setting = setting;
  3401. data.whichUnits = whichUnits;
  3402. data.byWhom = byWhom;
  3403. // Being spied is now a property of the unit, not us, since we can spy only a portion of the enemy.
  3404. iterateObjects( iterator_setUnitsVisionSpied, &data );
  3405. }
  3406. // ------------------------------------------------------------------------------------------------
  3407. Bool Player::isPlayerObserver(void) const
  3408. {
  3409. return m_observer;
  3410. }
  3411. // ------------------------------------------------------------------------------------------------
  3412. Bool Player::isPlayerDead(void) const
  3413. {
  3414. return m_isPlayerDead;
  3415. }
  3416. // ------------------------------------------------------------------------------------------------
  3417. Bool Player::isPlayerActive(void) const
  3418. {
  3419. return !m_observer && !m_isPlayerDead;
  3420. }
  3421. // ------------------------------------------------------------------------------------------------
  3422. Bool Player::isPlayableSide( void ) const
  3423. {
  3424. return m_playerTemplate ? m_playerTemplate->isPlayableSide() : FALSE;
  3425. } // end isPlayableSide
  3426. // ------------------------------------------------------------------------------------------------
  3427. /** CRC */
  3428. // ------------------------------------------------------------------------------------------------
  3429. void Player::crc( Xfer *xfer )
  3430. {
  3431. // Player battle plan bonuses
  3432. Bool battlePlanBonus = m_battlePlanBonuses != NULL;
  3433. xfer->xferBool( &battlePlanBonus );
  3434. CRCDEBUG_LOG(("Player %d[%ls] %s battle plans\n", m_playerIndex, m_playerDisplayName.str(), (battlePlanBonus)?"has":"doesn't have"));
  3435. if( m_battlePlanBonuses )
  3436. {
  3437. CRCDUMPBATTLEPLANBONUSES(m_battlePlanBonuses, this, NULL);
  3438. xfer->xferReal( &m_battlePlanBonuses->m_armorScalar );
  3439. xfer->xferReal( &m_battlePlanBonuses->m_sightRangeScalar );
  3440. xfer->xferInt( &m_battlePlanBonuses->m_bombardment );
  3441. xfer->xferInt( &m_battlePlanBonuses->m_holdTheLine );
  3442. xfer->xferInt( &m_battlePlanBonuses->m_searchAndDestroy );
  3443. m_battlePlanBonuses->m_validKindOf.xfer(xfer);
  3444. m_battlePlanBonuses->m_invalidKindOf.xfer(xfer);
  3445. }
  3446. xfer->xferInt( &m_skillPoints );
  3447. xfer->xferInt( &m_sciencePurchasePoints );
  3448. } // end crc
  3449. // ------------------------------------------------------------------------------------------------
  3450. /** Xfer Method
  3451. * Version Info:
  3452. * 1: Initial version
  3453. * 2: Player can now have a modifier on his skill points (multiplicative)
  3454. * 3: Player can be excluded from the score screen via script.
  3455. * 4: Player stores a list of specialpowerreadyframe timers, used by specialpowermodules abroad
  3456. * 5: ??? (Profit)
  3457. * 6: Store m_unitsShouldHunt, set to true after the script "Tell player to hunt" is called.
  3458. * 7: added Preorder flag
  3459. * 8: Save m_disabledSciences & m_hiddenSciences. jba.
  3460. */
  3461. // ------------------------------------------------------------------------------------------------
  3462. void Player::xfer( Xfer *xfer )
  3463. {
  3464. // version
  3465. const XferVersion currentVersion = 8;
  3466. XferVersion version = currentVersion;
  3467. xfer->xferVersion( &version, currentVersion );
  3468. // money
  3469. xfer->xferSnapshot( &m_money );
  3470. // upgrade list count
  3471. Upgrade *upgrade;
  3472. UnsignedShort upgradeCount = 0;
  3473. for( upgrade = m_upgradeList; upgrade; upgrade = upgrade->friend_getNext() )
  3474. upgradeCount++;
  3475. xfer->xferUnsignedShort( &upgradeCount );
  3476. if (version >= 7)
  3477. {
  3478. // preorder info
  3479. xfer->xferBool( & m_isPreorder );
  3480. }
  3481. if (version >= 8)
  3482. {
  3483. xfer->xferScienceVec(&m_sciencesDisabled);
  3484. xfer->xferScienceVec(&m_sciencesHidden);
  3485. }
  3486. // xfer upgrade instances
  3487. AsciiString upgradeName;
  3488. if( xfer->getXferMode() == XFER_SAVE )
  3489. {
  3490. for( upgrade = m_upgradeList; upgrade; upgrade = upgrade->friend_getNext() )
  3491. {
  3492. // write upgrade name
  3493. upgradeName = upgrade->getTemplate()->getUpgradeName();
  3494. xfer->xferAsciiString( &upgradeName );
  3495. // xfer upgrade data
  3496. xfer->xferSnapshot( upgrade );
  3497. } // end for, upgrade
  3498. } // end if, save
  3499. else
  3500. {
  3501. const UpgradeTemplate *upgradeTemplate;
  3502. for( UnsignedShort i = 0; i < upgradeCount; ++i )
  3503. {
  3504. // read name
  3505. xfer->xferAsciiString( &upgradeName );
  3506. // find template for this upgrade
  3507. upgradeTemplate = TheUpgradeCenter->findUpgrade( upgradeName );
  3508. // sanity
  3509. if( upgradeTemplate == NULL )
  3510. {
  3511. DEBUG_CRASH(( "Player::xfer - Unable to find upgrade '%s'\n", upgradeName.str() ));
  3512. throw SC_INVALID_DATA;
  3513. } // end if
  3514. // add upgrade to player, the status is invalid, but that's OK cause we're about to xfer it
  3515. upgrade = addUpgrade( upgradeTemplate, UPGRADE_STATUS_INVALID );
  3516. // xfer upgrade data
  3517. xfer->xferSnapshot( upgrade );
  3518. } // end for, i
  3519. } // end else, load
  3520. // radar info
  3521. xfer->xferInt( &m_radarCount );
  3522. xfer->xferBool( & m_isPlayerDead );
  3523. xfer->xferInt( &m_disableProofRadarCount );
  3524. xfer->xferBool( & m_radarDisabled );
  3525. // upgrades in progress
  3526. xfer->xferUpgradeMask( &m_upgradesInProgress );
  3527. // upgrades complete
  3528. xfer->xferUpgradeMask( &m_upgradesCompleted );
  3529. // energy info
  3530. xfer->xferSnapshot( &m_energy );
  3531. //
  3532. // team prototypes ... this is only the fact that team prototypes are on this player
  3533. // it is not the team prototype data itself
  3534. //
  3535. UnsignedShort prototypeCount = m_playerTeamPrototypes.size();
  3536. xfer->xferUnsignedShort( &prototypeCount );
  3537. TeamPrototypeID prototypeID;
  3538. TeamPrototype *prototype;
  3539. if( xfer->getXferMode() == XFER_SAVE )
  3540. {
  3541. PlayerTeamList::iterator it;
  3542. for( it = m_playerTeamPrototypes.begin(); it != m_playerTeamPrototypes.end(); ++it )
  3543. {
  3544. prototype = *it;
  3545. prototypeID = prototype->getID();
  3546. xfer->xferUser( &prototypeID, sizeof( TeamPrototypeID ) );
  3547. } // end for
  3548. } // end if, save
  3549. else
  3550. {
  3551. // empty the list right now
  3552. m_playerTeamPrototypes.clear();
  3553. // read all the data
  3554. for( UnsignedShort i = 0; i < prototypeCount; ++i )
  3555. {
  3556. // read id
  3557. xfer->xferUser( &prototypeID, sizeof( TeamPrototypeID ) );
  3558. // find prototype
  3559. prototype = TheTeamFactory->findTeamPrototypeByID( prototypeID );
  3560. // sanity
  3561. if( prototype == NULL )
  3562. {
  3563. DEBUG_CRASH(( "Player::xfer - Unable to find team prototype by id\n" ));
  3564. throw SC_INVALID_DATA;
  3565. } // end if
  3566. // put in list
  3567. m_playerTeamPrototypes.push_back( prototype );
  3568. } // end for, i
  3569. } // end else, load
  3570. // build list info
  3571. UnsignedShort buildListInfoCount = 0;
  3572. BuildListInfo *buildListInfo;
  3573. for( buildListInfo = m_pBuildList; buildListInfo; buildListInfo = buildListInfo->getNext() )
  3574. buildListInfoCount++;
  3575. xfer->xferUnsignedShort( &buildListInfoCount );
  3576. if( xfer->getXferMode() == XFER_SAVE )
  3577. {
  3578. // xfer each build list info
  3579. for( buildListInfo = m_pBuildList; buildListInfo; buildListInfo = buildListInfo->getNext() )
  3580. xfer->xferSnapshot( buildListInfo );
  3581. } // end if, save
  3582. else
  3583. {
  3584. //
  3585. // destroy any build list that we got from loading the bare bones map, note that deleting
  3586. // the head of these structures automatically deletes any links attached
  3587. //
  3588. if( m_pBuildList)
  3589. m_pBuildList->deleteInstance();
  3590. m_pBuildList = NULL;
  3591. // read each build list info
  3592. for( UnsignedShort i = 0; i < buildListInfoCount; ++i )
  3593. {
  3594. // allocate new build list
  3595. buildListInfo = newInstance( BuildListInfo );
  3596. buildListInfo->setNextBuildList( NULL );
  3597. // attach to the *end* of the list in the player
  3598. if( m_pBuildList == NULL )
  3599. m_pBuildList = buildListInfo;
  3600. else
  3601. {
  3602. BuildListInfo *last = m_pBuildList;
  3603. while( last->getNext() != NULL )
  3604. last = last->getNext();
  3605. last->setNextBuildList( buildListInfo );
  3606. } // end else
  3607. // xfer data
  3608. xfer->xferSnapshot( buildListInfo );
  3609. } // end for,i
  3610. } // end else, load
  3611. // ai player data
  3612. Bool aiPlayerPresent = m_ai ? TRUE : FALSE;
  3613. xfer->xferBool( &aiPlayerPresent );
  3614. if( (aiPlayerPresent == TRUE && m_ai == NULL) || (aiPlayerPresent == FALSE && m_ai != NULL) )
  3615. {
  3616. DEBUG_CRASH(( "Player::xfer - m_ai present/missing mismatch\n" ));
  3617. throw SC_INVALID_DATA;;
  3618. } // end if
  3619. if( m_ai )
  3620. xfer->xferSnapshot( m_ai );
  3621. // resource gathering manager
  3622. Bool resourceGatheringManagerPresent = m_resourceGatheringManager ? TRUE : FALSE;
  3623. xfer->xferBool( &resourceGatheringManagerPresent );
  3624. if( (resourceGatheringManagerPresent == TRUE && m_resourceGatheringManager == NULL) ||
  3625. (resourceGatheringManagerPresent == FALSE && m_resourceGatheringManager != NULL ) )
  3626. {
  3627. DEBUG_CRASH(( "Player::xfer - m_resourceGatheringManager present/missing mismatch\n" ));
  3628. throw SC_INVALID_DATA;
  3629. } // end if
  3630. if( m_resourceGatheringManager )
  3631. xfer->xferSnapshot( m_resourceGatheringManager );
  3632. // tunnel tracking system
  3633. Bool tunnelTrackerPresent = m_tunnelSystem ? TRUE : FALSE;
  3634. xfer->xferBool( &tunnelTrackerPresent );
  3635. if( (tunnelTrackerPresent == TRUE && m_tunnelSystem == NULL) ||
  3636. (tunnelTrackerPresent == FALSE && m_tunnelSystem != NULL) )
  3637. {
  3638. DEBUG_CRASH(( "Player::xfer - m_tunnelSystem present/missing mismatch\n" ));
  3639. throw SC_INVALID_DATA;
  3640. } // end if
  3641. if( m_tunnelSystem )
  3642. xfer->xferSnapshot( m_tunnelSystem );
  3643. // default team
  3644. TeamID teamID = m_defaultTeam ? m_defaultTeam->getID() : TEAM_ID_INVALID;
  3645. xfer->xferUser( &teamID, sizeof( TeamID ) );
  3646. if( xfer->getXferMode() == XFER_LOAD )
  3647. m_defaultTeam = TheTeamFactory->findTeamByID( teamID );
  3648. // sciences
  3649. if (version >= 5)
  3650. {
  3651. // m_sciences will contain some intrinsic sciences and stuff, which we don't want.
  3652. // so nuke 'em for load.
  3653. if( xfer->getXferMode() == XFER_LOAD )
  3654. m_sciences.clear();
  3655. xfer->xferScienceVec(&m_sciences);
  3656. }
  3657. else
  3658. {
  3659. /*
  3660. This code is WRONG WRONG WRONG and must not be used or mimicked; it
  3661. is present for backwards "compatibility" only. (srj)
  3662. */
  3663. UnsignedShort scienceCount = m_sciences.size();
  3664. xfer->xferUnsignedShort( &scienceCount );
  3665. ScienceType science;
  3666. if( xfer->getXferMode() == XFER_SAVE )
  3667. {
  3668. ScienceVec::const_iterator it;
  3669. for( it = m_sciences.begin(); it != m_sciences.end(); ++it )
  3670. {
  3671. science = *it;
  3672. xfer->xferUser( &science, sizeof( ScienceType ) );
  3673. }
  3674. }
  3675. else
  3676. {
  3677. for( UnsignedShort i = 0; i < scienceCount; ++i )
  3678. {
  3679. xfer->xferUser( &science, sizeof( ScienceType ) );
  3680. m_sciences.push_back( science );
  3681. }
  3682. }
  3683. /*
  3684. This code is WRONG WRONG WRONG and must not be used or mimicked; it
  3685. is present for backwards "compatibility" only. (srj)
  3686. */
  3687. }
  3688. // rank level
  3689. xfer->xferInt( &m_rankLevel );
  3690. // skill points
  3691. xfer->xferInt( &m_skillPoints );
  3692. // science purchase points
  3693. xfer->xferInt( &m_sciencePurchasePoints );
  3694. // level up
  3695. xfer->xferInt( &m_levelUp );
  3696. // level down
  3697. xfer->xferInt( &m_levelDown );
  3698. // general name
  3699. xfer->xferUnicodeString( &m_generalName );
  3700. // player relations
  3701. xfer->xferSnapshot( m_playerRelations );
  3702. // team relations
  3703. xfer->xferSnapshot( m_teamRelations );
  3704. // can build units
  3705. xfer->xferBool( &m_canBuildUnits );
  3706. // can build base
  3707. xfer->xferBool( &m_canBuildBase );
  3708. // observer
  3709. xfer->xferBool( &m_observer );
  3710. if (version >= 2)
  3711. {
  3712. // current skill point modifier value
  3713. xfer->xferReal( &m_skillPointsModifier);
  3714. }
  3715. else
  3716. {
  3717. m_skillPointsModifier = 1.0f;
  3718. }
  3719. if (version >= 3)
  3720. {
  3721. xfer->xferBool( &m_listInScoreScreen );
  3722. }
  3723. else
  3724. {
  3725. m_listInScoreScreen = TRUE;
  3726. }
  3727. // attacked by
  3728. xfer->xferUser( m_attackedBy, sizeof( Bool ) * MAX_PLAYER_COUNT );
  3729. // cash bounty percent
  3730. xfer->xferReal( &m_cashBountyPercent );
  3731. // score keeper
  3732. xfer->xferSnapshot( &m_scoreKeeper );
  3733. // size of and data for kindof percent production change list
  3734. UnsignedShort percentProductionChangeCount = m_kindOfPercentProductionChangeList.size();
  3735. xfer->xferUnsignedShort( &percentProductionChangeCount );
  3736. KindOfPercentProductionChange *entry;
  3737. if( xfer->getXferMode() == XFER_SAVE )
  3738. {
  3739. KindOfPercentProductionChangeListIt it;
  3740. // save each item
  3741. for( it = m_kindOfPercentProductionChangeList.begin();
  3742. it != m_kindOfPercentProductionChangeList.end();
  3743. ++it )
  3744. {
  3745. // get entry data
  3746. entry = *it;
  3747. // kind of mask type
  3748. entry->m_kindOf.xfer(xfer);
  3749. // percent
  3750. xfer->xferReal( &entry->m_percent );
  3751. // ref
  3752. xfer->xferUnsignedInt( &entry->m_ref );
  3753. } // end for
  3754. } // end if, save
  3755. else
  3756. {
  3757. // sanity, list must be empty right now
  3758. if( m_kindOfPercentProductionChangeList.size() != 0 )
  3759. {
  3760. DEBUG_CRASH(( "Player::xfer - m_kindOfPercentProductionChangeList should be empty but is not\n" ));
  3761. throw SC_INVALID_DATA;
  3762. } // end if
  3763. // read each entry
  3764. for( UnsignedInt i = 0; i < percentProductionChangeCount; ++i )
  3765. {
  3766. // allocate new entry
  3767. entry = newInstance( KindOfPercentProductionChange );
  3768. // read data
  3769. entry->m_kindOf.xfer(xfer);
  3770. xfer->xferReal( &entry->m_percent );
  3771. xfer->xferUnsignedInt( &entry->m_ref );
  3772. // put at end of list
  3773. m_kindOfPercentProductionChangeList.push_back( entry );
  3774. } // end for i
  3775. } // end else, load
  3776. ///////////////////////////////////////////////////////////////////////////
  3777. if ( version < 4 )
  3778. {
  3779. m_specialPowerReadyTimerList.clear();
  3780. }
  3781. else
  3782. {
  3783. UnsignedShort timerListSize = m_specialPowerReadyTimerList.size();
  3784. xfer->xferUnsignedShort( &timerListSize );// HANDY LITTLE SHORT TO SIZE MY LIST
  3785. if( xfer->getXferMode() == XFER_SAVE )
  3786. {
  3787. SpecialPowerReadyTimerType *timer;
  3788. SpecialPowerReadyTimerListIterator it;
  3789. for( it = m_specialPowerReadyTimerList.begin(); it != m_specialPowerReadyTimerList.end(); ++it )
  3790. {
  3791. timer = &(*it);
  3792. xfer->xferUnsignedInt( &timer->m_templateID );
  3793. xfer->xferUnsignedInt( &timer->m_readyFrame );
  3794. }
  3795. }
  3796. else
  3797. {
  3798. if( m_specialPowerReadyTimerList.size() != 0 ) // sanity, list must be empty right now
  3799. {
  3800. DEBUG_CRASH(( "Player::xfer - m_specialPowerReadyTimerList should be empty but is not\n" ));
  3801. throw SC_INVALID_DATA;
  3802. } // end if
  3803. // read each entry
  3804. for( UnsignedInt i = 0; i < timerListSize; ++i )
  3805. {
  3806. SpecialPowerReadyTimerType timer;
  3807. // read data
  3808. xfer->xferUnsignedInt( &timer.m_templateID );
  3809. xfer->xferUnsignedInt( &timer.m_readyFrame );
  3810. // put at end of list
  3811. m_specialPowerReadyTimerList.push_back( timer );
  3812. } // end for i
  3813. }
  3814. }
  3815. ///////////////////////////////////////////////////////////////////////////
  3816. // squads
  3817. UnsignedShort squadCount = NUM_HOTKEY_SQUADS;
  3818. xfer->xferUnsignedShort( &squadCount );
  3819. if( squadCount != NUM_HOTKEY_SQUADS )
  3820. {
  3821. DEBUG_CRASH(( "Player::xfer - size of m_squadCount array has changed\n" ));
  3822. throw SC_INVALID_DATA;
  3823. } // end if
  3824. for( UnsignedShort i = 0; i < squadCount; ++i )
  3825. {
  3826. if( m_squads[ i ] == NULL )
  3827. {
  3828. DEBUG_CRASH(( "Player::xfer - NULL squad at index '%d'\n", i ));
  3829. throw SC_INVALID_DATA;
  3830. } // end if
  3831. xfer->xferSnapshot( m_squads[ i ] );
  3832. } // end for, i
  3833. // current squad selection
  3834. Bool currentSelectionPresent = m_currentSelection ? TRUE : FALSE;
  3835. xfer->xferBool( &currentSelectionPresent );
  3836. if( currentSelectionPresent )
  3837. {
  3838. // allocate squad if needed
  3839. if( m_currentSelection == NULL && xfer->getXferMode() == XFER_LOAD )
  3840. m_currentSelection = newInstance( Squad );
  3841. // xfer
  3842. xfer->xferSnapshot( m_currentSelection );
  3843. } // end if
  3844. // Player battle plan bonuses
  3845. Bool battlePlanBonus = m_battlePlanBonuses != NULL;
  3846. xfer->xferBool( &battlePlanBonus ); //If we're loading, it just replaces the bool
  3847. if( xfer->getXferMode() == XFER_LOAD )
  3848. {
  3849. if (m_battlePlanBonuses)
  3850. {
  3851. m_battlePlanBonuses->deleteInstance();
  3852. m_battlePlanBonuses = NULL;
  3853. }
  3854. if ( battlePlanBonus )
  3855. {
  3856. m_battlePlanBonuses = newInstance( BattlePlanBonuses );
  3857. }
  3858. }
  3859. if( m_battlePlanBonuses )
  3860. {
  3861. xfer->xferReal( &m_battlePlanBonuses->m_armorScalar );
  3862. xfer->xferReal( &m_battlePlanBonuses->m_sightRangeScalar );
  3863. xfer->xferInt( &m_battlePlanBonuses->m_bombardment );
  3864. xfer->xferInt( &m_battlePlanBonuses->m_holdTheLine );
  3865. xfer->xferInt( &m_battlePlanBonuses->m_searchAndDestroy );
  3866. m_battlePlanBonuses->m_validKindOf.xfer(xfer);
  3867. m_battlePlanBonuses->m_invalidKindOf.xfer(xfer);
  3868. }
  3869. xfer->xferInt( &m_bombardBattlePlans );
  3870. xfer->xferInt( &m_holdTheLineBattlePlans );
  3871. xfer->xferInt( &m_searchAndDestroyBattlePlans );
  3872. if (version >= 6)
  3873. {
  3874. xfer->xferBool(&m_unitsShouldHunt);
  3875. }
  3876. else
  3877. m_unitsShouldHunt = FALSE;
  3878. } // end xfer
  3879. // ------------------------------------------------------------------------------------------------
  3880. /** Load post process */
  3881. // ------------------------------------------------------------------------------------------------
  3882. void Player::loadPostProcess( void )
  3883. {
  3884. } // end loadPostProcess