Player.cpp 123 KB

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