CGameState.cpp 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574
  1. #include "StdInc.h"
  2. #include "CGameState.h"
  3. #include "mapping/CCampaignHandler.h"
  4. #include "CDefObjInfoHandler.h"
  5. #include "CArtHandler.h"
  6. #include "CBuildingHandler.h"
  7. #include "CGeneralTextHandler.h"
  8. #include "CTownHandler.h"
  9. #include "CSpellHandler.h"
  10. #include "CHeroHandler.h"
  11. #include "CObjectHandler.h"
  12. #include "CCreatureHandler.h"
  13. #include "CModHandler.h"
  14. #include "VCMI_Lib.h"
  15. #include "Connection.h"
  16. #include "mapping/CMap.h"
  17. #include "mapping/CMapService.h"
  18. #include "StartInfo.h"
  19. #include "NetPacks.h"
  20. #include "registerTypes/RegisterTypes.h"
  21. #include "mapping/CMapInfo.h"
  22. #include "BattleState.h"
  23. #include "JsonNode.h"
  24. #include "filesystem/Filesystem.h"
  25. #include "GameConstants.h"
  26. #include "rmg/CMapGenerator.h"
  27. #include "CStopWatch.h"
  28. #include "mapping/CMapEditManager.h"
  29. class CGObjectInstance;
  30. #ifdef min
  31. #undef min
  32. #endif
  33. #ifdef max
  34. #undef max
  35. #endif
  36. /*
  37. * CGameState.cpp, part of VCMI engine
  38. *
  39. * Authors: listed in file AUTHORS in main folder
  40. *
  41. * License: GNU General Public License v2.0 or later
  42. * Full text of license available in license.txt file, in main folder
  43. *
  44. */
  45. template <typename T> class CApplyOnGS;
  46. class CBaseForGSApply
  47. {
  48. public:
  49. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  50. virtual ~CBaseForGSApply(){};
  51. template<typename U> static CBaseForGSApply *getApplier(const U * t=nullptr)
  52. {
  53. return new CApplyOnGS<U>;
  54. }
  55. };
  56. template <typename T> class CApplyOnGS : public CBaseForGSApply
  57. {
  58. public:
  59. void applyOnGS(CGameState *gs, void *pack) const
  60. {
  61. T *ptr = static_cast<T*>(pack);
  62. boost::unique_lock<boost::shared_mutex> lock(*gs->mx);
  63. ptr->applyGs(gs);
  64. }
  65. };
  66. static CApplier<CBaseForGSApply> *applierGs = nullptr;
  67. // class IObjectCaller
  68. // {
  69. // public:
  70. // virtual ~IObjectCaller(){};
  71. // virtual void preInit()=0;
  72. // virtual void postInit()=0;
  73. // };
  74. //
  75. // template <typename T>
  76. // class CObjectCaller : public IObjectCaller
  77. // {
  78. // public:
  79. // void preInit()
  80. // {
  81. // //T::preInit();
  82. // }
  83. // void postInit()
  84. // {
  85. // //T::postInit();
  86. // }
  87. // };
  88. // class CObjectCallersHandler
  89. // {
  90. // public:
  91. // std::vector<IObjectCaller*> apps;
  92. //
  93. // template<typename T> void registerType(const T * t=nullptr)
  94. // {
  95. // apps.push_back(new CObjectCaller<T>);
  96. // }
  97. //
  98. // CObjectCallersHandler()
  99. // {
  100. // registerTypesMapObjects(*this);
  101. // }
  102. //
  103. // ~CObjectCallersHandler()
  104. // {
  105. // for (auto & elem : apps)
  106. // delete elem;
  107. // }
  108. //
  109. // void preInit()
  110. // {
  111. // // for (size_t i = 0; i < apps.size(); i++)
  112. // // apps[i]->preInit();
  113. // }
  114. //
  115. // void postInit()
  116. // {
  117. // //for (size_t i = 0; i < apps.size(); i++)
  118. // //apps[i]->postInit();
  119. // }
  120. // } *objCaller = nullptr;
  121. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  122. {
  123. int type = txt.first, ser = txt.second;
  124. if(type == ART_NAMES)
  125. {
  126. dst = VLC->arth->artifacts[ser]->Name();
  127. }
  128. else if(type == CRE_PL_NAMES)
  129. {
  130. dst = VLC->creh->creatures[ser]->namePl;
  131. }
  132. else if(type == MINE_NAMES)
  133. {
  134. dst = VLC->generaltexth->mines[ser].first;
  135. }
  136. else if(type == MINE_EVNTS)
  137. {
  138. dst = VLC->generaltexth->mines[ser].second;
  139. }
  140. else if(type == SPELL_NAME)
  141. {
  142. dst = SpellID(ser).toSpell()->name;
  143. }
  144. else if(type == CRE_SING_NAMES)
  145. {
  146. dst = VLC->creh->creatures[ser]->nameSing;
  147. }
  148. else if(type == ART_DESCR)
  149. {
  150. dst = VLC->arth->artifacts[ser]->Description();
  151. }
  152. else if (type == ART_EVNTS)
  153. {
  154. dst = VLC->arth->artifacts[ser]->EventText();
  155. }
  156. else if (type == OBJ_NAMES)
  157. {
  158. dst = VLC->objtypeh->getObjectName(ser);
  159. }
  160. else
  161. {
  162. std::vector<std::string> *vec;
  163. switch(type)
  164. {
  165. case GENERAL_TXT:
  166. vec = &VLC->generaltexth->allTexts;
  167. break;
  168. case XTRAINFO_TXT:
  169. vec = &VLC->generaltexth->xtrainfo;
  170. break;
  171. case RES_NAMES:
  172. vec = &VLC->generaltexth->restypes;
  173. break;
  174. case ARRAY_TXT:
  175. vec = &VLC->generaltexth->arraytxt;
  176. break;
  177. case CREGENS:
  178. vec = &VLC->generaltexth->creGens;
  179. break;
  180. case CREGENS4:
  181. vec = &VLC->generaltexth->creGens4;
  182. break;
  183. case ADVOB_TXT:
  184. vec = &VLC->generaltexth->advobtxt;
  185. break;
  186. case SEC_SKILL_NAME:
  187. vec = &VLC->generaltexth->skillName;
  188. break;
  189. case COLOR:
  190. vec = &VLC->generaltexth->capColors;
  191. break;
  192. default:
  193. logGlobal->errorStream() << "Failed string substitution because type is " << type;
  194. dst = "#@#";
  195. return;
  196. }
  197. if(vec->size() <= ser)
  198. {
  199. logGlobal->errorStream() << "Failed string substitution with type " << type << " because index " << ser << " is out of bounds!";
  200. dst = "#!#";
  201. }
  202. else
  203. dst = (*vec)[ser];
  204. }
  205. }
  206. DLL_LINKAGE void MetaString::toString(std::string &dst) const
  207. {
  208. size_t exSt = 0, loSt = 0, nums = 0;
  209. dst.clear();
  210. for(auto & elem : message)
  211. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  212. switch(elem)
  213. {
  214. case TEXACT_STRING:
  215. dst += exactStrings[exSt++];
  216. break;
  217. case TLOCAL_STRING:
  218. {
  219. std::string hlp;
  220. getLocalString(localStrings[loSt++], hlp);
  221. dst += hlp;
  222. }
  223. break;
  224. case TNUMBER:
  225. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  226. break;
  227. case TREPLACE_ESTRING:
  228. boost::replace_first(dst, "%s", exactStrings[exSt++]);
  229. break;
  230. case TREPLACE_LSTRING:
  231. {
  232. std::string hlp;
  233. getLocalString(localStrings[loSt++], hlp);
  234. boost::replace_first(dst, "%s", hlp);
  235. }
  236. break;
  237. case TREPLACE_NUMBER:
  238. boost::replace_first(dst, "%d", boost::lexical_cast<std::string>(numbers[nums++]));
  239. break;
  240. case TREPLACE_PLUSNUMBER:
  241. boost::replace_first(dst, "%+d", '+' + boost::lexical_cast<std::string>(numbers[nums++]));
  242. break;
  243. default:
  244. logGlobal->errorStream() << "MetaString processing error!";
  245. break;
  246. }
  247. }
  248. }
  249. DLL_LINKAGE std::string MetaString::toString() const
  250. {
  251. std::string ret;
  252. toString(ret);
  253. return ret;
  254. }
  255. DLL_LINKAGE std::string MetaString::buildList () const
  256. ///used to handle loot from creature bank
  257. {
  258. size_t exSt = 0, loSt = 0, nums = 0;
  259. std::string lista;
  260. for (int i = 0; i < message.size(); ++i)
  261. {
  262. if (i > 0 && (message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING))
  263. {
  264. if (exSt == exactStrings.size() - 1)
  265. lista += VLC->generaltexth->allTexts[141]; //" and "
  266. else
  267. lista += ", ";
  268. }
  269. switch (message[i])
  270. {
  271. case TEXACT_STRING:
  272. lista += exactStrings[exSt++];
  273. break;
  274. case TLOCAL_STRING:
  275. {
  276. std::string hlp;
  277. getLocalString (localStrings[loSt++], hlp);
  278. lista += hlp;
  279. }
  280. break;
  281. case TNUMBER:
  282. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  283. break;
  284. case TREPLACE_ESTRING:
  285. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  286. break;
  287. case TREPLACE_LSTRING:
  288. {
  289. std::string hlp;
  290. getLocalString (localStrings[loSt++], hlp);
  291. lista.replace (lista.find("%s"), 2, hlp);
  292. }
  293. break;
  294. case TREPLACE_NUMBER:
  295. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  296. break;
  297. default:
  298. logGlobal->errorStream() << "MetaString processing error!";
  299. }
  300. }
  301. return lista;
  302. }
  303. void MetaString::addCreReplacement(CreatureID id, TQuantity count) //adds sing or plural name;
  304. {
  305. if (!count)
  306. addReplacement (CRE_PL_NAMES, id); //no creatures - just empty name (eg. defeat Angels)
  307. else if (count == 1)
  308. addReplacement (CRE_SING_NAMES, id);
  309. else
  310. addReplacement (CRE_PL_NAMES, id);
  311. }
  312. void MetaString::addReplacement(const CStackBasicDescriptor &stack)
  313. {
  314. assert(stack.type); //valid type
  315. addCreReplacement(stack.type->idNumber, stack.count);
  316. }
  317. static CGObjectInstance * createObject(Obj id, int subid, int3 pos, PlayerColor owner)
  318. {
  319. CGObjectInstance * nobj;
  320. switch(id)
  321. {
  322. case Obj::HERO:
  323. {
  324. auto handler = VLC->objtypeh->getHandlerFor(id, VLC->heroh->heroes[subid]->heroClass->id);
  325. nobj = handler->create(handler->getTemplates().front());
  326. break;
  327. }
  328. case Obj::TOWN:
  329. nobj = new CGTownInstance;
  330. break;
  331. default: //rest of objects
  332. nobj = new CGObjectInstance;
  333. break;
  334. }
  335. nobj->ID = id;
  336. nobj->subID = subid;
  337. nobj->pos = pos;
  338. nobj->tempOwner = owner;
  339. if (id != Obj::HERO)
  340. nobj->appearance = VLC->objtypeh->getHandlerFor(id, subid)->getTemplates().front();
  341. return nobj;
  342. }
  343. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, PlayerColor player, const CTown *town,
  344. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > &available, CRandomGenerator & rand, const CHeroClass * bannedClass /*= nullptr*/) const
  345. {
  346. CGHeroInstance *ret = nullptr;
  347. if(player>=PlayerColor::PLAYER_LIMIT)
  348. {
  349. logGlobal->errorStream() << "Cannot pick hero for " << town->faction->index << ". Wrong owner!";
  350. return nullptr;
  351. }
  352. std::vector<CGHeroInstance *> pool;
  353. if(native)
  354. {
  355. for(auto & elem : available)
  356. {
  357. if(pavailable.find(elem.first)->second & 1<<player.getNum()
  358. && elem.second->type->heroClass->faction == town->faction->index)
  359. {
  360. pool.push_back(elem.second); //get all available heroes
  361. }
  362. }
  363. if(!pool.size())
  364. {
  365. logGlobal->errorStream() << "Cannot pick native hero for " << player << ". Picking any...";
  366. return pickHeroFor(false, player, town, available, rand);
  367. }
  368. else
  369. {
  370. ret = *RandomGeneratorUtil::nextItem(pool, rand);
  371. }
  372. }
  373. else
  374. {
  375. int sum=0, r;
  376. for(auto & elem : available)
  377. {
  378. if (pavailable.find(elem.first)->second & (1<<player.getNum()) && // hero is available
  379. ( !bannedClass || elem.second->type->heroClass != bannedClass) ) // and his class is not same as other hero
  380. {
  381. pool.push_back(elem.second);
  382. sum += elem.second->type->heroClass->selectionProbability[town->faction->index]; //total weight
  383. }
  384. }
  385. if(!pool.size() || sum == 0)
  386. {
  387. logGlobal->errorStream() << "There are no heroes available for player " << player<<"!";
  388. return nullptr;
  389. }
  390. r = rand.nextInt(sum - 1);
  391. for (auto & elem : pool)
  392. {
  393. r -= elem->type->heroClass->selectionProbability[town->faction->index];
  394. if(r < 0)
  395. {
  396. ret = elem;
  397. break;
  398. }
  399. }
  400. if(!ret)
  401. ret = pool.back();
  402. }
  403. available.erase(ret->subID);
  404. return ret;
  405. }
  406. void CGameState::CrossoverHeroesList::addHeroToBothLists(CGHeroInstance * hero)
  407. {
  408. heroesFromPreviousScenario.push_back(hero);
  409. heroesFromAnyPreviousScenarios.push_back(hero);
  410. }
  411. void CGameState::CrossoverHeroesList::removeHeroFromBothLists(CGHeroInstance * hero)
  412. {
  413. heroesFromPreviousScenario -= hero;
  414. heroesFromAnyPreviousScenarios -= hero;
  415. }
  416. CGameState::CampaignHeroReplacement::CampaignHeroReplacement(CGHeroInstance * hero, ObjectInstanceID heroPlaceholderId) : hero(hero), heroPlaceholderId(heroPlaceholderId)
  417. {
  418. }
  419. int CGameState::pickNextHeroType(PlayerColor owner)
  420. {
  421. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  422. if(ps.hero >= 0 && !isUsedHero(HeroTypeID(ps.hero))) //we haven't used selected hero
  423. {
  424. return ps.hero;
  425. }
  426. return pickUnusedHeroTypeRandomly(owner);
  427. }
  428. int CGameState::pickUnusedHeroTypeRandomly(PlayerColor owner)
  429. {
  430. //list of available heroes for this faction and others
  431. std::vector<HeroTypeID> factionHeroes, otherHeroes;
  432. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  433. for(HeroTypeID hid : getUnusedAllowedHeroes())
  434. {
  435. if(VLC->heroh->heroes[hid.getNum()]->heroClass->faction == ps.castle)
  436. factionHeroes.push_back(hid);
  437. else
  438. otherHeroes.push_back(hid);
  439. }
  440. // select random hero native to "our" faction
  441. if(!factionHeroes.empty())
  442. {
  443. return RandomGeneratorUtil::nextItem(factionHeroes, rand)->getNum();
  444. }
  445. logGlobal->warnStream() << "Cannot find free hero of appropriate faction for player " << owner << " - trying to get first available...";
  446. if(!otherHeroes.empty())
  447. {
  448. return RandomGeneratorUtil::nextItem(otherHeroes, rand)->getNum();
  449. }
  450. logGlobal->errorStream() << "No free allowed heroes!";
  451. auto notAllowedHeroesButStillBetterThanCrash = getUnusedAllowedHeroes(true);
  452. if(notAllowedHeroesButStillBetterThanCrash.size())
  453. return notAllowedHeroesButStillBetterThanCrash.begin()->getNum();
  454. logGlobal->errorStream() << "No free heroes at all!";
  455. assert(0); //current code can't handle this situation
  456. return -1; // no available heroes at all
  457. }
  458. std::pair<Obj,int> CGameState::pickObject (CGObjectInstance *obj)
  459. {
  460. switch(obj->ID)
  461. {
  462. case Obj::RANDOM_ART:
  463. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(rand, CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  464. case Obj::RANDOM_TREASURE_ART:
  465. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(rand, CArtifact::ART_TREASURE));
  466. case Obj::RANDOM_MINOR_ART:
  467. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(rand, CArtifact::ART_MINOR));
  468. case Obj::RANDOM_MAJOR_ART:
  469. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(rand, CArtifact::ART_MAJOR));
  470. case Obj::RANDOM_RELIC_ART:
  471. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(rand, CArtifact::ART_RELIC));
  472. case Obj::RANDOM_HERO:
  473. return std::make_pair(Obj::HERO, pickNextHeroType(obj->tempOwner));
  474. case Obj::RANDOM_MONSTER:
  475. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(rand));
  476. case Obj::RANDOM_MONSTER_L1:
  477. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(rand, 1));
  478. case Obj::RANDOM_MONSTER_L2:
  479. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(rand, 2));
  480. case Obj::RANDOM_MONSTER_L3:
  481. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(rand, 3));
  482. case Obj::RANDOM_MONSTER_L4:
  483. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(rand, 4));
  484. case Obj::RANDOM_RESOURCE:
  485. return std::make_pair(Obj::RESOURCE,rand.nextInt(6)); //now it's OH3 style, use %8 for mithril
  486. case Obj::RANDOM_TOWN:
  487. {
  488. PlayerColor align = PlayerColor((static_cast<CGTownInstance*>(obj))->alignment);
  489. si32 f; // can be negative (for random)
  490. if(align >= PlayerColor::PLAYER_LIMIT)//same as owner / random
  491. {
  492. if(obj->tempOwner >= PlayerColor::PLAYER_LIMIT)
  493. f = -1; //random
  494. else
  495. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  496. }
  497. else
  498. {
  499. f = scenarioOps->getIthPlayersSettings(align).castle;
  500. }
  501. if(f<0)
  502. {
  503. do
  504. {
  505. f = rand.nextInt(VLC->townh->factions.size() - 1);
  506. }
  507. while (VLC->townh->factions[f]->town == nullptr); // find playable faction
  508. }
  509. return std::make_pair(Obj::TOWN,f);
  510. }
  511. case Obj::RANDOM_MONSTER_L5:
  512. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(rand, 5));
  513. case Obj::RANDOM_MONSTER_L6:
  514. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(rand, 6));
  515. case Obj::RANDOM_MONSTER_L7:
  516. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(rand, 7));
  517. case Obj::RANDOM_DWELLING:
  518. case Obj::RANDOM_DWELLING_LVL:
  519. case Obj::RANDOM_DWELLING_FACTION:
  520. {
  521. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  522. int faction;
  523. //if castle alignment available
  524. if (auto info = dynamic_cast<CCreGenAsCastleInfo*>(dwl->info))
  525. {
  526. faction = rand.nextInt(VLC->townh->factions.size() - 1);
  527. if (info->asCastle)
  528. {
  529. for(auto & elem : map->objects)
  530. {
  531. if(!elem)
  532. continue;
  533. if(elem->ID==Obj::RANDOM_TOWN
  534. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  535. {
  536. randomizeObject(elem); //we have to randomize the castle first
  537. faction = elem->subID;
  538. break;
  539. }
  540. else if(elem->ID==Obj::TOWN
  541. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  542. {
  543. faction = elem->subID;
  544. break;
  545. }
  546. }
  547. }
  548. else
  549. {
  550. while(!(info->castles[0]&(1<<faction)))
  551. {
  552. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  553. break;
  554. faction = rand.nextInt(GameConstants::F_NUMBER - 1);
  555. }
  556. }
  557. }
  558. else // castle alignment fixed
  559. faction = obj->subID;
  560. int level;
  561. //if level set to range
  562. if (auto info = dynamic_cast<CCreGenLeveledInfo*>(dwl->info))
  563. {
  564. level = rand.nextInt(info->minLevel, info->maxLevel);
  565. }
  566. else // fixed level
  567. {
  568. level = obj->subID;
  569. }
  570. delete dwl->info;
  571. dwl->info = nullptr;
  572. std::pair<Obj, int> result(Obj::NO_OBJ, -1);
  573. CreatureID cid = VLC->townh->factions[faction]->town->creatures[level][0];
  574. //golem factory is not in list of cregens but can be placed as random object
  575. static const CreatureID factoryCreatures[] = {CreatureID::STONE_GOLEM, CreatureID::IRON_GOLEM,
  576. CreatureID::GOLD_GOLEM, CreatureID::DIAMOND_GOLEM};
  577. std::vector<CreatureID> factory(factoryCreatures, factoryCreatures + ARRAY_COUNT(factoryCreatures));
  578. if (vstd::contains(factory, cid))
  579. result = std::make_pair(Obj::CREATURE_GENERATOR4, 1);
  580. //NOTE: this will pick last dwelling with this creature (Mantis #900)
  581. //check for block map equality is better but more complex solution
  582. for(auto &iter : VLC->objh->cregens)
  583. if (iter.second == cid)
  584. result = std::make_pair(Obj::CREATURE_GENERATOR1, iter.first);
  585. if (result.first == Obj::NO_OBJ)
  586. {
  587. logGlobal->errorStream() << "Error: failed to find creature for dwelling of "<< int(faction) << " of level " << int(level);
  588. result = std::make_pair(Obj::CREATURE_GENERATOR1, RandomGeneratorUtil::nextItem(VLC->objh->cregens, rand)->first);
  589. }
  590. return result;
  591. }
  592. }
  593. return std::make_pair(Obj::NO_OBJ,-1);
  594. }
  595. void CGameState::randomizeObject(CGObjectInstance *cur)
  596. {
  597. std::pair<Obj,int> ran = pickObject(cur);
  598. if(ran.first == Obj::NO_OBJ || ran.second<0) //this is not a random object, or we couldn't find anything
  599. {
  600. if(cur->ID==Obj::TOWN)
  601. cur->setType(cur->ID, cur->subID); // update def, if necessary
  602. return;
  603. }
  604. else if(ran.first==Obj::HERO)//special code for hero
  605. {
  606. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  607. cur->setType(ran.first, ran.second);
  608. map->heroesOnMap.push_back(h);
  609. return;
  610. }
  611. else if(ran.first==Obj::TOWN)//special code for town
  612. {
  613. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  614. cur->setType(ran.first, ran.second);
  615. map->towns.push_back(t);
  616. return;
  617. }
  618. cur->setType(ran.first, ran.second);
  619. }
  620. int CGameState::getDate(Date::EDateType mode) const
  621. {
  622. int temp;
  623. switch (mode)
  624. {
  625. case Date::DAY:
  626. return day;
  627. case Date::DAY_OF_WEEK: //day of week
  628. temp = (day)%7; // 1 - Monday, 7 - Sunday
  629. return temp ? temp : 7;
  630. case Date::WEEK: //current week
  631. temp = ((day-1)/7)+1;
  632. if (!(temp%4))
  633. return 4;
  634. else
  635. return (temp%4);
  636. case Date::MONTH: //current month
  637. return ((day-1)/28)+1;
  638. case Date::DAY_OF_MONTH: //day of month
  639. temp = (day)%28;
  640. if (temp)
  641. return temp;
  642. else return 28;
  643. }
  644. return 0;
  645. }
  646. CGameState::CGameState()
  647. {
  648. gs = this;
  649. mx = new boost::shared_mutex();
  650. applierGs = new CApplier<CBaseForGSApply>;
  651. registerTypesClientPacks1(*applierGs);
  652. registerTypesClientPacks2(*applierGs);
  653. //objCaller = new CObjectCallersHandler;
  654. globalEffects.setDescription("Global effects");
  655. globalEffects.setNodeType(CBonusSystemNode::GLOBAL_EFFECTS);
  656. }
  657. CGameState::~CGameState()
  658. {
  659. //delete mx;//TODO: crash on Linux (mutex must be unlocked before destruction)
  660. map.dellNull();
  661. curB.dellNull();
  662. //delete scenarioOps; //TODO: fix for loading ind delete
  663. //delete initialOpts;
  664. delete applierGs;
  665. //delete objCaller;
  666. for(auto ptr : hpool.heroesPool) // clean hero pool
  667. ptr.second.dellNull();
  668. }
  669. BattleInfo * CGameState::setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town)
  670. {
  671. const TerrainTile &t = map->getTile(tile);
  672. ETerrainType terrain = t.terType;
  673. if(t.isCoastal() && !t.isWater())
  674. terrain = ETerrainType::SAND;
  675. BFieldType terType = battleGetBattlefieldType(tile);
  676. return BattleInfo::setupBattle(tile, terrain, terType, armies, heroes, creatureBank, town);
  677. }
  678. void CGameState::init(StartInfo * si)
  679. {
  680. logGlobal->infoStream() << "\tUsing random seed: "<< si->seedToBeUsed;
  681. rand.setSeed(si->seedToBeUsed);
  682. scenarioOps = CMemorySerializer::deepCopy(*si).release();
  683. initialOpts = CMemorySerializer::deepCopy(*si).release();
  684. si = nullptr;
  685. switch(scenarioOps->mode)
  686. {
  687. case StartInfo::NEW_GAME:
  688. initNewGame();
  689. break;
  690. case StartInfo::CAMPAIGN:
  691. initCampaign();
  692. break;
  693. case StartInfo::DUEL:
  694. initDuel();
  695. return;
  696. default:
  697. logGlobal->errorStream() << "Wrong mode: " << (int)scenarioOps->mode;
  698. return;
  699. }
  700. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  701. logGlobal->infoStream() << "Map loaded!";
  702. checkMapChecksum();
  703. day = 0;
  704. logGlobal->debugStream() << "Initialization:";
  705. initPlayerStates();
  706. placeCampaignHeroes();
  707. initGrailPosition();
  708. initRandomFactionsForPlayers();
  709. randomizeMapObjects();
  710. placeStartingHeroes();
  711. initStartingResources();
  712. initHeroes();
  713. initStartingBonus();
  714. initTowns();
  715. initMapObjects();
  716. buildBonusSystemTree();
  717. initVisitingAndGarrisonedHeroes();
  718. initFogOfWar();
  719. logGlobal->debugStream() << "\tChecking objectives";
  720. map->checkForObjectives(); //needs to be run when all objects are properly placed
  721. auto seedAfterInit = rand.nextInt();
  722. logGlobal->infoStream() << "Seed after init is " << seedAfterInit << " (before was " << scenarioOps->seedToBeUsed << ")";
  723. if(scenarioOps->seedPostInit > 0)
  724. {
  725. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  726. assert(scenarioOps->seedPostInit == seedAfterInit);
  727. }
  728. else
  729. {
  730. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  731. }
  732. }
  733. void CGameState::initNewGame()
  734. {
  735. if(scenarioOps->createRandomMap())
  736. {
  737. logGlobal->infoStream() << "Create random map.";
  738. CStopWatch sw;
  739. // Gen map
  740. CMapGenerator mapGenerator;
  741. map = mapGenerator.generate(scenarioOps->mapGenOptions.get(), scenarioOps->seedToBeUsed).release();
  742. // Update starting options
  743. for(int i = 0; i < map->players.size(); ++i)
  744. {
  745. const auto & playerInfo = map->players[i];
  746. if(playerInfo.canAnyonePlay())
  747. {
  748. PlayerSettings & playerSettings = scenarioOps->playerInfos[PlayerColor(i)];
  749. playerSettings.compOnly = !playerInfo.canHumanPlay;
  750. playerSettings.team = playerInfo.team;
  751. playerSettings.castle = playerInfo.defaultCastle();
  752. if(playerSettings.playerID == PlayerSettings::PLAYER_AI && playerSettings.name.empty())
  753. {
  754. playerSettings.name = VLC->generaltexth->allTexts[468];
  755. }
  756. playerSettings.color = PlayerColor(i);
  757. }
  758. else
  759. {
  760. scenarioOps->playerInfos.erase(PlayerColor(i));
  761. }
  762. }
  763. logGlobal->infoStream() << boost::format("Generated random map in %i ms.") % sw.getDiff();
  764. }
  765. else
  766. {
  767. logGlobal->infoStream() << "Open map file: " << scenarioOps->mapname;
  768. map = CMapService::loadMap(scenarioOps->mapname).release();
  769. }
  770. }
  771. void CGameState::initCampaign()
  772. {
  773. logGlobal->infoStream() << "Open campaign map file: " << scenarioOps->campState->currentMap;
  774. auto campaign = scenarioOps->campState;
  775. assert(vstd::contains(campaign->camp->mapPieces, *scenarioOps->campState->currentMap));
  776. std::string scenarioName = scenarioOps->mapname.substr(0, scenarioOps->mapname.find('.'));
  777. boost::to_lower(scenarioName);
  778. scenarioName += ':' + boost::lexical_cast<std::string>(*campaign->currentMap);
  779. std::string & mapContent = campaign->camp->mapPieces[*campaign->currentMap];
  780. auto buffer = reinterpret_cast<const ui8 *>(mapContent.data());
  781. map = CMapService::loadMap(buffer, mapContent.size(), scenarioName).release();
  782. }
  783. void CGameState::initDuel()
  784. {
  785. DuelParameters dp;
  786. try //CLoadFile likes throwing
  787. {
  788. if(boost::algorithm::ends_with(scenarioOps->mapname, ".json"))
  789. {
  790. logGlobal->infoStream() << "Loading duel settings from JSON file: " << scenarioOps->mapname;
  791. dp = DuelParameters::fromJSON(scenarioOps->mapname);
  792. logGlobal->infoStream() << "JSON file has been successfully read!";
  793. }
  794. else
  795. {
  796. CLoadFile lf(scenarioOps->mapname);
  797. lf >> dp;
  798. }
  799. }
  800. catch(...)
  801. {
  802. logGlobal->errorStream() << "Cannot load duel settings from " << scenarioOps->mapname;
  803. throw;
  804. }
  805. const CArmedInstance *armies[2] = {nullptr};
  806. const CGHeroInstance *heroes[2] = {nullptr};
  807. CGTownInstance *town = nullptr;
  808. for(int i = 0; i < 2; i++)
  809. {
  810. CArmedInstance *obj = nullptr;
  811. if(dp.sides[i].heroId >= 0)
  812. {
  813. const DuelParameters::SideSettings &ss = dp.sides[i];
  814. auto h = new CGHeroInstance();
  815. armies[i] = heroes[i] = h;
  816. obj = h;
  817. h->subID = ss.heroId;
  818. for(int i = 0; i < ss.heroPrimSkills.size(); i++)
  819. h->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(i), ss.heroPrimSkills[i]);
  820. if(!ss.spells.empty())
  821. {
  822. h->putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(0));
  823. boost::copy(ss.spells, std::inserter(h->spells, h->spells.begin()));
  824. }
  825. for(auto &parka : ss.artifacts)
  826. {
  827. h->putArtifact(ArtifactPosition(parka.first), parka.second);
  828. }
  829. typedef const std::pair<si32, si8> &TSecSKill;
  830. for(TSecSKill secSkill : ss.heroSecSkills)
  831. h->setSecSkillLevel(SecondarySkill(secSkill.first), secSkill.second, 1);
  832. h->initHero(HeroTypeID(h->subID));
  833. obj->initObj();
  834. }
  835. else
  836. {
  837. auto c = new CGCreature();
  838. armies[i] = obj = c;
  839. //c->subID = 34;
  840. }
  841. obj->setOwner(PlayerColor(i));
  842. for(int j = 0; j < ARRAY_COUNT(dp.sides[i].stacks); j++)
  843. {
  844. CreatureID cre = dp.sides[i].stacks[j].type;
  845. TQuantity count = dp.sides[i].stacks[j].count;
  846. if(count || obj->hasStackAtSlot(SlotID(j)))
  847. obj->setCreature(SlotID(j), cre, count);
  848. }
  849. for(const DuelParameters::CusomCreature &cc : dp.creatures)
  850. {
  851. CCreature *c = VLC->creh->creatures[cc.id];
  852. if(cc.attack >= 0)
  853. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK))->val = cc.attack;
  854. if(cc.defense >= 0)
  855. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE))->val = cc.defense;
  856. if(cc.speed >= 0)
  857. c->getBonusLocalFirst(Selector::type(Bonus::STACKS_SPEED))->val = cc.speed;
  858. if(cc.HP >= 0)
  859. c->getBonusLocalFirst(Selector::type(Bonus::STACK_HEALTH))->val = cc.HP;
  860. if(cc.dmg >= 0)
  861. {
  862. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1))->val = cc.dmg;
  863. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2))->val = cc.dmg;
  864. }
  865. if(cc.shoots >= 0)
  866. c->getBonusLocalFirst(Selector::type(Bonus::SHOTS))->val = cc.shoots;
  867. }
  868. }
  869. curB = BattleInfo::setupBattle(int3(), dp.terType, dp.bfieldType, armies, heroes, false, town);
  870. curB->obstacles = dp.obstacles;
  871. curB->localInit();
  872. }
  873. void CGameState::checkMapChecksum()
  874. {
  875. logGlobal->infoStream() << "\tOur checksum for the map: "<< map->checksum;
  876. if(scenarioOps->mapfileChecksum)
  877. {
  878. logGlobal->infoStream() << "\tServer checksum for " << scenarioOps->mapname <<": "<< scenarioOps->mapfileChecksum;
  879. if(map->checksum != scenarioOps->mapfileChecksum)
  880. {
  881. logGlobal->errorStream() << "Wrong map checksum!!!";
  882. throw std::runtime_error("Wrong checksum");
  883. }
  884. }
  885. else
  886. {
  887. scenarioOps->mapfileChecksum = map->checksum;
  888. }
  889. }
  890. void CGameState::initGrailPosition()
  891. {
  892. logGlobal->debugStream() << "\tPicking grail position";
  893. //pick grail location
  894. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  895. {
  896. if(!map->grailRadious) //radius not given -> anywhere on map
  897. map->grailRadious = map->width * 2;
  898. std::vector<int3> allowedPos;
  899. static const int BORDER_WIDTH = 9; // grail must be at least 9 tiles away from border
  900. // add all not blocked tiles in range
  901. for (int i = BORDER_WIDTH; i < map->width - BORDER_WIDTH ; i++)
  902. {
  903. for (int j = BORDER_WIDTH; j < map->height - BORDER_WIDTH; j++)
  904. {
  905. for (int k = 0; k < (map->twoLevel ? 2 : 1); k++)
  906. {
  907. const TerrainTile &t = map->getTile(int3(i, j, k));
  908. if(!t.blocked
  909. && !t.visitable
  910. && t.terType != ETerrainType::WATER
  911. && t.terType != ETerrainType::ROCK
  912. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  913. allowedPos.push_back(int3(i,j,k));
  914. }
  915. }
  916. }
  917. //remove tiles with holes
  918. for(auto & elem : map->objects)
  919. if(elem && elem->ID == Obj::HOLE)
  920. allowedPos -= elem->pos;
  921. if(!allowedPos.empty())
  922. {
  923. map->grailPos = *RandomGeneratorUtil::nextItem(allowedPos, rand);
  924. }
  925. else
  926. {
  927. logGlobal->warnStream() << "Warning: Grail cannot be placed, no appropriate tile found!";
  928. }
  929. }
  930. }
  931. void CGameState::initRandomFactionsForPlayers()
  932. {
  933. logGlobal->debugStream() << "\tPicking random factions for players";
  934. for(auto & elem : scenarioOps->playerInfos)
  935. {
  936. if(elem.second.castle==-1)
  937. {
  938. auto randomID = rand.nextInt(map->players[elem.first.getNum()].allowedFactions.size() - 1);
  939. auto iter = map->players[elem.first.getNum()].allowedFactions.begin();
  940. std::advance(iter, randomID);
  941. elem.second.castle = *iter;
  942. }
  943. }
  944. }
  945. void CGameState::randomizeMapObjects()
  946. {
  947. logGlobal->debugStream() << "\tRandomizing objects";
  948. for(CGObjectInstance *obj : map->objects)
  949. {
  950. if(!obj) continue;
  951. randomizeObject(obj);
  952. obj->hoverName = VLC->objtypeh->getObjectName(obj->ID);
  953. //handle Favouring Winds - mark tiles under it
  954. if(obj->ID == Obj::FAVORABLE_WINDS)
  955. {
  956. for (int i = 0; i < obj->getWidth() ; i++)
  957. {
  958. for (int j = 0; j < obj->getHeight() ; j++)
  959. {
  960. int3 pos = obj->pos - int3(i,j,0);
  961. if(map->isInTheMap(pos)) map->getTile(pos).extTileFlags |= 128;
  962. }
  963. }
  964. }
  965. }
  966. }
  967. void CGameState::initPlayerStates()
  968. {
  969. logGlobal->debugStream() << "\tCreating player entries in gs";
  970. for(auto & elem : scenarioOps->playerInfos)
  971. {
  972. std::pair<PlayerColor, PlayerState> ins(elem.first,PlayerState());
  973. ins.second.color=ins.first;
  974. ins.second.human = elem.second.playerID;
  975. ins.second.team = map->players[ins.first.getNum()].team;
  976. teams[ins.second.team].id = ins.second.team;//init team
  977. teams[ins.second.team].players.insert(ins.first);//add player to team
  978. players.insert(ins);
  979. }
  980. }
  981. void CGameState::placeCampaignHeroes()
  982. {
  983. if (scenarioOps->campState)
  984. {
  985. // place bonus hero
  986. auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap();
  987. bool campaignGiveHero = campaignBonus && campaignBonus.get().type == CScenarioTravel::STravelBonus::HERO;
  988. if(campaignGiveHero)
  989. {
  990. auto playerColor = PlayerColor(campaignBonus->info1);
  991. auto it = scenarioOps->playerInfos.find(playerColor);
  992. if(it != scenarioOps->playerInfos.end())
  993. {
  994. auto heroTypeId = campaignBonus->info2;
  995. if(heroTypeId == 0xffff) // random bonus hero
  996. {
  997. heroTypeId = pickUnusedHeroTypeRandomly(playerColor);
  998. }
  999. placeStartingHero(playerColor, HeroTypeID(heroTypeId), map->players[playerColor.getNum()].posOfMainTown);
  1000. }
  1001. }
  1002. // replace heroes placeholders
  1003. auto crossoverHeroes = getCrossoverHeroesFromPreviousScenarios();
  1004. if(!crossoverHeroes.heroesFromAnyPreviousScenarios.empty())
  1005. {
  1006. logGlobal->debugStream() << "\tGenerate list of hero placeholders";
  1007. auto campaignHeroReplacements = generateCampaignHeroesToReplace(crossoverHeroes);
  1008. logGlobal->debugStream() << "\tPrepare crossover heroes";
  1009. prepareCrossoverHeroes(campaignHeroReplacements, scenarioOps->campState->getCurrentScenario().travelOptions);
  1010. // remove same heroes on the map which will be added through crossover heroes
  1011. // INFO: we will remove heroes because later it may be possible that the API doesn't allow having heroes
  1012. // with the same hero type id
  1013. std::vector<CGHeroInstance *> removedHeroes;
  1014. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  1015. {
  1016. auto hero = getUsedHero(HeroTypeID(campaignHeroReplacement.hero->subID));
  1017. if(hero)
  1018. {
  1019. removedHeroes.push_back(hero);
  1020. map->heroesOnMap -= hero;
  1021. map->objects[hero->id.getNum()] = nullptr;
  1022. map->removeBlockVisTiles(hero, true);
  1023. }
  1024. }
  1025. logGlobal->debugStream() << "\tReplace placeholders with heroes";
  1026. replaceHeroesPlaceholders(campaignHeroReplacements);
  1027. // remove hero placeholders on map
  1028. for(auto obj : map->objects)
  1029. {
  1030. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  1031. {
  1032. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  1033. map->removeBlockVisTiles(heroPlaceholder, true);
  1034. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  1035. delete heroPlaceholder;
  1036. }
  1037. }
  1038. // now add removed heroes again with unused type ID
  1039. for(auto hero : removedHeroes)
  1040. {
  1041. si32 heroTypeId = 0;
  1042. if(hero->ID == Obj::HERO)
  1043. {
  1044. heroTypeId = pickUnusedHeroTypeRandomly(hero->tempOwner);
  1045. }
  1046. else if(hero->ID == Obj::PRISON)
  1047. {
  1048. auto unusedHeroTypeIds = getUnusedAllowedHeroes();
  1049. if(!unusedHeroTypeIds.empty())
  1050. {
  1051. heroTypeId = (*RandomGeneratorUtil::nextItem(unusedHeroTypeIds, rand)).getNum();
  1052. }
  1053. else
  1054. {
  1055. logGlobal->errorStream() << "No free hero type ID found to replace prison.";
  1056. assert(0);
  1057. }
  1058. }
  1059. else
  1060. {
  1061. assert(0); // should not happen
  1062. }
  1063. hero->subID = heroTypeId;
  1064. hero->portrait = hero->subID;
  1065. map->getEditManager()->insertObject(hero, hero->pos);
  1066. }
  1067. }
  1068. }
  1069. }
  1070. void CGameState::placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos)
  1071. {
  1072. townPos.x += 1;
  1073. CGHeroInstance * hero = static_cast<CGHeroInstance*>(createObject(Obj::HERO, heroTypeId.getNum(), townPos, playerColor));
  1074. map->getEditManager()->insertObject(hero, townPos);
  1075. }
  1076. CGameState::CrossoverHeroesList CGameState::getCrossoverHeroesFromPreviousScenarios() const
  1077. {
  1078. CrossoverHeroesList crossoverHeroes;
  1079. auto campaignState = scenarioOps->campState;
  1080. auto bonus = campaignState->getBonusForCurrentMap();
  1081. if (bonus && bonus->type == CScenarioTravel::STravelBonus::HEROES_FROM_PREVIOUS_SCENARIO)
  1082. {
  1083. crossoverHeroes.heroesFromAnyPreviousScenarios = crossoverHeroes.heroesFromPreviousScenario = campaignState->camp->scenarios[bonus->info2].crossoverHeroes;
  1084. }
  1085. else
  1086. {
  1087. if(!campaignState->mapsConquered.empty())
  1088. {
  1089. crossoverHeroes.heroesFromPreviousScenario = campaignState->camp->scenarios[campaignState->mapsConquered.back()].crossoverHeroes;
  1090. for(auto mapNr : campaignState->mapsConquered)
  1091. {
  1092. // create a list of deleted heroes
  1093. auto & scenario = campaignState->camp->scenarios[mapNr];
  1094. auto lostCrossoverHeroes = scenario.getLostCrossoverHeroes();
  1095. // remove heroes which didn't reached the end of the scenario, but were available at the start
  1096. for(auto hero : lostCrossoverHeroes)
  1097. {
  1098. crossoverHeroes.heroesFromAnyPreviousScenarios.erase(range::remove_if(crossoverHeroes.heroesFromAnyPreviousScenarios,
  1099. CGObjectInstanceBySubIdFinder(hero)), crossoverHeroes.heroesFromAnyPreviousScenarios.end());
  1100. }
  1101. // now add heroes which completed the scenario
  1102. for(auto hero : scenario.crossoverHeroes)
  1103. {
  1104. // add new heroes and replace old heroes with newer ones
  1105. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, CGObjectInstanceBySubIdFinder(hero));
  1106. if (it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  1107. {
  1108. // replace old hero with newer one
  1109. crossoverHeroes.heroesFromAnyPreviousScenarios[it - crossoverHeroes.heroesFromAnyPreviousScenarios.begin()] = hero;
  1110. }
  1111. else
  1112. {
  1113. // add new hero
  1114. crossoverHeroes.heroesFromAnyPreviousScenarios.push_back(hero);
  1115. }
  1116. }
  1117. }
  1118. }
  1119. }
  1120. // Now we need to perform deep copies of all heroes
  1121. // The lambda below replaces pointer to a hero with a pointer to its deep copy.
  1122. auto replaceWithDeepCopy = [](CGHeroInstance *&hero)
  1123. {
  1124. // We cache map original hero => copy.
  1125. // We may be called multiple times with the same hero and should return a single copy.
  1126. static std::map<CGHeroInstance*, CGHeroInstance*> oldToCopy;
  1127. if(!oldToCopy[hero])
  1128. oldToCopy[hero] = CMemorySerializer::deepCopy(*hero).release();
  1129. hero = oldToCopy[hero];
  1130. };
  1131. range::for_each(crossoverHeroes.heroesFromAnyPreviousScenarios, replaceWithDeepCopy);
  1132. range::for_each(crossoverHeroes.heroesFromPreviousScenario, replaceWithDeepCopy);
  1133. return crossoverHeroes;
  1134. }
  1135. void CGameState::prepareCrossoverHeroes(std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions) const
  1136. {
  1137. // create heroes list for convenience iterating
  1138. std::vector<CGHeroInstance *> crossoverHeroes;
  1139. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  1140. {
  1141. crossoverHeroes.push_back(campaignHeroReplacement.hero);
  1142. }
  1143. // TODO replace magic numbers with named constants
  1144. // TODO this logic (what should be kept) should be part of CScenarioTravel and be exposed via some clean set of methods
  1145. if(!(travelOptions.whatHeroKeeps & 1))
  1146. {
  1147. //trimming experience
  1148. for(CGHeroInstance * cgh : crossoverHeroes)
  1149. {
  1150. cgh->initExp();
  1151. }
  1152. }
  1153. if(!(travelOptions.whatHeroKeeps & 2))
  1154. {
  1155. //trimming prim skills
  1156. for(CGHeroInstance * cgh : crossoverHeroes)
  1157. {
  1158. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1159. {
  1160. auto sel = Selector::type(Bonus::PRIMARY_SKILL)
  1161. .And(Selector::subtype(g))
  1162. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL));
  1163. cgh->getBonusLocalFirst(sel)->val = cgh->type->heroClass->primarySkillInitial[g];
  1164. }
  1165. }
  1166. }
  1167. if(!(travelOptions.whatHeroKeeps & 4))
  1168. {
  1169. //trimming sec skills
  1170. for(CGHeroInstance * cgh : crossoverHeroes)
  1171. {
  1172. cgh->secSkills = cgh->type->secSkillsInit;
  1173. cgh->recreateSecondarySkillsBonuses();
  1174. }
  1175. }
  1176. if(!(travelOptions.whatHeroKeeps & 8))
  1177. {
  1178. for(CGHeroInstance * cgh : crossoverHeroes)
  1179. {
  1180. // Trimming spells
  1181. cgh->spells.clear();
  1182. // Spellbook will also be removed
  1183. if (cgh->hasSpellbook())
  1184. ArtifactLocation(cgh, ArtifactPosition(ArtifactPosition::SPELLBOOK)).removeArtifact();
  1185. }
  1186. }
  1187. if(!(travelOptions.whatHeroKeeps & 16))
  1188. {
  1189. //trimming artifacts
  1190. for(CGHeroInstance * hero : crossoverHeroes)
  1191. {
  1192. size_t totalArts = GameConstants::BACKPACK_START + hero->artifactsInBackpack.size();
  1193. for (size_t i = 0; i < totalArts; i++ )
  1194. {
  1195. auto artifactPosition = ArtifactPosition(i);
  1196. if(artifactPosition == ArtifactPosition::SPELLBOOK) continue; // do not handle spellbook this way
  1197. const ArtSlotInfo *info = hero->getSlot(artifactPosition);
  1198. if(!info)
  1199. continue;
  1200. // TODO: why would there be nullptr artifacts?
  1201. const CArtifactInstance *art = info->artifact;
  1202. if(!art)
  1203. continue;
  1204. int id = art->artType->id;
  1205. assert( 8*18 > id );//number of arts that fits into h3m format
  1206. bool takeable = travelOptions.artifsKeptByHero[id / 8] & ( 1 << (id%8) );
  1207. ArtifactLocation al(hero, artifactPosition);
  1208. if(!takeable && !al.getSlot()->locked) //don't try removing locked artifacts -> it crashes #1719
  1209. al.removeArtifact();
  1210. }
  1211. }
  1212. }
  1213. //trimming creatures
  1214. for(CGHeroInstance * cgh : crossoverHeroes)
  1215. {
  1216. auto shouldSlotBeErased = [&](const std::pair<SlotID, CStackInstance *> & j) -> bool
  1217. {
  1218. CreatureID::ECreatureID crid = j.second->getCreatureID().toEnum();
  1219. return !(travelOptions.monstersKeptByHero[crid / 8] & (1 << (crid % 8)));
  1220. };
  1221. auto stacksCopy = cgh->stacks; //copy of the map, so we can iterate iover it and remove stacks
  1222. for(auto &slotPair : stacksCopy)
  1223. if(shouldSlotBeErased(slotPair))
  1224. cgh->eraseStack(slotPair.first);
  1225. }
  1226. // Removing short-term bonuses
  1227. for(CGHeroInstance * cgh : crossoverHeroes)
  1228. {
  1229. cgh->popBonuses(Selector::durationType(Bonus::ONE_DAY));
  1230. cgh->popBonuses(Selector::durationType(Bonus::ONE_WEEK));
  1231. cgh->popBonuses(Selector::durationType(Bonus::N_TURNS));
  1232. cgh->popBonuses(Selector::durationType(Bonus::N_DAYS));
  1233. cgh->popBonuses(Selector::durationType(Bonus::ONE_BATTLE));
  1234. }
  1235. }
  1236. void CGameState::placeStartingHeroes()
  1237. {
  1238. logGlobal->debugStream() << "\tGiving starting hero";
  1239. for(auto & playerSettingPair : scenarioOps->playerInfos)
  1240. {
  1241. auto playerColor = playerSettingPair.first;
  1242. auto & playerInfo = map->players[playerColor.getNum()];
  1243. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  1244. {
  1245. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  1246. if(scenarioOps->campState)
  1247. {
  1248. if(auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap())
  1249. {
  1250. if(campaignBonus->type == CScenarioTravel::STravelBonus::HERO && playerColor == PlayerColor(campaignBonus->info1)) continue;
  1251. }
  1252. }
  1253. int heroTypeId = pickNextHeroType(playerColor);
  1254. if(playerSettingPair.second.hero == -1) playerSettingPair.second.hero = heroTypeId;
  1255. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  1256. }
  1257. }
  1258. }
  1259. void CGameState::initStartingResources()
  1260. {
  1261. logGlobal->debugStream() << "\tSetting up resources";
  1262. const JsonNode config(ResourceID("config/startres.json"));
  1263. const JsonVector &vector = config["difficulty"].Vector();
  1264. const JsonNode &level = vector[scenarioOps->difficulty];
  1265. TResources startresAI(level["ai"]);
  1266. TResources startresHuman(level["human"]);
  1267. for (auto & elem : players)
  1268. {
  1269. PlayerState &p = elem.second;
  1270. if (p.human)
  1271. p.resources = startresHuman;
  1272. else
  1273. p.resources = startresAI;
  1274. }
  1275. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  1276. {
  1277. std::vector<const PlayerSettings *> ret;
  1278. for(auto it = scenarioOps->playerInfos.cbegin();
  1279. it != scenarioOps->playerInfos.cend(); ++it)
  1280. {
  1281. if(it->second.playerID != PlayerSettings::PLAYER_AI)
  1282. ret.push_back(&it->second);
  1283. }
  1284. return ret;
  1285. };
  1286. //give start resource bonus in case of campaign
  1287. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1288. {
  1289. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1290. if(chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::RESOURCE)
  1291. {
  1292. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  1293. for(const PlayerSettings *ps : people)
  1294. {
  1295. std::vector<int> res; //resources we will give
  1296. switch (chosenBonus->info1)
  1297. {
  1298. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1299. res.push_back(chosenBonus->info1);
  1300. break;
  1301. case 0xFD: //wood+ore
  1302. res.push_back(Res::WOOD); res.push_back(Res::ORE);
  1303. break;
  1304. case 0xFE: //rare
  1305. res.push_back(Res::MERCURY); res.push_back(Res::SULFUR); res.push_back(Res::CRYSTAL); res.push_back(Res::GEMS);
  1306. break;
  1307. default:
  1308. assert(0);
  1309. break;
  1310. }
  1311. //increasing resource quantity
  1312. for (auto & re : res)
  1313. {
  1314. players[ps->color].resources[re] += chosenBonus->info2;
  1315. }
  1316. }
  1317. }
  1318. }
  1319. }
  1320. void CGameState::initHeroes()
  1321. {
  1322. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1323. {
  1324. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  1325. {
  1326. logGlobal->warnStream() << "Warning - hero with uninitialized owner!";
  1327. continue;
  1328. }
  1329. hero->initHero();
  1330. getPlayer(hero->getOwner())->heroes.push_back(hero);
  1331. map->allHeroes[hero->type->ID.getNum()] = hero;
  1332. }
  1333. for(auto obj : map->objects) //prisons
  1334. {
  1335. if(obj && obj->ID == Obj::PRISON)
  1336. map->allHeroes[obj->subID] = dynamic_cast<CGHeroInstance*>(obj.get());
  1337. }
  1338. std::set<HeroTypeID> heroesToCreate = getUnusedAllowedHeroes(); //ids of heroes to be created and put into the pool
  1339. for(auto ph : map->predefinedHeroes)
  1340. {
  1341. if(!vstd::contains(heroesToCreate, HeroTypeID(ph->subID)))
  1342. continue;
  1343. ph->initHero();
  1344. hpool.heroesPool[ph->subID] = ph;
  1345. hpool.pavailable[ph->subID] = 0xff;
  1346. heroesToCreate.erase(ph->type->ID);
  1347. map->allHeroes[ph->subID] = ph;
  1348. }
  1349. for(HeroTypeID htype : heroesToCreate) //all not used allowed heroes go with default state into the pool
  1350. {
  1351. auto vhi = new CGHeroInstance();
  1352. vhi->initHero(htype);
  1353. int typeID = htype.getNum();
  1354. map->allHeroes[typeID] = vhi;
  1355. hpool.heroesPool[typeID] = vhi;
  1356. hpool.pavailable[typeID] = 0xff;
  1357. }
  1358. for(auto & elem : map->disposedHeroes)
  1359. {
  1360. hpool.pavailable[elem.heroId] = elem.players;
  1361. }
  1362. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1363. {
  1364. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1365. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->info1 != 0xFFFE) //exclude generated heroes
  1366. {
  1367. //find human player
  1368. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  1369. for (auto & elem : players)
  1370. {
  1371. if(elem.second.human)
  1372. {
  1373. humanPlayer = elem.first;
  1374. break;
  1375. }
  1376. }
  1377. assert(humanPlayer != PlayerColor::NEUTRAL);
  1378. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1379. if (chosenBonus->info1 == 0xFFFD) //most powerful
  1380. {
  1381. int maxB = -1;
  1382. for (int b=0; b<heroes.size(); ++b)
  1383. {
  1384. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1385. {
  1386. maxB = b;
  1387. }
  1388. }
  1389. if(maxB < 0)
  1390. logGlobal->warnStream() << "Warning - cannot give bonus to hero cause there are no heroes!";
  1391. else
  1392. giveCampaignBonusToHero(heroes[maxB]);
  1393. }
  1394. else //specific hero
  1395. {
  1396. for (auto & heroe : heroes)
  1397. {
  1398. if (heroe->subID == chosenBonus->info1)
  1399. {
  1400. giveCampaignBonusToHero(heroe);
  1401. break;
  1402. }
  1403. }
  1404. }
  1405. }
  1406. }
  1407. }
  1408. void CGameState::giveCampaignBonusToHero(CGHeroInstance * hero)
  1409. {
  1410. const boost::optional<CScenarioTravel::STravelBonus> & curBonus = scenarioOps->campState->getBonusForCurrentMap();
  1411. if(!curBonus)
  1412. return;
  1413. if(curBonus->isBonusForHero())
  1414. {
  1415. //apply bonus
  1416. switch (curBonus->type)
  1417. {
  1418. case CScenarioTravel::STravelBonus::SPELL:
  1419. hero->spells.insert(SpellID(curBonus->info2));
  1420. break;
  1421. case CScenarioTravel::STravelBonus::MONSTER:
  1422. {
  1423. for(int i=0; i<GameConstants::ARMY_SIZE; i++)
  1424. {
  1425. if(hero->slotEmpty(SlotID(i)))
  1426. {
  1427. hero->addToSlot(SlotID(i), CreatureID(curBonus->info2), curBonus->info3);
  1428. break;
  1429. }
  1430. }
  1431. }
  1432. break;
  1433. case CScenarioTravel::STravelBonus::ARTIFACT:
  1434. gs->giveHeroArtifact(hero, static_cast<ArtifactID>(curBonus->info2));
  1435. break;
  1436. case CScenarioTravel::STravelBonus::SPELL_SCROLL:
  1437. {
  1438. CArtifactInstance * scroll = CArtifactInstance::createScroll(SpellID(curBonus->info2).toSpell());
  1439. scroll->putAt(ArtifactLocation(hero, scroll->firstAvailableSlot(hero)));
  1440. }
  1441. break;
  1442. case CScenarioTravel::STravelBonus::PRIMARY_SKILL:
  1443. {
  1444. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus->info2);
  1445. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1446. {
  1447. int val = ptr[g];
  1448. if (val == 0)
  1449. {
  1450. continue;
  1451. }
  1452. auto bb = new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::CAMPAIGN_BONUS, val, *scenarioOps->campState->currentMap, g);
  1453. hero->addNewBonus(bb);
  1454. }
  1455. }
  1456. break;
  1457. case CScenarioTravel::STravelBonus::SECONDARY_SKILL:
  1458. hero->setSecSkillLevel(SecondarySkill(curBonus->info2), curBonus->info3, true);
  1459. break;
  1460. }
  1461. }
  1462. }
  1463. void CGameState::initFogOfWar()
  1464. {
  1465. logGlobal->debugStream() << "\tFog of war"; //FIXME: should be initialized after all bonuses are set
  1466. for(auto & elem : teams)
  1467. {
  1468. elem.second.fogOfWarMap.resize(map->width);
  1469. for(int g=0; g<map->width; ++g)
  1470. elem.second.fogOfWarMap[g].resize(map->height);
  1471. for(int g=-0; g<map->width; ++g)
  1472. for(int h=0; h<map->height; ++h)
  1473. elem.second.fogOfWarMap[g][h].resize(map->twoLevel ? 2 : 1, 0);
  1474. for(int g=0; g<map->width; ++g)
  1475. for(int h=0; h<map->height; ++h)
  1476. for(int v = 0; v < (map->twoLevel ? 2 : 1); ++v)
  1477. elem.second.fogOfWarMap[g][h][v] = 0;
  1478. for(CGObjectInstance *obj : map->objects)
  1479. {
  1480. if(!obj || !vstd::contains(elem.second.players, obj->tempOwner)) continue; //not a flagged object
  1481. std::unordered_set<int3, ShashInt3> tiles;
  1482. obj->getSightTiles(tiles);
  1483. for(int3 tile : tiles)
  1484. {
  1485. elem.second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1486. }
  1487. }
  1488. }
  1489. }
  1490. void CGameState::initStartingBonus()
  1491. {
  1492. logGlobal->debugStream() << "\tStarting bonuses";
  1493. for(auto & elem : players)
  1494. {
  1495. //starting bonus
  1496. if(scenarioOps->playerInfos[elem.first].bonus==PlayerSettings::RANDOM)
  1497. scenarioOps->playerInfos[elem.first].bonus = static_cast<PlayerSettings::Ebonus>(rand.nextInt(2));
  1498. switch(scenarioOps->playerInfos[elem.first].bonus)
  1499. {
  1500. case PlayerSettings::GOLD:
  1501. elem.second.resources[Res::GOLD] += rand.nextInt(500, 1000);
  1502. break;
  1503. case PlayerSettings::RESOURCE:
  1504. {
  1505. int res = VLC->townh->factions[scenarioOps->playerInfos[elem.first].castle]->town->primaryRes;
  1506. if(res == Res::WOOD_AND_ORE)
  1507. {
  1508. elem.second.resources[Res::WOOD] += rand.nextInt(5, 10);
  1509. elem.second.resources[Res::ORE] += rand.nextInt(5, 10);
  1510. }
  1511. else
  1512. {
  1513. elem.second.resources[res] += rand.nextInt(3, 6);
  1514. }
  1515. break;
  1516. }
  1517. case PlayerSettings::ARTIFACT:
  1518. {
  1519. if(!elem.second.heroes.size())
  1520. {
  1521. logGlobal->debugStream() << "Cannot give starting artifact - no heroes!";
  1522. break;
  1523. }
  1524. CArtifact *toGive;
  1525. toGive = VLC->arth->artifacts[VLC->arth->pickRandomArtifact(rand, CArtifact::ART_TREASURE)];
  1526. CGHeroInstance *hero = elem.second.heroes[0];
  1527. giveHeroArtifact(hero, toGive->id);
  1528. }
  1529. break;
  1530. }
  1531. }
  1532. }
  1533. void CGameState::initTowns()
  1534. {
  1535. logGlobal->debugStream() << "\tTowns";
  1536. //campaign bonuses for towns
  1537. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1538. {
  1539. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1540. if (chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::BUILDING)
  1541. {
  1542. for (int g=0; g<map->towns.size(); ++g)
  1543. {
  1544. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  1545. if (owner)
  1546. {
  1547. PlayerInfo & pi = map->players[owner->color.getNum()];
  1548. if (owner->human && //human-owned
  1549. map->towns[g]->pos == pi.posOfMainTown + int3(2, 0, 0))
  1550. {
  1551. map->towns[g]->builtBuildings.insert(
  1552. CBuildingHandler::campToERMU(chosenBonus->info1, map->towns[g]->subID, map->towns[g]->builtBuildings));
  1553. break;
  1554. }
  1555. }
  1556. }
  1557. }
  1558. }
  1559. CGTownInstance::universitySkills.clear();
  1560. for ( int i=0; i<4; i++)
  1561. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1562. for (auto & elem : map->towns)
  1563. {
  1564. CGTownInstance * vti =(elem);
  1565. if(!vti->town)
  1566. {
  1567. vti->town = VLC->townh->factions[vti->subID]->town;
  1568. }
  1569. if(vti->name.empty())
  1570. {
  1571. vti->name = *RandomGeneratorUtil::nextItem(vti->town->names, rand);
  1572. }
  1573. //init buildings
  1574. if(vstd::contains(vti->builtBuildings, BuildingID::DEFAULT)) //give standard set of buildings
  1575. {
  1576. vti->builtBuildings.erase(BuildingID::DEFAULT);
  1577. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1578. vti->builtBuildings.insert(BuildingID::TAVERN);
  1579. vti->builtBuildings.insert(BuildingID::DWELL_FIRST);
  1580. if(rand.nextInt(1) == 1)
  1581. {
  1582. vti->builtBuildings.insert(BuildingID::DWELL_LVL_2);
  1583. }
  1584. }
  1585. //#1444 - remove entries that don't have buildings defined (like some unused extra town hall buildings)
  1586. vstd::erase_if(vti->builtBuildings, [vti](BuildingID bid){
  1587. return !vti->town->buildings.count(bid) || !vti->town->buildings.at(bid); });
  1588. if (vstd::contains(vti->builtBuildings, BuildingID::SHIPYARD) && vti->shipyardStatus()==IBoatGenerator::TILE_BLOCKED)
  1589. vti->builtBuildings.erase(BuildingID::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  1590. //init hordes
  1591. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1592. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1593. {
  1594. vti->builtBuildings.erase(BuildingID(-31-i));//remove old ID
  1595. if (vti->town->hordeLvl.at(0) == i)//if town first horde is this one
  1596. {
  1597. vti->builtBuildings.insert(BuildingID::HORDE_1);//add it
  1598. if (vstd::contains(vti->builtBuildings,(BuildingID::DWELL_UP_FIRST+i)))//if we have upgraded dwelling as well
  1599. vti->builtBuildings.insert(BuildingID::HORDE_1_UPGR);//add it as well
  1600. }
  1601. if (vti->town->hordeLvl.at(1) == i)//if town second horde is this one
  1602. {
  1603. vti->builtBuildings.insert(BuildingID::HORDE_2);
  1604. if (vstd::contains(vti->builtBuildings,(BuildingID::DWELL_UP_FIRST+i)))
  1605. vti->builtBuildings.insert(BuildingID::HORDE_2_UPGR);
  1606. }
  1607. }
  1608. //Early check for #1444-like problems
  1609. for(auto building : vti->builtBuildings)
  1610. {
  1611. assert(vti->town->buildings.at(building) != nullptr);
  1612. UNUSED(building);
  1613. }
  1614. //town events
  1615. for(CCastleEvent &ev : vti->events)
  1616. {
  1617. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1618. if (vstd::contains(ev.buildings,(-31-i))) //if we have horde for this level
  1619. {
  1620. ev.buildings.erase(BuildingID(-31-i));
  1621. if (vti->town->hordeLvl.at(0) == i)
  1622. ev.buildings.insert(BuildingID::HORDE_1);
  1623. if (vti->town->hordeLvl.at(1) == i)
  1624. ev.buildings.insert(BuildingID::HORDE_2);
  1625. }
  1626. }
  1627. //init spells
  1628. logGlobal->debugStream() << "\t\tTown init spells";
  1629. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1630. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1631. {
  1632. CSpell *s = vti->obligatorySpells[z].toSpell();
  1633. vti->spells[s->level-1].push_back(s->id);
  1634. vti->possibleSpells -= s->id;
  1635. }
  1636. logGlobal->debugStream() << "\t\tTown init spells2";
  1637. while(vti->possibleSpells.size())
  1638. {
  1639. ui32 total=0;
  1640. int sel = -1;
  1641. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1642. total += vti->possibleSpells[ps].toSpell()->getProbability(vti->subID);
  1643. if (total == 0) // remaining spells have 0 probability
  1644. break;
  1645. auto r = rand.nextInt(total - 1);
  1646. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1647. {
  1648. r -= vti->possibleSpells[ps].toSpell()->getProbability(vti->subID);
  1649. if(r<0)
  1650. {
  1651. sel = ps;
  1652. break;
  1653. }
  1654. }
  1655. if(sel<0)
  1656. sel=0;
  1657. CSpell *s = vti->possibleSpells[sel].toSpell();
  1658. vti->spells[s->level-1].push_back(s->id);
  1659. vti->possibleSpells -= s->id;
  1660. }
  1661. vti->possibleSpells.clear();
  1662. if(vti->getOwner() != PlayerColor::NEUTRAL)
  1663. getPlayer(vti->getOwner())->towns.push_back(vti);
  1664. logGlobal->debugStream() << "\t\tTown init spells3";
  1665. }
  1666. }
  1667. void CGameState::initMapObjects()
  1668. {
  1669. logGlobal->debugStream() << "\tObject initialization";
  1670. // objCaller->preInit();
  1671. for(CGObjectInstance *obj : map->objects)
  1672. {
  1673. if(obj)
  1674. obj->initObj();
  1675. }
  1676. for(CGObjectInstance *obj : map->objects)
  1677. {
  1678. if(!obj)
  1679. continue;
  1680. switch (obj->ID)
  1681. {
  1682. case Obj::QUEST_GUARD:
  1683. case Obj::SEER_HUT:
  1684. {
  1685. auto q = static_cast<CGSeerHut*>(obj);
  1686. assert (q);
  1687. q->setObjToKill();
  1688. }
  1689. }
  1690. }
  1691. CGTeleport::postInit(); //pairing subterranean gates
  1692. }
  1693. void CGameState::initVisitingAndGarrisonedHeroes()
  1694. {
  1695. for(auto k=players.begin(); k!=players.end(); ++k)
  1696. {
  1697. if(k->first==PlayerColor::NEUTRAL)
  1698. continue;
  1699. //init visiting and garrisoned heroes
  1700. for(CGHeroInstance *h : k->second.heroes)
  1701. {
  1702. for(CGTownInstance *t : k->second.towns)
  1703. {
  1704. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1705. if(vistile == h->pos || h->pos==t->pos)
  1706. {
  1707. t->setVisitingHero(h);
  1708. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1709. {
  1710. map->removeBlockVisTiles(h);
  1711. h->pos.x -= 1;
  1712. map->addBlockVisTiles(h);
  1713. }
  1714. break;
  1715. }
  1716. }
  1717. }
  1718. }
  1719. }
  1720. BFieldType CGameState::battleGetBattlefieldType(int3 tile)
  1721. {
  1722. if(tile==int3() && curB)
  1723. tile = curB->tile;
  1724. else if(tile==int3() && !curB)
  1725. return BFieldType::NONE;
  1726. const TerrainTile &t = map->getTile(tile);
  1727. //fight in mine -> subterranean
  1728. if(dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  1729. return BFieldType::SUBTERRANEAN;
  1730. for(auto &obj : map->objects)
  1731. {
  1732. //look only for objects covering given tile
  1733. if( !obj || obj->pos.z != tile.z
  1734. || !obj->coveringAt(tile.x - obj->pos.x, tile.y - obj->pos.y))
  1735. continue;
  1736. switch(obj->ID)
  1737. {
  1738. case Obj::CLOVER_FIELD:
  1739. return BFieldType::CLOVER_FIELD;
  1740. case Obj::CURSED_GROUND1: case Obj::CURSED_GROUND2:
  1741. return BFieldType::CURSED_GROUND;
  1742. case Obj::EVIL_FOG:
  1743. return BFieldType::EVIL_FOG;
  1744. case Obj::FAVORABLE_WINDS:
  1745. return BFieldType::FAVOURABLE_WINDS;
  1746. case Obj::FIERY_FIELDS:
  1747. return BFieldType::FIERY_FIELDS;
  1748. case Obj::HOLY_GROUNDS:
  1749. return BFieldType::HOLY_GROUND;
  1750. case Obj::LUCID_POOLS:
  1751. return BFieldType::LUCID_POOLS;
  1752. case Obj::MAGIC_CLOUDS:
  1753. return BFieldType::MAGIC_CLOUDS;
  1754. case Obj::MAGIC_PLAINS1: case Obj::MAGIC_PLAINS2:
  1755. return BFieldType::MAGIC_PLAINS;
  1756. case Obj::ROCKLANDS:
  1757. return BFieldType::ROCKLANDS;
  1758. }
  1759. }
  1760. if(!t.isWater() && t.isCoastal())
  1761. return BFieldType::SAND_SHORE;
  1762. switch(t.terType)
  1763. {
  1764. case ETerrainType::DIRT:
  1765. return BFieldType(rand.nextInt(3, 5));
  1766. case ETerrainType::SAND:
  1767. return BFieldType::SAND_MESAS; //TODO: coast support
  1768. case ETerrainType::GRASS:
  1769. return BFieldType(rand.nextInt(6, 7));
  1770. case ETerrainType::SNOW:
  1771. return BFieldType(rand.nextInt(10, 11));
  1772. case ETerrainType::SWAMP:
  1773. return BFieldType::SWAMP_TREES;
  1774. case ETerrainType::ROUGH:
  1775. return BFieldType::ROUGH;
  1776. case ETerrainType::SUBTERRANEAN:
  1777. return BFieldType::SUBTERRANEAN;
  1778. case ETerrainType::LAVA:
  1779. return BFieldType::LAVA;
  1780. case ETerrainType::WATER:
  1781. return BFieldType::SHIP;
  1782. case ETerrainType::ROCK:
  1783. return BFieldType::ROCKLANDS;
  1784. default:
  1785. return BFieldType::NONE;
  1786. }
  1787. }
  1788. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1789. {
  1790. UpgradeInfo ret;
  1791. const CCreature *base = stack.type;
  1792. const CGHeroInstance *h = stack.armyObj->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(stack.armyObj) : nullptr;
  1793. const CGTownInstance *t = nullptr;
  1794. if(stack.armyObj->ID == Obj::TOWN)
  1795. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1796. else if(h)
  1797. { //hero specialty
  1798. TBonusListPtr lista = h->getBonuses(Selector::typeSubtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1799. for(const Bonus *it : *lista)
  1800. {
  1801. auto nid = CreatureID(it->additionalInfo);
  1802. if (nid != base->idNumber) //in very specific case the upgrade is available by default (?)
  1803. {
  1804. ret.newID.push_back(nid);
  1805. ret.cost.push_back(VLC->creh->creatures[nid]->cost - base->cost);
  1806. }
  1807. }
  1808. t = h->visitedTown;
  1809. }
  1810. if(t)
  1811. {
  1812. for(const CGTownInstance::TCreaturesSet::value_type & dwelling : t->creatures)
  1813. {
  1814. if (vstd::contains(dwelling.second, base->idNumber)) //Dwelling with our creature
  1815. {
  1816. for(auto upgrID : dwelling.second)
  1817. {
  1818. if(vstd::contains(base->upgrades, upgrID)) //possible upgrade
  1819. {
  1820. ret.newID.push_back(upgrID);
  1821. ret.cost.push_back(VLC->creh->creatures[upgrID]->cost - base->cost);
  1822. }
  1823. }
  1824. }
  1825. }
  1826. }
  1827. //hero is visiting Hill Fort
  1828. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == Obj::HILL_FORT)
  1829. {
  1830. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1831. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1832. for(auto nid : base->upgrades)
  1833. {
  1834. ret.newID.push_back(nid);
  1835. ret.cost.push_back((VLC->creh->creatures[nid]->cost - base->cost) * costModifier / 100);
  1836. }
  1837. }
  1838. if(ret.newID.size())
  1839. ret.oldID = base->idNumber;
  1840. for (Res::ResourceSet &cost : ret.cost)
  1841. cost.positive(); //upgrade cost can't be negative, ignore missing resources
  1842. return ret;
  1843. }
  1844. PlayerRelations::PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 )
  1845. {
  1846. if ( color1 == color2 )
  1847. return PlayerRelations::SAME_PLAYER;
  1848. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  1849. return PlayerRelations::ENEMIES;
  1850. const TeamState * ts = getPlayerTeam(color1);
  1851. if (ts && vstd::contains(ts->players, color2))
  1852. return PlayerRelations::ALLIES;
  1853. return PlayerRelations::ENEMIES;
  1854. }
  1855. void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing)
  1856. {
  1857. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1858. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1859. //vec.reserve(8); //optimization
  1860. for (auto & dir : dirs)
  1861. {
  1862. const int3 hlp = tile + dir;
  1863. if(!map->isInTheMap(hlp))
  1864. continue;
  1865. const TerrainTile &hlpt = map->getTile(hlp);
  1866. // //we cannot visit things from blocked tiles
  1867. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1868. // {
  1869. // continue;
  1870. // }
  1871. if(srct.terType == ETerrainType::WATER && limitCoastSailing && hlpt.terType == ETerrainType::WATER && dir.x && dir.y) //diagonal move through water
  1872. {
  1873. int3 hlp1 = tile,
  1874. hlp2 = tile;
  1875. hlp1.x += dir.x;
  1876. hlp2.y += dir.y;
  1877. if(map->getTile(hlp1).terType != ETerrainType::WATER || map->getTile(hlp2).terType != ETerrainType::WATER)
  1878. continue;
  1879. }
  1880. if((indeterminate(onLand) || onLand == (hlpt.terType!=ETerrainType::WATER) )
  1881. && hlpt.terType != ETerrainType::ROCK)
  1882. {
  1883. vec.push_back(hlp);
  1884. }
  1885. }
  1886. }
  1887. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, bool flying, int remainingMovePoints, bool checkLast)
  1888. {
  1889. if(src == dest) //same tile
  1890. return 0;
  1891. TerrainTile &s = map->getTile(src),
  1892. &d = map->getTile(dest);
  1893. //get basic cost
  1894. int ret = h->getTileCost(d,s);
  1895. if(d.blocked && flying)
  1896. {
  1897. bool freeFlying = h->getBonusesCount(Selector::typeSubtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1898. if(!freeFlying)
  1899. {
  1900. ret *= 1.4; //40% penalty for movement over blocked tile
  1901. }
  1902. }
  1903. else if (d.terType == ETerrainType::WATER)
  1904. {
  1905. if(h->boat && s.hasFavourableWinds() && d.hasFavourableWinds()) //Favourable Winds
  1906. ret *= 0.666;
  1907. else if (!h->boat && h->getBonusesCount(Selector::typeSubtype(Bonus::WATER_WALKING, 1)) > 0)
  1908. ret *= 1.4; //40% penalty for water walking
  1909. }
  1910. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1911. {
  1912. int old = ret;
  1913. ret *= 1.414213;
  1914. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1915. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1916. {
  1917. return remainingMovePoints;
  1918. }
  1919. }
  1920. int left = remainingMovePoints-ret;
  1921. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1922. {
  1923. std::vector<int3> vec;
  1924. vec.reserve(8); //optimization
  1925. getNeighbours(d, dest, vec, s.terType != ETerrainType::WATER, true);
  1926. for(auto & elem : vec)
  1927. {
  1928. int fcost = getMovementCost(h,dest, elem, flying, left, false);
  1929. if(fcost <= left)
  1930. {
  1931. return ret;
  1932. }
  1933. }
  1934. ret = remainingMovePoints;
  1935. }
  1936. return ret;
  1937. }
  1938. void CGameState::apply(CPack *pack)
  1939. {
  1940. ui16 typ = typeList.getTypeID(pack);
  1941. applierGs->apps[typ]->applyOnGS(this,pack);
  1942. }
  1943. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1944. {
  1945. CPathfinder pathfinder(out, this, hero);
  1946. pathfinder.calculatePaths(src, movement);
  1947. }
  1948. /**
  1949. * Tells if the tile is guarded by a monster as well as the position
  1950. * of the monster that will attack on it.
  1951. *
  1952. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1953. * the monster guarding the tile.
  1954. */
  1955. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1956. {
  1957. std::vector<CGObjectInstance*> guards;
  1958. const int3 originalPos = pos;
  1959. if (!map->isInTheMap(pos))
  1960. return guards;
  1961. const TerrainTile &posTile = map->getTile(pos);
  1962. if (posTile.visitable)
  1963. {
  1964. for (CGObjectInstance* obj : posTile.visitableObjects)
  1965. {
  1966. if(obj->blockVisit)
  1967. {
  1968. if (obj->ID == Obj::MONSTER) // Monster
  1969. guards.push_back(obj);
  1970. }
  1971. }
  1972. }
  1973. pos -= int3(1, 1, 0); // Start with top left.
  1974. for (int dx = 0; dx < 3; dx++)
  1975. {
  1976. for (int dy = 0; dy < 3; dy++)
  1977. {
  1978. if (map->isInTheMap(pos))
  1979. {
  1980. const auto & tile = map->getTile(pos);
  1981. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1982. {
  1983. for (CGObjectInstance* obj : tile.visitableObjects)
  1984. {
  1985. if (obj->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1986. {
  1987. guards.push_back(obj);
  1988. }
  1989. }
  1990. }
  1991. }
  1992. pos.y++;
  1993. }
  1994. pos.y -= 3;
  1995. pos.x++;
  1996. }
  1997. return guards;
  1998. }
  1999. int3 CGameState::guardingCreaturePosition (int3 pos) const
  2000. {
  2001. return gs->map->guardingCreaturePositions[pos.x][pos.y][pos.z];
  2002. }
  2003. bool CGameState::isVisible(int3 pos, PlayerColor player)
  2004. {
  2005. if(player == PlayerColor::NEUTRAL)
  2006. return false;
  2007. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  2008. }
  2009. bool CGameState::isVisible( const CGObjectInstance *obj, boost::optional<PlayerColor> player )
  2010. {
  2011. if(!player)
  2012. return true;
  2013. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  2014. return false;
  2015. //object is visible when at least one blocked tile is visible
  2016. for(int fy=0; fy < obj->getHeight(); ++fy)
  2017. {
  2018. for(int fx=0; fx < obj->getWidth(); ++fx)
  2019. {
  2020. int3 pos = obj->pos + int3(-fx, -fy, 0);
  2021. if ( map->isInTheMap(pos) &&
  2022. obj->coveringAt(pos.x, pos.y) &&
  2023. isVisible(pos, *player))
  2024. return true;
  2025. }
  2026. }
  2027. return false;
  2028. }
  2029. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  2030. {
  2031. const TerrainTile * pom = &map->getTile(dst);
  2032. return map->checkForVisitableDir(src, pom, dst);
  2033. }
  2034. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(PlayerColor player) const
  2035. {
  2036. const std::string & messageWonSelf = VLC->generaltexth->allTexts[659];
  2037. const std::string & messageWonOther = VLC->generaltexth->allTexts[5];
  2038. const std::string & messageLostSelf = VLC->generaltexth->allTexts[7];
  2039. const std::string & messageLostOther = VLC->generaltexth->allTexts[8];
  2040. auto evaluateEvent = [=](const EventCondition & condition)
  2041. {
  2042. return this->checkForVictory(player, condition);
  2043. };
  2044. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  2045. //cheater or tester, but has entered the code...
  2046. if (p->enteredWinningCheatCode)
  2047. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  2048. if (p->enteredLosingCheatCode)
  2049. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  2050. for (const TriggeredEvent & event : map->triggeredEvents)
  2051. {
  2052. if ((event.trigger.test(evaluateEvent)))
  2053. {
  2054. if (event.effect.type == EventEffect::VICTORY)
  2055. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  2056. if (event.effect.type == EventEffect::DEFEAT)
  2057. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  2058. }
  2059. }
  2060. if (checkForStandardLoss(player))
  2061. {
  2062. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  2063. }
  2064. return EVictoryLossCheckResult();
  2065. }
  2066. bool CGameState::checkForVictory( PlayerColor player, const EventCondition & condition ) const
  2067. {
  2068. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  2069. switch (condition.condition)
  2070. {
  2071. case EventCondition::STANDARD_WIN:
  2072. {
  2073. return player == checkForStandardWin();
  2074. }
  2075. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  2076. {
  2077. for(auto & elem : p->heroes)
  2078. if(elem->hasArt(condition.objectType))
  2079. return true;
  2080. return false;
  2081. }
  2082. case EventCondition::HAVE_CREATURES:
  2083. {
  2084. //check if in players armies there is enough creatures
  2085. int total = 0; //creature counter
  2086. for(size_t i = 0; i < map->objects.size(); i++)
  2087. {
  2088. const CArmedInstance *ai = nullptr;
  2089. if(map->objects[i]
  2090. && map->objects[i]->tempOwner == player //object controlled by player
  2091. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  2092. {
  2093. for(auto & elem : ai->Slots()) //iterate through army
  2094. if(elem.second->type->idNumber == condition.objectType) //it's searched creature
  2095. total += elem.second->count;
  2096. }
  2097. }
  2098. return total >= condition.value;
  2099. }
  2100. case EventCondition::HAVE_RESOURCES:
  2101. {
  2102. return p->resources[condition.objectType] >= condition.value;
  2103. }
  2104. case EventCondition::HAVE_BUILDING:
  2105. {
  2106. if (condition.object) // specific town
  2107. {
  2108. const CGTownInstance *t = static_cast<const CGTownInstance *>(condition.object);
  2109. return (t->tempOwner == player && t->hasBuilt(BuildingID(condition.objectType)));
  2110. }
  2111. else // any town
  2112. {
  2113. for (const CGTownInstance * t : p->towns)
  2114. {
  2115. if (t->hasBuilt(BuildingID(condition.objectType)))
  2116. return true;
  2117. }
  2118. return false;
  2119. }
  2120. }
  2121. case EventCondition::DESTROY:
  2122. {
  2123. if (condition.object) // mode A - destroy specific object of this type
  2124. {
  2125. if (auto hero = dynamic_cast<const CGHeroInstance*>(condition.object))
  2126. return boost::range::find(gs->map->heroesOnMap, hero) == gs->map->heroesOnMap.end();
  2127. else
  2128. return getObj(condition.object->id) == nullptr;
  2129. }
  2130. else
  2131. {
  2132. for(auto & elem : map->objects) // mode B - destroy all objects of this type
  2133. {
  2134. if(elem && elem->ID == condition.objectType)
  2135. return false;
  2136. }
  2137. return true;
  2138. }
  2139. }
  2140. case EventCondition::CONTROL:
  2141. {
  2142. // list of players that need to control object to fulfull condition
  2143. // NOTE: cgameinfocallback specified explicitly in order to get const version
  2144. auto & team = CGameInfoCallback::getPlayerTeam(player)->players;
  2145. if (condition.object) // mode A - flag one specific object, like town
  2146. {
  2147. return team.count(condition.object->tempOwner) != 0;
  2148. }
  2149. else
  2150. {
  2151. for(auto & elem : map->objects) // mode B - flag all objects of this type
  2152. {
  2153. //check not flagged objs
  2154. if ( elem && elem->ID == condition.objectType && team.count(elem->tempOwner) == 0 )
  2155. return false;
  2156. }
  2157. return true;
  2158. }
  2159. }
  2160. case EventCondition::TRANSPORT:
  2161. {
  2162. const CGTownInstance *t = static_cast<const CGTownInstance *>(condition.object);
  2163. if((t->visitingHero && t->visitingHero->hasArt(condition.objectType))
  2164. || (t->garrisonHero && t->garrisonHero->hasArt(condition.objectType)))
  2165. {
  2166. return true;
  2167. }
  2168. return false;
  2169. }
  2170. case EventCondition::DAYS_PASSED:
  2171. {
  2172. return gs->day > condition.value;
  2173. }
  2174. case EventCondition::IS_HUMAN:
  2175. {
  2176. return p->human ? condition.value == 1 : condition.value == 0;
  2177. }
  2178. case EventCondition::DAYS_WITHOUT_TOWN:
  2179. {
  2180. if (p->daysWithoutCastle)
  2181. return p->daysWithoutCastle.get() >= condition.value;
  2182. else
  2183. return false;
  2184. }
  2185. case EventCondition::CONST_VALUE:
  2186. {
  2187. return condition.value; // just convert to bool
  2188. }
  2189. }
  2190. assert(0);
  2191. return false;
  2192. }
  2193. PlayerColor CGameState::checkForStandardWin() const
  2194. {
  2195. //std victory condition is:
  2196. //all enemies lost
  2197. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  2198. TeamID winnerTeam = TeamID::NO_TEAM;
  2199. for(auto & elem : players)
  2200. {
  2201. if(elem.second.status == EPlayerStatus::INGAME && elem.first < PlayerColor::PLAYER_LIMIT)
  2202. {
  2203. if(supposedWinner == PlayerColor::NEUTRAL)
  2204. {
  2205. //first player remaining ingame - candidate for victory
  2206. supposedWinner = elem.second.color;
  2207. winnerTeam = elem.second.team;
  2208. }
  2209. else if(winnerTeam != elem.second.team)
  2210. {
  2211. //current candidate has enemy remaining in game -> no vicotry
  2212. return PlayerColor::NEUTRAL;
  2213. }
  2214. }
  2215. }
  2216. return supposedWinner;
  2217. }
  2218. bool CGameState::checkForStandardLoss( PlayerColor player ) const
  2219. {
  2220. //std loss condition is: player lost all towns and heroes
  2221. const PlayerState &p = *CGameInfoCallback::getPlayer(player);
  2222. return !p.heroes.size() && !p.towns.size();
  2223. }
  2224. struct statsHLP
  2225. {
  2226. typedef std::pair< PlayerColor, si64 > TStat;
  2227. //converts [<player's color, value>] to vec[place] -> platers
  2228. static std::vector< std::vector< PlayerColor > > getRank( std::vector<TStat> stats )
  2229. {
  2230. std::sort(stats.begin(), stats.end(), statsHLP());
  2231. //put first element
  2232. std::vector< std::vector<PlayerColor> > ret;
  2233. std::vector<PlayerColor> tmp;
  2234. tmp.push_back( stats[0].first );
  2235. ret.push_back( tmp );
  2236. //the rest of elements
  2237. for(int g=1; g<stats.size(); ++g)
  2238. {
  2239. if(stats[g].second == stats[g-1].second)
  2240. {
  2241. (ret.end()-1)->push_back( stats[g].first );
  2242. }
  2243. else
  2244. {
  2245. //create next occupied rank
  2246. std::vector<PlayerColor> tmp;
  2247. tmp.push_back(stats[g].first);
  2248. ret.push_back(tmp);
  2249. }
  2250. }
  2251. return ret;
  2252. }
  2253. bool operator()(const TStat & a, const TStat & b) const
  2254. {
  2255. return a.second > b.second;
  2256. }
  2257. static const CGHeroInstance * findBestHero(CGameState * gs, PlayerColor color)
  2258. {
  2259. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2260. if(!h.size())
  2261. return nullptr;
  2262. //best hero will be that with highest exp
  2263. int best = 0;
  2264. for(int b=1; b<h.size(); ++b)
  2265. {
  2266. if(h[b]->exp > h[best]->exp)
  2267. {
  2268. best = b;
  2269. }
  2270. }
  2271. return h[best];
  2272. }
  2273. //calculates total number of artifacts that belong to given player
  2274. static int getNumberOfArts(const PlayerState * ps)
  2275. {
  2276. int ret = 0;
  2277. for(auto h : ps->heroes)
  2278. {
  2279. ret += h->artifactsInBackpack.size() + h->artifactsWorn.size();
  2280. }
  2281. return ret;
  2282. }
  2283. // get total strength of player army
  2284. static si64 getArmyStrength(const PlayerState * ps)
  2285. {
  2286. si64 str = 0;
  2287. for(auto h : ps->heroes)
  2288. {
  2289. if(!h->inTownGarrison) //original h3 behavior
  2290. str += h->getArmyStrength();
  2291. }
  2292. return str;
  2293. }
  2294. };
  2295. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2296. {
  2297. auto playerInactive = [&](PlayerColor color)
  2298. {
  2299. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  2300. };
  2301. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2302. { \
  2303. std::vector< std::pair< PlayerColor, si64 > > stats; \
  2304. for(auto g = players.begin(); g != players.end(); ++g) \
  2305. { \
  2306. if(playerInactive(g->second.color)) \
  2307. continue; \
  2308. std::pair< PlayerColor, si64 > stat; \
  2309. stat.first = g->second.color; \
  2310. stat.second = VAL_GETTER; \
  2311. stats.push_back(stat); \
  2312. } \
  2313. tgi.FIELD = statsHLP::getRank(stats); \
  2314. }
  2315. for(auto & elem : players)
  2316. {
  2317. if(!playerInactive(elem.second.color))
  2318. tgi.playerColors.push_back(elem.second.color);
  2319. }
  2320. if(level >= 1) //num of towns & num of heroes
  2321. {
  2322. //num of towns
  2323. FILL_FIELD(numOfTowns, g->second.towns.size())
  2324. //num of heroes
  2325. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2326. //best hero's portrait
  2327. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2328. {
  2329. if(playerInactive(g->second.color))
  2330. continue;
  2331. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2332. InfoAboutHero iah;
  2333. iah.initFromHero(best, level >= 8);
  2334. iah.army.clear();
  2335. tgi.colorToBestHero[g->second.color] = iah;
  2336. }
  2337. }
  2338. if(level >= 2) //gold
  2339. {
  2340. FILL_FIELD(gold, g->second.resources[Res::GOLD])
  2341. }
  2342. if(level >= 2) //wood & ore
  2343. {
  2344. FILL_FIELD(woodOre, g->second.resources[Res::WOOD] + g->second.resources[Res::ORE])
  2345. }
  2346. if(level >= 3) //mercury, sulfur, crystal, gems
  2347. {
  2348. FILL_FIELD(mercSulfCrystGems, g->second.resources[Res::MERCURY] + g->second.resources[Res::SULFUR] + g->second.resources[Res::CRYSTAL] + g->second.resources[Res::GEMS])
  2349. }
  2350. if(level >= 4) //obelisks found
  2351. {
  2352. FILL_FIELD(obelisks, CGObelisk::visited[gs->getPlayerTeam(g->second.color)->id])
  2353. }
  2354. if(level >= 5) //artifacts
  2355. {
  2356. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2357. }
  2358. if(level >= 6) //army strength
  2359. {
  2360. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  2361. }
  2362. if(level >= 7) //income
  2363. {
  2364. //TODO:obtainPlayersStats - income
  2365. }
  2366. if(level >= 8) //best hero's stats
  2367. {
  2368. //already set in lvl 1 handling
  2369. }
  2370. if(level >= 9) //personality
  2371. {
  2372. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2373. {
  2374. if(playerInactive(g->second.color)) //do nothing for neutral player
  2375. continue;
  2376. if(g->second.human)
  2377. {
  2378. tgi.personality[g->second.color] = EAiTactic::NONE;
  2379. }
  2380. else //AI
  2381. {
  2382. tgi.personality[g->second.color] = map->players[g->second.color.getNum()].aiTactic;
  2383. }
  2384. }
  2385. }
  2386. if(level >= 10) //best creature
  2387. {
  2388. //best creatures belonging to player (highest AI value)
  2389. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2390. {
  2391. if(playerInactive(g->second.color)) //do nothing for neutral player
  2392. continue;
  2393. int bestCre = -1; //best creature's ID
  2394. for(auto & elem : g->second.heroes)
  2395. {
  2396. for(auto it = elem->Slots().begin(); it != elem->Slots().end(); ++it)
  2397. {
  2398. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  2399. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  2400. {
  2401. bestCre = toCmp;
  2402. }
  2403. }
  2404. }
  2405. tgi.bestCreature[g->second.color] = bestCre;
  2406. }
  2407. }
  2408. #undef FILL_FIELD
  2409. }
  2410. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2411. {
  2412. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2413. for ( auto i = players.cbegin() ; i != players.cend();i++)
  2414. for(auto j = i->second.availableHeroes.cbegin(); j != i->second.availableHeroes.cend(); j++)
  2415. if(*j)
  2416. pool.erase((**j).subID);
  2417. return pool;
  2418. }
  2419. void CGameState::buildBonusSystemTree()
  2420. {
  2421. buildGlobalTeamPlayerTree();
  2422. attachArmedObjects();
  2423. for(CGTownInstance *t : map->towns)
  2424. {
  2425. t->deserializationFix();
  2426. }
  2427. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2428. // are provided on initializing / deserializing
  2429. }
  2430. void CGameState::deserializationFix()
  2431. {
  2432. buildGlobalTeamPlayerTree();
  2433. attachArmedObjects();
  2434. }
  2435. void CGameState::buildGlobalTeamPlayerTree()
  2436. {
  2437. for(auto k=teams.begin(); k!=teams.end(); ++k)
  2438. {
  2439. TeamState *t = &k->second;
  2440. t->attachTo(&globalEffects);
  2441. for(PlayerColor teamMember : k->second.players)
  2442. {
  2443. PlayerState *p = getPlayer(teamMember);
  2444. assert(p);
  2445. p->attachTo(t);
  2446. }
  2447. }
  2448. }
  2449. void CGameState::attachArmedObjects()
  2450. {
  2451. for(CGObjectInstance *obj : map->objects)
  2452. {
  2453. if(CArmedInstance *armed = dynamic_cast<CArmedInstance*>(obj))
  2454. armed->whatShouldBeAttached()->attachTo(armed->whereShouldBeAttached(this));
  2455. }
  2456. }
  2457. void CGameState::giveHeroArtifact(CGHeroInstance *h, ArtifactID aid)
  2458. {
  2459. CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  2460. CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  2461. map->addNewArtifactInstance(ai);
  2462. ai->putAt(ArtifactLocation(h, ai->firstAvailableSlot(h)));
  2463. }
  2464. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed /*= false*/) const
  2465. {
  2466. std::set<HeroTypeID> ret;
  2467. for(int i = 0; i < map->allowedHeroes.size(); i++)
  2468. if(map->allowedHeroes[i] || alsoIncludeNotAllowed)
  2469. ret.insert(HeroTypeID(i));
  2470. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2471. {
  2472. if(hero->type)
  2473. ret -= hero->type->ID;
  2474. else
  2475. ret -= HeroTypeID(hero->subID);
  2476. }
  2477. for(auto obj : map->objects) //prisons
  2478. if(obj && obj->ID == Obj::PRISON)
  2479. ret -= HeroTypeID(obj->subID);
  2480. return ret;
  2481. }
  2482. std::vector<CGameState::CampaignHeroReplacement> CGameState::generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes)
  2483. {
  2484. std::vector<CampaignHeroReplacement> campaignHeroReplacements;
  2485. //selecting heroes by type
  2486. for(auto obj : map->objects)
  2487. {
  2488. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2489. {
  2490. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2491. if(heroPlaceholder->subID != 0xFF) //select by type
  2492. {
  2493. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [heroPlaceholder](CGHeroInstance * hero)
  2494. {
  2495. return hero->subID == heroPlaceholder->subID;
  2496. });
  2497. if(it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  2498. {
  2499. auto hero = *it;
  2500. crossoverHeroes.removeHeroFromBothLists(hero);
  2501. campaignHeroReplacements.push_back(CampaignHeroReplacement(hero, heroPlaceholder->id));
  2502. }
  2503. }
  2504. }
  2505. }
  2506. //selecting heroes by power
  2507. range::sort(crossoverHeroes.heroesFromPreviousScenario, [](const CGHeroInstance * a, const CGHeroInstance * b)
  2508. {
  2509. return a->getHeroStrength() > b->getHeroStrength();
  2510. }); //sort, descending strength
  2511. // sort hero placeholders descending power
  2512. std::vector<CGHeroPlaceholder *> heroPlaceholders;
  2513. for(auto obj : map->objects)
  2514. {
  2515. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2516. {
  2517. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2518. if(heroPlaceholder->subID == 0xFF) //select by power
  2519. {
  2520. heroPlaceholders.push_back(heroPlaceholder);
  2521. }
  2522. }
  2523. }
  2524. range::sort(heroPlaceholders, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  2525. {
  2526. return a->power > b->power;
  2527. });
  2528. for(int i = 0; i < heroPlaceholders.size(); ++i)
  2529. {
  2530. auto heroPlaceholder = heroPlaceholders[i];
  2531. if(crossoverHeroes.heroesFromPreviousScenario.size() > i)
  2532. {
  2533. campaignHeroReplacements.push_back(CampaignHeroReplacement(crossoverHeroes.heroesFromPreviousScenario[i], heroPlaceholder->id));
  2534. }
  2535. }
  2536. return campaignHeroReplacements;
  2537. }
  2538. void CGameState::replaceHeroesPlaceholders(const std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements)
  2539. {
  2540. for(auto campaignHeroReplacement : campaignHeroReplacements)
  2541. {
  2542. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder*>(getObjInstance(campaignHeroReplacement.heroPlaceholderId));
  2543. CGHeroInstance *heroToPlace = campaignHeroReplacement.hero;
  2544. heroToPlace->id = campaignHeroReplacement.heroPlaceholderId;
  2545. heroToPlace->tempOwner = heroPlaceholder->tempOwner;
  2546. heroToPlace->pos = heroPlaceholder->pos;
  2547. heroToPlace->type = VLC->heroh->heroes[heroToPlace->subID];
  2548. for(auto &&i : heroToPlace->stacks)
  2549. i.second->type = VLC->creh->creatures[i.second->getCreatureID()];
  2550. auto fixArtifact = [&](CArtifactInstance * art)
  2551. {
  2552. art->artType = VLC->arth->artifacts[art->artType->id];
  2553. gs->map->artInstances.push_back(art);
  2554. art->id = ArtifactInstanceID(gs->map->artInstances.size() - 1);
  2555. };
  2556. for(auto &&i : heroToPlace->artifactsWorn)
  2557. fixArtifact(i.second.artifact);
  2558. for(auto &&i : heroToPlace->artifactsInBackpack)
  2559. fixArtifact(i.artifact);
  2560. map->heroesOnMap.push_back(heroToPlace);
  2561. map->objects[heroToPlace->id.getNum()] = heroToPlace;
  2562. map->addBlockVisTiles(heroToPlace);
  2563. scenarioOps->campState->getCurrentScenario().placedCrossoverHeroes.push_back(heroToPlace);
  2564. }
  2565. }
  2566. bool CGameState::isUsedHero(HeroTypeID hid) const
  2567. {
  2568. return getUsedHero(hid);
  2569. }
  2570. CGHeroInstance * CGameState::getUsedHero(HeroTypeID hid) const
  2571. {
  2572. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2573. {
  2574. if(hero->subID == hid.getNum())
  2575. {
  2576. return hero;
  2577. }
  2578. }
  2579. for(auto obj : map->objects) //prisons
  2580. {
  2581. if(obj && obj->ID == Obj::PRISON && obj->subID == hid.getNum())
  2582. {
  2583. return dynamic_cast<CGHeroInstance *>(obj.get());
  2584. }
  2585. }
  2586. return nullptr;
  2587. }
  2588. CGPathNode::CGPathNode()
  2589. :coord(-1,-1,-1)
  2590. {
  2591. accessible = NOT_SET;
  2592. land = 0;
  2593. moveRemains = 0;
  2594. turns = 255;
  2595. theNodeBefore = nullptr;
  2596. }
  2597. bool CGPathNode::reachable() const
  2598. {
  2599. return turns < 255;
  2600. }
  2601. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2602. {
  2603. assert(isValid);
  2604. out.nodes.clear();
  2605. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2606. if(!curnode->theNodeBefore)
  2607. return false;
  2608. while(curnode)
  2609. {
  2610. CGPathNode cpn = *curnode;
  2611. curnode = curnode->theNodeBefore;
  2612. out.nodes.push_back(cpn);
  2613. }
  2614. return true;
  2615. }
  2616. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2617. :sizes(Sizes)
  2618. {
  2619. hero = nullptr;
  2620. nodes = new CGPathNode**[sizes.x];
  2621. for(int i = 0; i < sizes.x; i++)
  2622. {
  2623. nodes[i] = new CGPathNode*[sizes.y];
  2624. for (int j = 0; j < sizes.y; j++)
  2625. {
  2626. nodes[i][j] = new CGPathNode[sizes.z];
  2627. }
  2628. }
  2629. }
  2630. CPathsInfo::~CPathsInfo()
  2631. {
  2632. for(int i = 0; i < sizes.x; i++)
  2633. {
  2634. for (int j = 0; j < sizes.y; j++)
  2635. {
  2636. delete [] nodes[i][j];
  2637. }
  2638. delete [] nodes[i];
  2639. }
  2640. delete [] nodes;
  2641. }
  2642. int3 CGPath::startPos() const
  2643. {
  2644. return nodes[nodes.size()-1].coord;
  2645. }
  2646. int3 CGPath::endPos() const
  2647. {
  2648. return nodes[0].coord;
  2649. }
  2650. void CGPath::convert( ui8 mode )
  2651. {
  2652. if(mode==0)
  2653. {
  2654. for(auto & elem : nodes)
  2655. {
  2656. elem.coord = CGHeroInstance::convertPosition(elem.coord,true);
  2657. }
  2658. }
  2659. }
  2660. PlayerState::PlayerState()
  2661. : color(-1), currentSelection(0xffffffff), enteredWinningCheatCode(0),
  2662. enteredLosingCheatCode(0), status(EPlayerStatus::INGAME)
  2663. {
  2664. setNodeType(PLAYER);
  2665. }
  2666. std::string PlayerState::nodeName() const
  2667. {
  2668. return "Player " + (color.getNum() < VLC->generaltexth->capColors.size() ? VLC->generaltexth->capColors[color.getNum()] : boost::lexical_cast<std::string>(color));
  2669. }
  2670. InfoAboutArmy::InfoAboutArmy():
  2671. owner(PlayerColor::NEUTRAL)
  2672. {}
  2673. InfoAboutArmy::InfoAboutArmy(const CArmedInstance *Army, bool detailed)
  2674. {
  2675. initFromArmy(Army, detailed);
  2676. }
  2677. void InfoAboutArmy::initFromArmy(const CArmedInstance *Army, bool detailed)
  2678. {
  2679. army = ArmyDescriptor(Army, detailed);
  2680. owner = Army->tempOwner;
  2681. name = Army->getHoverText();
  2682. }
  2683. void InfoAboutHero::assign(const InfoAboutHero & iah)
  2684. {
  2685. InfoAboutArmy::operator = (iah);
  2686. details = (iah.details ? new Details(*iah.details) : nullptr);
  2687. hclass = iah.hclass;
  2688. portrait = iah.portrait;
  2689. }
  2690. InfoAboutHero::InfoAboutHero():
  2691. details(nullptr),
  2692. hclass(nullptr),
  2693. portrait(-1)
  2694. {}
  2695. InfoAboutHero::InfoAboutHero(const InfoAboutHero & iah):
  2696. InfoAboutArmy()
  2697. {
  2698. assign(iah);
  2699. }
  2700. InfoAboutHero::InfoAboutHero(const CGHeroInstance *h, bool detailed)
  2701. : details(nullptr),
  2702. hclass(nullptr),
  2703. portrait(-1)
  2704. {
  2705. initFromHero(h, detailed);
  2706. }
  2707. InfoAboutHero::~InfoAboutHero()
  2708. {
  2709. delete details;
  2710. }
  2711. InfoAboutHero & InfoAboutHero::operator=(const InfoAboutHero & iah)
  2712. {
  2713. assign(iah);
  2714. return *this;
  2715. }
  2716. void InfoAboutHero::initFromHero(const CGHeroInstance *h, bool detailed)
  2717. {
  2718. if(!h)
  2719. return;
  2720. initFromArmy(h, detailed);
  2721. hclass = h->type->heroClass;
  2722. name = h->name;
  2723. portrait = h->portrait;
  2724. if(detailed)
  2725. {
  2726. //include details about hero
  2727. details = new Details;
  2728. details->luck = h->LuckVal();
  2729. details->morale = h->MoraleVal();
  2730. details->mana = h->mana;
  2731. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2732. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2733. {
  2734. details->primskills[i] = h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i));
  2735. }
  2736. }
  2737. }
  2738. InfoAboutTown::InfoAboutTown():
  2739. details(nullptr),
  2740. tType(nullptr),
  2741. built(0),
  2742. fortLevel(0)
  2743. {
  2744. }
  2745. InfoAboutTown::InfoAboutTown(const CGTownInstance *t, bool detailed)
  2746. {
  2747. initFromTown(t, detailed);
  2748. }
  2749. InfoAboutTown::~InfoAboutTown()
  2750. {
  2751. delete details;
  2752. }
  2753. void InfoAboutTown::initFromTown(const CGTownInstance *t, bool detailed)
  2754. {
  2755. initFromArmy(t, detailed);
  2756. army = ArmyDescriptor(t->getUpperArmy(), detailed);
  2757. built = t->builded;
  2758. fortLevel = t->fortLevel();
  2759. name = t->name;
  2760. tType = t->town;
  2761. if(detailed)
  2762. {
  2763. //include details about hero
  2764. details = new Details;
  2765. details->goldIncome = t->dailyIncome();
  2766. details->customRes = t->hasBuilt(BuildingID::RESOURCE_SILO);
  2767. details->hallLevel = t->hallLevel();
  2768. details->garrisonedHero = t->garrisonHero;
  2769. }
  2770. }
  2771. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2772. : isDetailed(detailed)
  2773. {
  2774. for(auto & elem : army->Slots())
  2775. {
  2776. if(detailed)
  2777. (*this)[elem.first] = *elem.second;
  2778. else
  2779. (*this)[elem.first] = CStackBasicDescriptor(elem.second->type, elem.second->getQuantityID());
  2780. }
  2781. }
  2782. ArmyDescriptor::ArmyDescriptor()
  2783. : isDetailed(false)
  2784. {
  2785. }
  2786. int ArmyDescriptor::getStrength() const
  2787. {
  2788. ui64 ret = 0;
  2789. if(isDetailed)
  2790. {
  2791. for(auto & elem : *this)
  2792. ret += elem.second.type->AIValue * elem.second.count;
  2793. }
  2794. else
  2795. {
  2796. for(auto & elem : *this)
  2797. ret += elem.second.type->AIValue * CCreature::estimateCreatureCount(elem.second.count);
  2798. }
  2799. return ret;
  2800. }
  2801. DuelParameters::SideSettings::StackSettings::StackSettings()
  2802. : type(CreatureID::NONE), count(0)
  2803. {
  2804. }
  2805. DuelParameters::SideSettings::StackSettings::StackSettings(CreatureID Type, si32 Count)
  2806. : type(Type), count(Count)
  2807. {
  2808. }
  2809. DuelParameters::SideSettings::SideSettings()
  2810. {
  2811. heroId = -1;
  2812. }
  2813. DuelParameters::DuelParameters():
  2814. terType(ETerrainType::DIRT),
  2815. bfieldType(BFieldType::ROCKLANDS)
  2816. {
  2817. }
  2818. DuelParameters DuelParameters::fromJSON(const std::string &fname)
  2819. {
  2820. DuelParameters ret;
  2821. const JsonNode duelData(ResourceID("DATA/" + fname, EResType::TEXT));
  2822. ret.terType = ETerrainType((int)duelData["terType"].Float());
  2823. ret.bfieldType = BFieldType((int)duelData["bfieldType"].Float());
  2824. for(const JsonNode &n : duelData["sides"].Vector())
  2825. {
  2826. SideSettings &ss = ret.sides[(int)n["side"].Float()];
  2827. int i = 0;
  2828. for(const JsonNode &stackNode : n["army"].Vector())
  2829. {
  2830. ss.stacks[i].type = CreatureID((si32)stackNode.Vector()[0].Float());
  2831. ss.stacks[i].count = stackNode.Vector()[1].Float();
  2832. i++;
  2833. }
  2834. if(n["heroid"].getType() == JsonNode::DATA_FLOAT)
  2835. ss.heroId = n["heroid"].Float();
  2836. else
  2837. ss.heroId = -1;
  2838. for(const JsonNode &entry : n["heroPrimSkills"].Vector())
  2839. ss.heroPrimSkills.push_back(entry.Float());
  2840. for(const JsonNode &skillNode : n["heroSecSkills"].Vector())
  2841. {
  2842. std::pair<si32, si8> secSkill;
  2843. secSkill.first = skillNode.Vector()[0].Float();
  2844. secSkill.second = skillNode.Vector()[1].Float();
  2845. ss.heroSecSkills.push_back(secSkill);
  2846. }
  2847. assert(ss.heroPrimSkills.empty() || ss.heroPrimSkills.size() == GameConstants::PRIMARY_SKILLS);
  2848. if(ss.heroId != -1)
  2849. {
  2850. const JsonNode & spells = n["spells"];
  2851. if(spells.getType() == JsonNode::DATA_STRING && spells.String() == "all")
  2852. {
  2853. for(auto spell : VLC->spellh->objects)
  2854. if(spell->id <= SpellID::SUMMON_AIR_ELEMENTAL)
  2855. ss.spells.insert(spell->id);
  2856. }
  2857. else
  2858. for(const JsonNode &spell : n["spells"].Vector())
  2859. ss.spells.insert(SpellID(spell.Float()));
  2860. }
  2861. }
  2862. for(const JsonNode &n : duelData["obstacles"].Vector())
  2863. {
  2864. auto oi = make_shared<CObstacleInstance>();
  2865. if(n.getType() == JsonNode::DATA_VECTOR)
  2866. {
  2867. oi->ID = n.Vector()[0].Float();
  2868. oi->pos = n.Vector()[1].Float();
  2869. }
  2870. else
  2871. {
  2872. assert(n.getType() == JsonNode::DATA_FLOAT);
  2873. oi->ID = 21;
  2874. oi->pos = n.Float();
  2875. }
  2876. oi->uniqueID = ret.obstacles.size();
  2877. ret.obstacles.push_back(oi);
  2878. }
  2879. for(const JsonNode &n : duelData["creatures"].Vector())
  2880. {
  2881. CusomCreature cc;
  2882. cc.id = n["id"].Float();
  2883. #define retrieve(name) \
  2884. if(n[ #name ].getType() == JsonNode::DATA_FLOAT)\
  2885. cc.name = n[ #name ].Float(); \
  2886. else \
  2887. cc.name = -1;
  2888. retrieve(attack);
  2889. retrieve(defense);
  2890. retrieve(HP);
  2891. retrieve(dmg);
  2892. retrieve(shoots);
  2893. retrieve(speed);
  2894. ret.creatures.push_back(cc);
  2895. }
  2896. return ret;
  2897. }
  2898. TeamState::TeamState()
  2899. {
  2900. setNodeType(TEAM);
  2901. }
  2902. void CPathfinder::initializeGraph()
  2903. {
  2904. CGPathNode ***graph = out.nodes;
  2905. for(size_t i=0; i < out.sizes.x; ++i)
  2906. {
  2907. for(size_t j=0; j < out.sizes.y; ++j)
  2908. {
  2909. for(size_t k=0; k < out.sizes.z; ++k)
  2910. {
  2911. curPos = int3(i,j,k);
  2912. const TerrainTile *tinfo = &gs->map->getTile(int3(i, j, k));
  2913. CGPathNode &node = graph[i][j][k];
  2914. node.accessible = evaluateAccessibility(tinfo);
  2915. node.turns = 0xff;
  2916. node.moveRemains = 0;
  2917. node.coord.x = i;
  2918. node.coord.y = j;
  2919. node.coord.z = k;
  2920. node.land = tinfo->terType != ETerrainType::WATER;
  2921. node.theNodeBefore = nullptr;
  2922. }
  2923. }
  2924. }
  2925. }
  2926. void CPathfinder::calculatePaths(int3 src /*= int3(-1,-1,-1)*/, int movement /*= -1*/)
  2927. {
  2928. assert(hero);
  2929. assert(hero == getHero(hero->id));
  2930. if(src.x < 0)
  2931. src = hero->getPosition(false);
  2932. if(movement < 0)
  2933. movement = hero->movement;
  2934. bool flying = hero->hasBonusOfType(Bonus::FLYING_MOVEMENT);
  2935. int maxMovePointsLand = hero->maxMovePoints(true);
  2936. int maxMovePointsWater = hero->maxMovePoints(false);
  2937. auto maxMovePoints = [&](CGPathNode *cp) -> int
  2938. {
  2939. return cp->land ? maxMovePointsLand : maxMovePointsWater;
  2940. };
  2941. out.hero = hero;
  2942. out.hpos = src;
  2943. if(!gs->map->isInTheMap(src)/* || !gs->map->isInTheMap(dest)*/) //check input
  2944. {
  2945. logGlobal->errorStream() << "CGameState::calculatePaths: Hero outside the gs->map? How dare you...";
  2946. return;
  2947. }
  2948. initializeGraph();
  2949. //initial tile - set cost on 0 and add to the queue
  2950. CGPathNode &initialNode = *getNode(src);
  2951. initialNode.turns = 0;
  2952. initialNode.moveRemains = movement;
  2953. mq.push_back(&initialNode);
  2954. std::vector<int3> neighbours;
  2955. neighbours.reserve(16);
  2956. while(!mq.empty())
  2957. {
  2958. cp = mq.front();
  2959. mq.pop_front();
  2960. const int3 sourceGuardPosition = gs->map->guardingCreaturePositions[cp->coord.x][cp->coord.y][cp->coord.z];
  2961. bool guardedSource = (sourceGuardPosition != int3(-1, -1, -1) && cp->coord != src);
  2962. ct = &gs->map->getTile(cp->coord);
  2963. int movement = cp->moveRemains, turn = cp->turns;
  2964. if(!movement)
  2965. {
  2966. movement = maxMovePoints(cp);
  2967. turn++;
  2968. }
  2969. //add accessible neighbouring nodes to the queue
  2970. neighbours.clear();
  2971. //handling subterranean gate => it's exit is the only neighbour
  2972. bool subterraneanEntry = (ct->topVisitableId() == Obj::SUBTERRANEAN_GATE && useSubterraneanGates);
  2973. if(subterraneanEntry)
  2974. {
  2975. //try finding the exit gate
  2976. if(const CGObjectInstance *outGate = getObj(CGTeleport::getMatchingGate(ct->visitableObjects.back()->id), false))
  2977. {
  2978. const int3 outPos = outGate->visitablePos();
  2979. //gs->getNeighbours(*getTile(outPos), outPos, neighbours, boost::logic::indeterminate, !cp->land);
  2980. neighbours.push_back(outPos);
  2981. }
  2982. else
  2983. {
  2984. //gate with no exit (blocked) -> do nothing with this node
  2985. continue;
  2986. }
  2987. }
  2988. gs->getNeighbours(*ct, cp->coord, neighbours, boost::logic::indeterminate, !cp->land);
  2989. for(auto & neighbour : neighbours)
  2990. {
  2991. const int3 &n = neighbour; //current neighbor
  2992. dp = getNode(n);
  2993. dt = &gs->map->getTile(n);
  2994. destTopVisObjID = dt->topVisitableId();
  2995. useEmbarkCost = 0; //0 - usual movement; 1 - embark; 2 - disembark
  2996. int turnAtNextTile = turn;
  2997. const bool destIsGuardian = sourceGuardPosition == n;
  2998. if(!goodForLandSeaTransition())
  2999. continue;
  3000. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED )
  3001. continue;
  3002. //special case -> hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  3003. if(cp->accessible == CGPathNode::VISITABLE && guardedSource && cp->theNodeBefore->land && ct->topVisitableId() == Obj::BOAT)
  3004. guardedSource = false;
  3005. int cost = gs->getMovementCost(hero, cp->coord, dp->coord, flying, movement);
  3006. //special case -> moving from src Subterranean gate to dest gate -> it's free
  3007. if(subterraneanEntry && destTopVisObjID == Obj::SUBTERRANEAN_GATE && cp->coord.z != dp->coord.z)
  3008. cost = 0;
  3009. int remains = movement - cost;
  3010. if(useEmbarkCost)
  3011. {
  3012. remains = hero->movementPointsAfterEmbark(movement, cost, useEmbarkCost - 1);
  3013. cost = movement - remains;
  3014. }
  3015. if(remains < 0)
  3016. {
  3017. //occurs rarely, when hero with low movepoints tries to leave the road
  3018. turnAtNextTile++;
  3019. int moveAtNextTile = maxMovePoints(cp);
  3020. cost = gs->getMovementCost(hero, cp->coord, dp->coord, flying, moveAtNextTile); //cost must be updated, movement points changed :(
  3021. remains = moveAtNextTile - cost;
  3022. }
  3023. if((dp->turns==0xff //we haven't been here before
  3024. || dp->turns > turnAtNextTile
  3025. || (dp->turns >= turnAtNextTile && dp->moveRemains < remains)) //this route is faster
  3026. && (!guardedSource || destIsGuardian)) // Can step into tile of guard
  3027. {
  3028. assert(dp != cp->theNodeBefore); //two tiles can't point to each other
  3029. dp->moveRemains = remains;
  3030. dp->turns = turnAtNextTile;
  3031. dp->theNodeBefore = cp;
  3032. const bool guardedDst = gs->map->guardingCreaturePositions[dp->coord.x][dp->coord.y][dp->coord.z].valid()
  3033. && dp->accessible == CGPathNode::BLOCKVIS;
  3034. if (dp->accessible == CGPathNode::ACCESSIBLE
  3035. || (useEmbarkCost && allowEmbarkAndDisembark)
  3036. || destTopVisObjID == Obj::SUBTERRANEAN_GATE
  3037. || (guardedDst && !guardedSource)) // Can step into a hostile tile once.
  3038. {
  3039. mq.push_back(dp);
  3040. }
  3041. }
  3042. } //neighbours loop
  3043. } //queue loop
  3044. out.isValid = true;
  3045. }
  3046. CGPathNode *CPathfinder::getNode(const int3 &coord)
  3047. {
  3048. return &out.nodes[coord.x][coord.y][coord.z];
  3049. }
  3050. bool CPathfinder::canMoveBetween(const int3 &a, const int3 &b) const
  3051. {
  3052. return gs->checkForVisitableDir(a, b) && gs->checkForVisitableDir(b, a);
  3053. }
  3054. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const TerrainTile *tinfo) const
  3055. {
  3056. CGPathNode::EAccessibility ret = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  3057. if(tinfo->terType == ETerrainType::ROCK || !FoW[curPos.x][curPos.y][curPos.z])
  3058. return CGPathNode::BLOCKED;
  3059. if(tinfo->visitable)
  3060. {
  3061. if(tinfo->visitableObjects.front()->ID == Obj::SANCTUARY && tinfo->visitableObjects.back()->ID == Obj::HERO && tinfo->visitableObjects.back()->tempOwner != hero->tempOwner) //non-owned hero stands on Sanctuary
  3062. {
  3063. return CGPathNode::BLOCKED;
  3064. }
  3065. else
  3066. {
  3067. for(const CGObjectInstance *obj : tinfo->visitableObjects)
  3068. {
  3069. if(obj->passableFor(hero->tempOwner)) //special object instance specific passableness flag - overwrites other accessibility flags
  3070. {
  3071. ret = CGPathNode::ACCESSIBLE;
  3072. }
  3073. else if(obj->blockVisit)
  3074. {
  3075. return CGPathNode::BLOCKVIS;
  3076. }
  3077. else if(obj->ID != Obj::EVENT) //pathfinder should ignore placed events
  3078. {
  3079. ret = CGPathNode::VISITABLE;
  3080. }
  3081. }
  3082. }
  3083. }
  3084. else if (gs->map->guardingCreaturePositions[curPos.x][curPos.y][curPos.z].valid()
  3085. && !tinfo->blocked)
  3086. {
  3087. // Monster close by; blocked visit for battle.
  3088. return CGPathNode::BLOCKVIS;
  3089. }
  3090. return ret;
  3091. }
  3092. bool CPathfinder::goodForLandSeaTransition()
  3093. {
  3094. if(cp->land != dp->land) //hero can traverse land<->sea only in special circumstances
  3095. {
  3096. if(cp->land) //from land to sea -> embark or assault hero on boat
  3097. {
  3098. if(dp->accessible == CGPathNode::ACCESSIBLE || destTopVisObjID < 0) //cannot enter empty water tile from land -> it has to be visitable
  3099. return false;
  3100. if(destTopVisObjID != Obj::HERO && destTopVisObjID != Obj::BOAT) //only boat or hero can be accessed from land
  3101. return false;
  3102. if(destTopVisObjID == Obj::BOAT)
  3103. useEmbarkCost = 1;
  3104. }
  3105. else //disembark
  3106. {
  3107. //can disembark only on coastal tiles
  3108. if(!dt->isCoastal())
  3109. return false;
  3110. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  3111. if( (dp->accessible != CGPathNode::ACCESSIBLE && (dp->accessible != CGPathNode::BLOCKVIS || dt->blocked))
  3112. || dt->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  3113. return false;;
  3114. useEmbarkCost = 2;
  3115. }
  3116. }
  3117. return true;
  3118. }
  3119. CPathfinder::CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero) : CGameInfoCallback(_gs, boost::optional<PlayerColor>()), out(_out), hero(_hero), FoW(getPlayerTeam(hero->tempOwner)->fogOfWarMap)
  3120. {
  3121. useSubterraneanGates = true;
  3122. allowEmbarkAndDisembark = true;
  3123. }
  3124. EVictoryLossCheckResult::EVictoryLossCheckResult() :
  3125. intValue(0)
  3126. {
  3127. }
  3128. EVictoryLossCheckResult::EVictoryLossCheckResult(si32 intValue, std::string toSelf, std::string toOthers) :
  3129. messageToSelf(toSelf),
  3130. messageToOthers(toOthers),
  3131. intValue(intValue)
  3132. {
  3133. }
  3134. bool EVictoryLossCheckResult::operator==(EVictoryLossCheckResult const & other) const
  3135. {
  3136. return intValue == other.intValue;
  3137. }
  3138. bool EVictoryLossCheckResult::operator!=(EVictoryLossCheckResult const & other) const
  3139. {
  3140. return intValue != other.intValue;
  3141. }
  3142. bool EVictoryLossCheckResult::victory() const
  3143. {
  3144. return intValue == VICTORY;
  3145. }
  3146. bool EVictoryLossCheckResult::loss() const
  3147. {
  3148. return intValue == DEFEAT;
  3149. }
  3150. EVictoryLossCheckResult EVictoryLossCheckResult::invert()
  3151. {
  3152. return EVictoryLossCheckResult(-intValue, messageToOthers, messageToSelf);
  3153. }
  3154. EVictoryLossCheckResult EVictoryLossCheckResult::victory(std::string toSelf, std::string toOthers)
  3155. {
  3156. return EVictoryLossCheckResult(VICTORY, toSelf, toOthers);
  3157. }
  3158. EVictoryLossCheckResult EVictoryLossCheckResult::defeat(std::string toSelf, std::string toOthers)
  3159. {
  3160. return EVictoryLossCheckResult(DEFEAT, toSelf, toOthers);
  3161. }
  3162. std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult)
  3163. {
  3164. os << victoryLossCheckResult.messageToSelf;
  3165. return os;
  3166. }
  3167. CRandomGenerator & CGameState::getRandomGenerator()
  3168. {
  3169. return rand;
  3170. }