CGameState.cpp 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985
  1. /*
  2. * CGameState.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CGameState.h"
  12. #include "mapping/CCampaignHandler.h"
  13. #include "ArtifactUtils.h"
  14. #include "CArtHandler.h"
  15. #include "CBuildingHandler.h"
  16. #include "CGeneralTextHandler.h"
  17. #include "CTownHandler.h"
  18. #include "spells/CSpellHandler.h"
  19. #include "CHeroHandler.h"
  20. #include "CModHandler.h"
  21. #include "GameSettings.h"
  22. #include "TerrainHandler.h"
  23. #include "CSkillHandler.h"
  24. #include "mapping/CMap.h"
  25. #include "mapping/CMapService.h"
  26. #include "mapObjectConstructors/CObjectClassesHandler.h"
  27. #include "StartInfo.h"
  28. #include "NetPacks.h"
  29. #include "registerTypes/RegisterTypes.h"
  30. #include "battle/BattleInfo.h"
  31. #include "JsonNode.h"
  32. #include "filesystem/Filesystem.h"
  33. #include "GameConstants.h"
  34. #include "rmg/CMapGenerator.h"
  35. #include "CStopWatch.h"
  36. #include "mapping/CMapEditManager.h"
  37. #include "serializer/CTypeList.h"
  38. #include "serializer/CMemorySerializer.h"
  39. #include "VCMIDirs.h"
  40. VCMI_LIB_NAMESPACE_BEGIN
  41. boost::shared_mutex CGameState::mutex;
  42. template <typename T> class CApplyOnGS;
  43. class CBaseForGSApply
  44. {
  45. public:
  46. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  47. virtual ~CBaseForGSApply() = default;
  48. template<typename U> static CBaseForGSApply *getApplier(const U * t=nullptr)
  49. {
  50. return new CApplyOnGS<U>();
  51. }
  52. };
  53. template <typename T> class CApplyOnGS : public CBaseForGSApply
  54. {
  55. public:
  56. void applyOnGS(CGameState *gs, void *pack) const override
  57. {
  58. T *ptr = static_cast<T*>(pack);
  59. boost::unique_lock<boost::shared_mutex> lock(CGameState::mutex);
  60. ptr->applyGs(gs);
  61. }
  62. };
  63. static CGObjectInstance * createObject(const Obj & id, int subid, const int3 & pos, const PlayerColor & owner)
  64. {
  65. CGObjectInstance * nobj;
  66. switch(id)
  67. {
  68. case Obj::HERO:
  69. {
  70. auto handler = VLC->objtypeh->getHandlerFor(id, VLC->heroh->objects[subid]->heroClass->getIndex());
  71. nobj = handler->create(handler->getTemplates().front());
  72. break;
  73. }
  74. case Obj::TOWN:
  75. nobj = new CGTownInstance();
  76. break;
  77. default: //rest of objects
  78. nobj = new CGObjectInstance();
  79. break;
  80. }
  81. nobj->ID = id;
  82. nobj->subID = subid;
  83. nobj->pos = pos;
  84. nobj->tempOwner = owner;
  85. if (id != Obj::HERO)
  86. nobj->appearance = VLC->objtypeh->getHandlerFor(id, subid)->getTemplates().front();
  87. return nobj;
  88. }
  89. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native,
  90. const PlayerColor & player,
  91. const CTown * town,
  92. std::map<ui32, ConstTransitivePtr<CGHeroInstance>> & available,
  93. CRandomGenerator & rand,
  94. const CHeroClass * bannedClass) const
  95. {
  96. CGHeroInstance *ret = nullptr;
  97. if(player>=PlayerColor::PLAYER_LIMIT)
  98. {
  99. logGlobal->error("Cannot pick hero for faction %s. Wrong owner!", town->faction->getJsonKey());
  100. return nullptr;
  101. }
  102. std::vector<CGHeroInstance *> pool;
  103. if(native)
  104. {
  105. for(auto & elem : available)
  106. {
  107. if(pavailable.find(elem.first)->second & 1<<player.getNum()
  108. && elem.second->type->heroClass->faction == town->faction->getIndex())
  109. {
  110. pool.push_back(elem.second); //get all available heroes
  111. }
  112. }
  113. if(pool.empty())
  114. {
  115. logGlobal->error("Cannot pick native hero for %s. Picking any...", player.getStr());
  116. return pickHeroFor(false, player, town, available, rand);
  117. }
  118. else
  119. {
  120. ret = *RandomGeneratorUtil::nextItem(pool, rand);
  121. }
  122. }
  123. else
  124. {
  125. int sum = 0;
  126. int r;
  127. for(auto & elem : available)
  128. {
  129. if (pavailable.find(elem.first)->second & (1<<player.getNum()) && // hero is available
  130. ( !bannedClass || elem.second->type->heroClass != bannedClass) ) // and his class is not same as other hero
  131. {
  132. pool.push_back(elem.second);
  133. sum += elem.second->type->heroClass->selectionProbability[town->faction->getId()]; //total weight
  134. }
  135. }
  136. if(pool.empty() || sum == 0)
  137. {
  138. logGlobal->error("There are no heroes available for player %s!", player.getStr());
  139. return nullptr;
  140. }
  141. r = rand.nextInt(sum - 1);
  142. for (auto & elem : pool)
  143. {
  144. r -= elem->type->heroClass->selectionProbability[town->faction->getId()];
  145. if(r < 0)
  146. {
  147. ret = elem;
  148. break;
  149. }
  150. }
  151. if(!ret)
  152. ret = pool.back();
  153. }
  154. available.erase(ret->subID);
  155. return ret;
  156. }
  157. void CGameState::CrossoverHeroesList::addHeroToBothLists(CGHeroInstance * hero)
  158. {
  159. heroesFromPreviousScenario.push_back(hero);
  160. heroesFromAnyPreviousScenarios.push_back(hero);
  161. }
  162. void CGameState::CrossoverHeroesList::removeHeroFromBothLists(CGHeroInstance * hero)
  163. {
  164. heroesFromPreviousScenario -= hero;
  165. heroesFromAnyPreviousScenarios -= hero;
  166. }
  167. CGameState::CampaignHeroReplacement::CampaignHeroReplacement(CGHeroInstance * hero, const ObjectInstanceID & heroPlaceholderId):
  168. hero(hero),
  169. heroPlaceholderId(heroPlaceholderId)
  170. {
  171. }
  172. int CGameState::pickNextHeroType(const PlayerColor & owner)
  173. {
  174. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  175. if(ps.hero >= 0 && !isUsedHero(HeroTypeID(ps.hero))) //we haven't used selected hero
  176. {
  177. return ps.hero;
  178. }
  179. return pickUnusedHeroTypeRandomly(owner);
  180. }
  181. int CGameState::pickUnusedHeroTypeRandomly(const PlayerColor & owner)
  182. {
  183. //list of available heroes for this faction and others
  184. std::vector<HeroTypeID> factionHeroes;
  185. std::vector<HeroTypeID> otherHeroes;
  186. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  187. for(const HeroTypeID & hid : getUnusedAllowedHeroes())
  188. {
  189. if(VLC->heroh->objects[hid.getNum()]->heroClass->faction == ps.castle)
  190. factionHeroes.push_back(hid);
  191. else
  192. otherHeroes.push_back(hid);
  193. }
  194. // select random hero native to "our" faction
  195. if(!factionHeroes.empty())
  196. {
  197. return RandomGeneratorUtil::nextItem(factionHeroes, getRandomGenerator())->getNum();
  198. }
  199. logGlobal->warn("Cannot find free hero of appropriate faction for player %s - trying to get first available...", owner.getStr());
  200. if(!otherHeroes.empty())
  201. {
  202. return RandomGeneratorUtil::nextItem(otherHeroes, getRandomGenerator())->getNum();
  203. }
  204. logGlobal->error("No free allowed heroes!");
  205. auto notAllowedHeroesButStillBetterThanCrash = getUnusedAllowedHeroes(true);
  206. if(!notAllowedHeroesButStillBetterThanCrash.empty())
  207. return notAllowedHeroesButStillBetterThanCrash.begin()->getNum();
  208. logGlobal->error("No free heroes at all!");
  209. assert(0); //current code can't handle this situation
  210. return -1; // no available heroes at all
  211. }
  212. std::pair<Obj,int> CGameState::pickObject (CGObjectInstance *obj)
  213. {
  214. switch(obj->ID)
  215. {
  216. case Obj::RANDOM_ART:
  217. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  218. case Obj::RANDOM_TREASURE_ART:
  219. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE));
  220. case Obj::RANDOM_MINOR_ART:
  221. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_MINOR));
  222. case Obj::RANDOM_MAJOR_ART:
  223. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_MAJOR));
  224. case Obj::RANDOM_RELIC_ART:
  225. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_RELIC));
  226. case Obj::RANDOM_HERO:
  227. return std::make_pair(Obj::HERO, pickNextHeroType(obj->tempOwner));
  228. case Obj::RANDOM_MONSTER:
  229. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator()));
  230. case Obj::RANDOM_MONSTER_L1:
  231. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 1));
  232. case Obj::RANDOM_MONSTER_L2:
  233. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 2));
  234. case Obj::RANDOM_MONSTER_L3:
  235. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 3));
  236. case Obj::RANDOM_MONSTER_L4:
  237. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 4));
  238. case Obj::RANDOM_RESOURCE:
  239. return std::make_pair(Obj::RESOURCE,getRandomGenerator().nextInt(6)); //now it's OH3 style, use %8 for mithril
  240. case Obj::RANDOM_TOWN:
  241. {
  242. PlayerColor align = (dynamic_cast<CGTownInstance *>(obj))->alignmentToPlayer;
  243. si32 f; // can be negative (for random)
  244. if(align >= PlayerColor::PLAYER_LIMIT) //same as owner / random
  245. {
  246. if(obj->tempOwner >= PlayerColor::PLAYER_LIMIT)
  247. f = -1; //random
  248. else
  249. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  250. }
  251. else
  252. {
  253. f = scenarioOps->getIthPlayersSettings(align).castle;
  254. }
  255. if(f<0)
  256. {
  257. do
  258. {
  259. f = getRandomGenerator().nextInt((int)VLC->townh->size() - 1);
  260. }
  261. while ((*VLC->townh)[f]->town == nullptr); // find playable faction
  262. }
  263. return std::make_pair(Obj::TOWN,f);
  264. }
  265. case Obj::RANDOM_MONSTER_L5:
  266. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 5));
  267. case Obj::RANDOM_MONSTER_L6:
  268. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 6));
  269. case Obj::RANDOM_MONSTER_L7:
  270. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 7));
  271. case Obj::RANDOM_DWELLING:
  272. case Obj::RANDOM_DWELLING_LVL:
  273. case Obj::RANDOM_DWELLING_FACTION:
  274. {
  275. auto * dwl = dynamic_cast<CGDwelling *>(obj);
  276. int faction;
  277. //if castle alignment available
  278. if(auto * info = dynamic_cast<CCreGenAsCastleInfo *>(dwl->info))
  279. {
  280. faction = getRandomGenerator().nextInt((int)VLC->townh->size() - 1);
  281. if(info->asCastle && !info->instanceId.empty())
  282. {
  283. auto iter = map->instanceNames.find(info->instanceId);
  284. if(iter == map->instanceNames.end())
  285. logGlobal->error("Map object not found: %s", info->instanceId);
  286. else
  287. {
  288. auto elem = iter->second;
  289. if(elem->ID==Obj::RANDOM_TOWN)
  290. {
  291. randomizeObject(elem.get()); //we have to randomize the castle first
  292. faction = elem->subID;
  293. }
  294. else if(elem->ID==Obj::TOWN)
  295. faction = elem->subID;
  296. else
  297. logGlobal->error("Map object must be town: %s", info->instanceId);
  298. }
  299. }
  300. else if(info->asCastle)
  301. {
  302. for(auto & elem : map->objects)
  303. {
  304. if(!elem)
  305. continue;
  306. if(elem->ID==Obj::RANDOM_TOWN
  307. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  308. {
  309. randomizeObject(elem); //we have to randomize the castle first
  310. faction = elem->subID;
  311. break;
  312. }
  313. else if(elem->ID==Obj::TOWN
  314. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  315. {
  316. faction = elem->subID;
  317. break;
  318. }
  319. }
  320. }
  321. else
  322. {
  323. std::set<int> temp;
  324. for(int i = 0; i < info->allowedFactions.size(); i++)
  325. if(info->allowedFactions[i])
  326. temp.insert(i);
  327. if(temp.empty())
  328. logGlobal->error("Random faction selection failed. Nothing is allowed. Fall back to random.");
  329. else
  330. faction = *RandomGeneratorUtil::nextItem(temp, getRandomGenerator());
  331. }
  332. }
  333. else // castle alignment fixed
  334. faction = obj->subID;
  335. int level;
  336. //if level set to range
  337. if(auto * info = dynamic_cast<CCreGenLeveledInfo *>(dwl->info))
  338. {
  339. level = getRandomGenerator().nextInt(info->minLevel, info->maxLevel);
  340. }
  341. else // fixed level
  342. {
  343. level = obj->subID;
  344. }
  345. delete dwl->info;
  346. dwl->info = nullptr;
  347. std::pair<Obj, int> result(Obj::NO_OBJ, -1);
  348. CreatureID cid = (*VLC->townh)[faction]->town->creatures[level][0];
  349. //NOTE: this will pick last dwelling with this creature (Mantis #900)
  350. //check for block map equality is better but more complex solution
  351. auto testID = [&](const Obj & primaryID) -> void
  352. {
  353. auto dwellingIDs = VLC->objtypeh->knownSubObjects(primaryID);
  354. for (si32 entry : dwellingIDs)
  355. {
  356. const auto * handler = dynamic_cast<const DwellingInstanceConstructor *>(VLC->objtypeh->getHandlerFor(primaryID, entry).get());
  357. if (handler->producesCreature(VLC->creh->objects[cid]))
  358. result = std::make_pair(primaryID, entry);
  359. }
  360. };
  361. testID(Obj::CREATURE_GENERATOR1);
  362. if (result.first == Obj::NO_OBJ)
  363. testID(Obj::CREATURE_GENERATOR4);
  364. if (result.first == Obj::NO_OBJ)
  365. {
  366. logGlobal->error("Error: failed to find dwelling for %s of level %d", (*VLC->townh)[faction]->getNameTranslated(), int(level));
  367. result = std::make_pair(Obj::CREATURE_GENERATOR1, *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1), getRandomGenerator()));
  368. }
  369. return result;
  370. }
  371. }
  372. return std::make_pair(Obj::NO_OBJ,-1);
  373. }
  374. void CGameState::randomizeObject(CGObjectInstance *cur)
  375. {
  376. std::pair<Obj,int> ran = pickObject(cur);
  377. if(ran.first == Obj::NO_OBJ || ran.second<0) //this is not a random object, or we couldn't find anything
  378. {
  379. if(cur->ID==Obj::TOWN || cur->ID==Obj::MONSTER)
  380. cur->setType(cur->ID, cur->subID); // update def, if necessary
  381. }
  382. else if(ran.first==Obj::HERO)//special code for hero
  383. {
  384. auto * h = dynamic_cast<CGHeroInstance *>(cur);
  385. cur->setType(ran.first, ran.second);
  386. map->heroesOnMap.emplace_back(h);
  387. }
  388. else if(ran.first==Obj::TOWN)//special code for town
  389. {
  390. auto * t = dynamic_cast<CGTownInstance *>(cur);
  391. cur->setType(ran.first, ran.second);
  392. map->towns.emplace_back(t);
  393. }
  394. else
  395. {
  396. cur->setType(ran.first, ran.second);
  397. }
  398. }
  399. int CGameState::getDate(Date::EDateType mode) const
  400. {
  401. int temp;
  402. switch (mode)
  403. {
  404. case Date::DAY:
  405. return day;
  406. case Date::DAY_OF_WEEK: //day of week
  407. temp = (day)%7; // 1 - Monday, 7 - Sunday
  408. return temp ? temp : 7;
  409. case Date::WEEK: //current week
  410. temp = ((day-1)/7)+1;
  411. if (!(temp%4))
  412. return 4;
  413. else
  414. return (temp%4);
  415. case Date::MONTH: //current month
  416. return ((day-1)/28)+1;
  417. case Date::DAY_OF_MONTH: //day of month
  418. temp = (day)%28;
  419. if (temp)
  420. return temp;
  421. else return 28;
  422. }
  423. return 0;
  424. }
  425. CGameState::CGameState()
  426. {
  427. gs = this;
  428. applier = std::make_shared<CApplier<CBaseForGSApply>>();
  429. registerTypesClientPacks1(*applier);
  430. registerTypesClientPacks2(*applier);
  431. globalEffects.setNodeType(CBonusSystemNode::GLOBAL_EFFECTS);
  432. }
  433. CGameState::~CGameState()
  434. {
  435. map.dellNull();
  436. curB.dellNull();
  437. for(auto ptr : hpool.heroesPool) // clean hero pool
  438. ptr.second.dellNull();
  439. }
  440. void CGameState::preInit(Services * services)
  441. {
  442. this->services = services;
  443. }
  444. void CGameState::init(const IMapService * mapService, StartInfo * si, bool allowSavingRandomMap)
  445. {
  446. preInitAuto();
  447. logGlobal->info("\tUsing random seed: %d", si->seedToBeUsed);
  448. getRandomGenerator().setSeed(si->seedToBeUsed);
  449. scenarioOps = CMemorySerializer::deepCopy(*si).release();
  450. initialOpts = CMemorySerializer::deepCopy(*si).release();
  451. si = nullptr;
  452. switch(scenarioOps->mode)
  453. {
  454. case StartInfo::NEW_GAME:
  455. initNewGame(mapService, allowSavingRandomMap);
  456. break;
  457. case StartInfo::CAMPAIGN:
  458. initCampaign();
  459. break;
  460. default:
  461. logGlobal->error("Wrong mode: %d", static_cast<int>(scenarioOps->mode));
  462. return;
  463. }
  464. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  465. logGlobal->info("Map loaded!");
  466. checkMapChecksum();
  467. day = 0;
  468. logGlobal->debug("Initialization:");
  469. initGlobalBonuses();
  470. initPlayerStates();
  471. placeCampaignHeroes();
  472. initGrailPosition();
  473. initRandomFactionsForPlayers();
  474. randomizeMapObjects();
  475. placeStartingHeroes();
  476. initStartingResources();
  477. initHeroes();
  478. initStartingBonus();
  479. initTowns();
  480. placeHeroesInTowns();
  481. initMapObjects();
  482. buildBonusSystemTree();
  483. initVisitingAndGarrisonedHeroes();
  484. initFogOfWar();
  485. // Explicitly initialize static variables
  486. for(auto & elem : players)
  487. {
  488. CGKeys::playerKeyMap[elem.first] = std::set<ui8>();
  489. }
  490. for(auto & elem : teams)
  491. {
  492. CGObelisk::visited[elem.first] = 0;
  493. }
  494. logGlobal->debug("\tChecking objectives");
  495. map->checkForObjectives(); //needs to be run when all objects are properly placed
  496. auto seedAfterInit = getRandomGenerator().nextInt();
  497. logGlobal->info("Seed after init is %d (before was %d)", seedAfterInit, scenarioOps->seedToBeUsed);
  498. if(scenarioOps->seedPostInit > 0)
  499. {
  500. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  501. assert(scenarioOps->seedPostInit == seedAfterInit);
  502. }
  503. else
  504. {
  505. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  506. }
  507. }
  508. void CGameState::updateEntity(Metatype metatype, int32_t index, const JsonNode & data)
  509. {
  510. switch(metatype)
  511. {
  512. case Metatype::ARTIFACT_INSTANCE:
  513. logGlobal->error("Artifact instance update is not implemented");
  514. break;
  515. case Metatype::CREATURE_INSTANCE:
  516. logGlobal->error("Creature instance update is not implemented");
  517. break;
  518. case Metatype::HERO_INSTANCE:
  519. //index is hero type
  520. if(index >= 0 && index < map->allHeroes.size())
  521. {
  522. CGHeroInstance * hero = map->allHeroes.at(index);
  523. hero->updateFrom(data);
  524. }
  525. else
  526. {
  527. logGlobal->error("Update entity: hero index %s is out of range [%d,%d]", index, 0, map->allHeroes.size());
  528. }
  529. break;
  530. case Metatype::MAP_OBJECT_INSTANCE:
  531. if(index >= 0 && index < map->objects.size())
  532. {
  533. CGObjectInstance * obj = getObjInstance(ObjectInstanceID(index));
  534. obj->updateFrom(data);
  535. }
  536. else
  537. {
  538. logGlobal->error("Update entity: object index %s is out of range [%d,%d]", index, 0, map->objects.size());
  539. }
  540. break;
  541. default:
  542. services->updateEntity(metatype, index, data);
  543. break;
  544. }
  545. }
  546. void CGameState::updateOnLoad(StartInfo * si)
  547. {
  548. preInitAuto();
  549. scenarioOps->playerInfos = si->playerInfos;
  550. for(auto & i : si->playerInfos)
  551. gs->players[i.first].human = i.second.isControlledByHuman();
  552. }
  553. void CGameState::preInitAuto()
  554. {
  555. if(services == nullptr)
  556. {
  557. logGlobal->error("Game state preinit missing");
  558. preInit(VLC);
  559. }
  560. }
  561. void CGameState::initNewGame(const IMapService * mapService, bool allowSavingRandomMap)
  562. {
  563. if(scenarioOps->createRandomMap())
  564. {
  565. logGlobal->info("Create random map.");
  566. CStopWatch sw;
  567. // Gen map
  568. CMapGenerator mapGenerator(*scenarioOps->mapGenOptions, scenarioOps->seedToBeUsed);
  569. std::unique_ptr<CMap> randomMap = mapGenerator.generate();
  570. if(allowSavingRandomMap)
  571. {
  572. try
  573. {
  574. auto path = VCMIDirs::get().userCachePath() / "RandomMaps";
  575. boost::filesystem::create_directories(path);
  576. std::shared_ptr<CMapGenOptions> options = scenarioOps->mapGenOptions;
  577. const std::string templateName = options->getMapTemplate()->getName();
  578. const ui32 seed = scenarioOps->seedToBeUsed;
  579. const std::string fileName = boost::str(boost::format("%s_%d.vmap") % templateName % seed );
  580. const auto fullPath = path / fileName;
  581. mapService->saveMap(randomMap, fullPath);
  582. logGlobal->info("Random map has been saved to:");
  583. logGlobal->info(fullPath.string());
  584. }
  585. catch(...)
  586. {
  587. logGlobal->error("Saving random map failed with exception");
  588. handleException();
  589. }
  590. }
  591. map = randomMap.release();
  592. // Update starting options
  593. for(int i = 0; i < map->players.size(); ++i)
  594. {
  595. const auto & playerInfo = map->players[i];
  596. if(playerInfo.canAnyonePlay())
  597. {
  598. PlayerSettings & playerSettings = scenarioOps->playerInfos[PlayerColor(i)];
  599. playerSettings.compOnly = !playerInfo.canHumanPlay;
  600. playerSettings.team = playerInfo.team;
  601. playerSettings.castle = playerInfo.defaultCastle();
  602. if(playerSettings.isControlledByAI() && playerSettings.name.empty())
  603. {
  604. playerSettings.name = VLC->generaltexth->allTexts[468];
  605. }
  606. playerSettings.color = PlayerColor(i);
  607. }
  608. else
  609. {
  610. scenarioOps->playerInfos.erase(PlayerColor(i));
  611. }
  612. }
  613. logGlobal->info("Generated random map in %i ms.", sw.getDiff());
  614. }
  615. else
  616. {
  617. logGlobal->info("Open map file: %s", scenarioOps->mapname);
  618. const ResourceID mapURI(scenarioOps->mapname, EResType::MAP);
  619. map = mapService->loadMap(mapURI).release();
  620. }
  621. }
  622. void CGameState::initCampaign()
  623. {
  624. logGlobal->info("Open campaign map file: %d", scenarioOps->campState->currentMap.value());
  625. map = scenarioOps->campState->getMap();
  626. }
  627. void CGameState::checkMapChecksum()
  628. {
  629. logGlobal->info("\tOur checksum for the map: %d", map->checksum);
  630. if(scenarioOps->mapfileChecksum)
  631. {
  632. logGlobal->info("\tServer checksum for %s: %d", scenarioOps->mapname, scenarioOps->mapfileChecksum);
  633. if(map->checksum != scenarioOps->mapfileChecksum)
  634. {
  635. logGlobal->error("Wrong map checksum!!!");
  636. throw std::runtime_error("Wrong checksum");
  637. }
  638. }
  639. else
  640. {
  641. scenarioOps->mapfileChecksum = map->checksum;
  642. }
  643. }
  644. void CGameState::initGlobalBonuses()
  645. {
  646. const JsonNode & baseBonuses = VLC->settings()->getValue(EGameSettings::BONUSES_GLOBAL);
  647. logGlobal->debug("\tLoading global bonuses");
  648. for(const auto & b : baseBonuses.Struct())
  649. {
  650. auto bonus = JsonUtils::parseBonus(b.second);
  651. bonus->source = BonusSource::GLOBAL;//for all
  652. bonus->sid = -1; //there is one global object
  653. globalEffects.addNewBonus(bonus);
  654. }
  655. VLC->creh->loadCrExpBon(globalEffects);
  656. }
  657. void CGameState::initGrailPosition()
  658. {
  659. logGlobal->debug("\tPicking grail position");
  660. //pick grail location
  661. if(map->grailPos.x < 0 || map->grailRadius) //grail not set or set within a radius around some place
  662. {
  663. if(!map->grailRadius) //radius not given -> anywhere on map
  664. map->grailRadius = map->width * 2;
  665. std::vector<int3> allowedPos;
  666. static const int BORDER_WIDTH = 9; // grail must be at least 9 tiles away from border
  667. // add all not blocked tiles in range
  668. for (int z = 0; z < map->levels(); z++)
  669. {
  670. for(int x = BORDER_WIDTH; x < map->width - BORDER_WIDTH ; x++)
  671. {
  672. for(int y = BORDER_WIDTH; y < map->height - BORDER_WIDTH; y++)
  673. {
  674. const TerrainTile &t = map->getTile(int3(x, y, z));
  675. if(!t.blocked
  676. && !t.visitable
  677. && t.terType->isLand()
  678. && t.terType->isPassable()
  679. && (int)map->grailPos.dist2dSQ(int3(x, y, z)) <= (map->grailRadius * map->grailRadius))
  680. allowedPos.emplace_back(x, y, z);
  681. }
  682. }
  683. }
  684. //remove tiles with holes
  685. for(auto & elem : map->objects)
  686. if(elem && elem->ID == Obj::HOLE)
  687. allowedPos -= elem->pos;
  688. if(!allowedPos.empty())
  689. {
  690. map->grailPos = *RandomGeneratorUtil::nextItem(allowedPos, getRandomGenerator());
  691. }
  692. else
  693. {
  694. logGlobal->warn("Grail cannot be placed, no appropriate tile found!");
  695. }
  696. }
  697. }
  698. void CGameState::initRandomFactionsForPlayers()
  699. {
  700. logGlobal->debug("\tPicking random factions for players");
  701. for(auto & elem : scenarioOps->playerInfos)
  702. {
  703. if(elem.second.castle==-1)
  704. {
  705. auto randomID = getRandomGenerator().nextInt((int)map->players[elem.first.getNum()].allowedFactions.size() - 1);
  706. auto iter = map->players[elem.first.getNum()].allowedFactions.begin();
  707. std::advance(iter, randomID);
  708. elem.second.castle = *iter;
  709. }
  710. }
  711. }
  712. void CGameState::randomizeMapObjects()
  713. {
  714. logGlobal->debug("\tRandomizing objects");
  715. for(CGObjectInstance *obj : map->objects)
  716. {
  717. if(!obj) continue;
  718. randomizeObject(obj);
  719. //handle Favouring Winds - mark tiles under it
  720. if(obj->ID == Obj::FAVORABLE_WINDS)
  721. {
  722. for (int i = 0; i < obj->getWidth() ; i++)
  723. {
  724. for (int j = 0; j < obj->getHeight() ; j++)
  725. {
  726. int3 pos = obj->pos - int3(i,j,0);
  727. if(map->isInTheMap(pos)) map->getTile(pos).extTileFlags |= 128;
  728. }
  729. }
  730. }
  731. }
  732. }
  733. void CGameState::initPlayerStates()
  734. {
  735. logGlobal->debug("\tCreating player entries in gs");
  736. for(auto & elem : scenarioOps->playerInfos)
  737. {
  738. PlayerState & p = players[elem.first];
  739. p.color=elem.first;
  740. p.human = elem.second.isControlledByHuman();
  741. p.team = map->players[elem.first.getNum()].team;
  742. teams[p.team].id = p.team;//init team
  743. teams[p.team].players.insert(elem.first);//add player to team
  744. }
  745. }
  746. void CGameState::placeCampaignHeroes()
  747. {
  748. if (scenarioOps->campState)
  749. {
  750. // place bonus hero
  751. auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap();
  752. bool campaignGiveHero = campaignBonus && campaignBonus->type == CScenarioTravel::STravelBonus::HERO;
  753. if(campaignGiveHero)
  754. {
  755. auto playerColor = PlayerColor(campaignBonus->info1);
  756. auto it = scenarioOps->playerInfos.find(playerColor);
  757. if(it != scenarioOps->playerInfos.end())
  758. {
  759. auto heroTypeId = campaignBonus->info2;
  760. if(heroTypeId == 0xffff) // random bonus hero
  761. {
  762. heroTypeId = pickUnusedHeroTypeRandomly(playerColor);
  763. }
  764. placeStartingHero(playerColor, HeroTypeID(heroTypeId), map->players[playerColor.getNum()].posOfMainTown);
  765. }
  766. }
  767. // replace heroes placeholders
  768. auto crossoverHeroes = getCrossoverHeroesFromPreviousScenarios();
  769. if(!crossoverHeroes.heroesFromAnyPreviousScenarios.empty())
  770. {
  771. logGlobal->debug("\tGenerate list of hero placeholders");
  772. auto campaignHeroReplacements = generateCampaignHeroesToReplace(crossoverHeroes);
  773. logGlobal->debug("\tPrepare crossover heroes");
  774. prepareCrossoverHeroes(campaignHeroReplacements, scenarioOps->campState->getCurrentScenario().travelOptions);
  775. // remove same heroes on the map which will be added through crossover heroes
  776. // INFO: we will remove heroes because later it may be possible that the API doesn't allow having heroes
  777. // with the same hero type id
  778. std::vector<CGHeroInstance *> removedHeroes;
  779. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  780. {
  781. auto * hero = getUsedHero(HeroTypeID(campaignHeroReplacement.hero->subID));
  782. if(hero)
  783. {
  784. removedHeroes.push_back(hero);
  785. map->heroesOnMap -= hero;
  786. map->objects[hero->id.getNum()] = nullptr;
  787. map->removeBlockVisTiles(hero, true);
  788. }
  789. }
  790. logGlobal->debug("\tReplace placeholders with heroes");
  791. replaceHeroesPlaceholders(campaignHeroReplacements);
  792. // now add removed heroes again with unused type ID
  793. for(auto * hero : removedHeroes)
  794. {
  795. si32 heroTypeId = 0;
  796. if(hero->ID == Obj::HERO)
  797. {
  798. heroTypeId = pickUnusedHeroTypeRandomly(hero->tempOwner);
  799. }
  800. else if(hero->ID == Obj::PRISON)
  801. {
  802. auto unusedHeroTypeIds = getUnusedAllowedHeroes();
  803. if(!unusedHeroTypeIds.empty())
  804. {
  805. heroTypeId = (*RandomGeneratorUtil::nextItem(unusedHeroTypeIds, getRandomGenerator())).getNum();
  806. }
  807. else
  808. {
  809. logGlobal->error("No free hero type ID found to replace prison.");
  810. assert(0);
  811. }
  812. }
  813. else
  814. {
  815. assert(0); // should not happen
  816. }
  817. hero->subID = heroTypeId;
  818. hero->portrait = hero->subID;
  819. map->getEditManager()->insertObject(hero);
  820. }
  821. }
  822. }
  823. // remove hero placeholders on map
  824. for(auto obj : map->objects)
  825. {
  826. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  827. {
  828. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  829. map->removeBlockVisTiles(heroPlaceholder, true);
  830. map->instanceNames.erase(obj->instanceName);
  831. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  832. delete heroPlaceholder;
  833. }
  834. }
  835. }
  836. void CGameState::placeStartingHero(const PlayerColor & playerColor, const HeroTypeID & heroTypeId, int3 townPos)
  837. {
  838. for(auto town : map->towns)
  839. {
  840. if(town->getPosition() == townPos)
  841. {
  842. townPos = town->visitablePos();
  843. break;
  844. }
  845. }
  846. CGObjectInstance * hero = createObject(Obj::HERO, heroTypeId.getNum(), townPos, playerColor);
  847. hero->pos += hero->getVisitableOffset();
  848. map->getEditManager()->insertObject(hero);
  849. }
  850. CGameState::CrossoverHeroesList CGameState::getCrossoverHeroesFromPreviousScenarios() const
  851. {
  852. CrossoverHeroesList crossoverHeroes;
  853. auto campaignState = scenarioOps->campState;
  854. auto bonus = campaignState->getBonusForCurrentMap();
  855. if(bonus && bonus->type == CScenarioTravel::STravelBonus::HEROES_FROM_PREVIOUS_SCENARIO)
  856. {
  857. std::vector<CGHeroInstance *> heroes;
  858. for(auto & node : campaignState->camp->scenarios[bonus->info2].crossoverHeroes)
  859. {
  860. auto * h = CCampaignState::crossoverDeserialize(node);
  861. heroes.push_back(h);
  862. }
  863. crossoverHeroes.heroesFromAnyPreviousScenarios = crossoverHeroes.heroesFromPreviousScenario = heroes;
  864. }
  865. else
  866. {
  867. if(!campaignState->mapsConquered.empty())
  868. {
  869. std::vector<CGHeroInstance *> heroes = {};
  870. crossoverHeroes.heroesFromAnyPreviousScenarios = crossoverHeroes.heroesFromPreviousScenario = heroes;
  871. crossoverHeroes.heroesFromPreviousScenario = heroes;
  872. for(auto mapNr : campaignState->mapsConquered)
  873. {
  874. // create a list of deleted heroes
  875. auto & scenario = campaignState->camp->scenarios[mapNr];
  876. auto lostCrossoverHeroes = scenario.getLostCrossoverHeroes();
  877. // remove heroes which didn't reached the end of the scenario, but were available at the start
  878. for(auto * hero : lostCrossoverHeroes)
  879. {
  880. // auto hero = CCampaignState::crossoverDeserialize(node);
  881. vstd::erase_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [hero](CGHeroInstance * h)
  882. {
  883. return hero->subID == h->subID;
  884. });
  885. }
  886. // now add heroes which completed the scenario
  887. for(auto node : scenario.crossoverHeroes)
  888. {
  889. auto * hero = CCampaignState::crossoverDeserialize(node);
  890. // add new heroes and replace old heroes with newer ones
  891. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [hero](CGHeroInstance * h)
  892. {
  893. return hero->subID == h->subID;
  894. });
  895. if(it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  896. {
  897. // replace old hero with newer one
  898. crossoverHeroes.heroesFromAnyPreviousScenarios[it - crossoverHeroes.heroesFromAnyPreviousScenarios.begin()] = hero;
  899. }
  900. else
  901. {
  902. // add new hero
  903. crossoverHeroes.heroesFromAnyPreviousScenarios.push_back(hero);
  904. }
  905. if(mapNr == campaignState->mapsConquered.back())
  906. {
  907. crossoverHeroes.heroesFromPreviousScenario.push_back(hero);
  908. }
  909. }
  910. }
  911. }
  912. }
  913. return crossoverHeroes;
  914. }
  915. void CGameState::prepareCrossoverHeroes(std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions)
  916. {
  917. // create heroes list for convenience iterating
  918. std::vector<CGHeroInstance *> crossoverHeroes;
  919. crossoverHeroes.reserve(campaignHeroReplacements.size());
  920. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  921. {
  922. crossoverHeroes.push_back(campaignHeroReplacement.hero);
  923. }
  924. // TODO replace magic numbers with named constants
  925. // TODO this logic (what should be kept) should be part of CScenarioTravel and be exposed via some clean set of methods
  926. if(!travelOptions.whatHeroKeeps.experience)
  927. {
  928. //trimming experience
  929. for(CGHeroInstance * cgh : crossoverHeroes)
  930. {
  931. cgh->initExp(getRandomGenerator());
  932. }
  933. }
  934. if(!travelOptions.whatHeroKeeps.primarySkills)
  935. {
  936. //trimming prim skills
  937. for(CGHeroInstance * cgh : crossoverHeroes)
  938. {
  939. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  940. {
  941. auto sel = Selector::type()(BonusType::PRIMARY_SKILL)
  942. .And(Selector::subtype()(g))
  943. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  944. cgh->getBonusLocalFirst(sel)->val = cgh->type->heroClass->primarySkillInitial[g];
  945. }
  946. }
  947. }
  948. if(!travelOptions.whatHeroKeeps.secondarySkills)
  949. {
  950. //trimming sec skills
  951. for(CGHeroInstance * cgh : crossoverHeroes)
  952. {
  953. cgh->secSkills = cgh->type->secSkillsInit;
  954. cgh->recreateSecondarySkillsBonuses();
  955. }
  956. }
  957. if(!travelOptions.whatHeroKeeps.spells)
  958. {
  959. for(CGHeroInstance * cgh : crossoverHeroes)
  960. {
  961. cgh->removeSpellbook();
  962. }
  963. }
  964. if(!travelOptions.whatHeroKeeps.artifacts)
  965. {
  966. //trimming artifacts
  967. for(CGHeroInstance * hero : crossoverHeroes)
  968. {
  969. size_t totalArts = GameConstants::BACKPACK_START + hero->artifactsInBackpack.size();
  970. for (size_t i = 0; i < totalArts; i++ )
  971. {
  972. auto artifactPosition = ArtifactPosition((si32)i);
  973. if(artifactPosition == ArtifactPosition::SPELLBOOK) continue; // do not handle spellbook this way
  974. const ArtSlotInfo *info = hero->getSlot(artifactPosition);
  975. if(!info)
  976. continue;
  977. // TODO: why would there be nullptr artifacts?
  978. const CArtifactInstance *art = info->artifact;
  979. if(!art)
  980. continue;
  981. bool takeable = travelOptions.artifactsKeptByHero.count(art->artType->getId());
  982. ArtifactLocation al(hero, artifactPosition);
  983. if(!takeable && !al.getSlot()->locked) //don't try removing locked artifacts -> it crashes #1719
  984. al.removeArtifact();
  985. }
  986. }
  987. }
  988. //trimming creatures
  989. for(CGHeroInstance * cgh : crossoverHeroes)
  990. {
  991. auto shouldSlotBeErased = [&](const std::pair<SlotID, CStackInstance *> & j) -> bool
  992. {
  993. CreatureID::ECreatureID crid = j.second->getCreatureID().toEnum();
  994. return !travelOptions.monstersKeptByHero.count(crid);
  995. };
  996. auto stacksCopy = cgh->stacks; //copy of the map, so we can iterate iover it and remove stacks
  997. for(auto &slotPair : stacksCopy)
  998. if(shouldSlotBeErased(slotPair))
  999. cgh->eraseStack(slotPair.first);
  1000. }
  1001. // Removing short-term bonuses
  1002. for(CGHeroInstance * cgh : crossoverHeroes)
  1003. {
  1004. cgh->removeBonusesRecursive(CSelector(Bonus::OneDay)
  1005. .Or(CSelector(Bonus::OneWeek))
  1006. .Or(CSelector(Bonus::NTurns))
  1007. .Or(CSelector(Bonus::NDays))
  1008. .Or(CSelector(Bonus::OneBattle)));
  1009. }
  1010. }
  1011. void CGameState::placeStartingHeroes()
  1012. {
  1013. logGlobal->debug("\tGiving starting hero");
  1014. for(auto & playerSettingPair : scenarioOps->playerInfos)
  1015. {
  1016. auto playerColor = playerSettingPair.first;
  1017. auto & playerInfo = map->players[playerColor.getNum()];
  1018. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  1019. {
  1020. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  1021. if(scenarioOps->campState)
  1022. {
  1023. if(auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap())
  1024. {
  1025. if(campaignBonus->type == CScenarioTravel::STravelBonus::HERO && playerColor == PlayerColor(campaignBonus->info1))
  1026. continue;
  1027. }
  1028. }
  1029. int heroTypeId = pickNextHeroType(playerColor);
  1030. if(playerSettingPair.second.hero == -1)
  1031. playerSettingPair.second.hero = heroTypeId;
  1032. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  1033. }
  1034. }
  1035. }
  1036. void CGameState::initStartingResources()
  1037. {
  1038. logGlobal->debug("\tSetting up resources");
  1039. const JsonNode config(ResourceID("config/startres.json"));
  1040. const JsonVector &vector = config["difficulty"].Vector();
  1041. const JsonNode &level = vector[scenarioOps->difficulty];
  1042. TResources startresAI(level["ai"]);
  1043. TResources startresHuman(level["human"]);
  1044. for (auto & elem : players)
  1045. {
  1046. PlayerState &p = elem.second;
  1047. if (p.human)
  1048. p.resources = startresHuman;
  1049. else
  1050. p.resources = startresAI;
  1051. }
  1052. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  1053. {
  1054. std::vector<const PlayerSettings *> ret;
  1055. for(const auto & playerInfo : scenarioOps->playerInfos)
  1056. {
  1057. if(playerInfo.second.isControlledByHuman())
  1058. ret.push_back(&playerInfo.second);
  1059. }
  1060. return ret;
  1061. };
  1062. //give start resource bonus in case of campaign
  1063. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1064. {
  1065. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1066. if(chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::RESOURCE)
  1067. {
  1068. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  1069. for(const PlayerSettings *ps : people)
  1070. {
  1071. std::vector<int> res; //resources we will give
  1072. switch (chosenBonus->info1)
  1073. {
  1074. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1075. res.push_back(chosenBonus->info1);
  1076. break;
  1077. case 0xFD: //wood+ore
  1078. res.push_back(GameResID(EGameResID::WOOD));
  1079. res.push_back(GameResID(EGameResID::ORE));
  1080. break;
  1081. case 0xFE: //rare
  1082. res.push_back(GameResID(EGameResID::MERCURY));
  1083. res.push_back(GameResID(EGameResID::SULFUR));
  1084. res.push_back(GameResID(EGameResID::CRYSTAL));
  1085. res.push_back(GameResID(EGameResID::GEMS));
  1086. break;
  1087. default:
  1088. assert(0);
  1089. break;
  1090. }
  1091. //increasing resource quantity
  1092. for (auto & re : res)
  1093. {
  1094. players[ps->color].resources[re] += chosenBonus->info2;
  1095. }
  1096. }
  1097. }
  1098. }
  1099. }
  1100. void CGameState::initHeroes()
  1101. {
  1102. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1103. {
  1104. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  1105. {
  1106. logGlobal->warn("Hero with uninitialized owner!");
  1107. continue;
  1108. }
  1109. hero->initHero(getRandomGenerator());
  1110. getPlayerState(hero->getOwner())->heroes.push_back(hero);
  1111. map->allHeroes[hero->type->getIndex()] = hero;
  1112. }
  1113. // generate boats for all heroes on water
  1114. for(auto hero : map->heroesOnMap)
  1115. {
  1116. assert(map->isInTheMap(hero->visitablePos()));
  1117. const auto & tile = map->getTile(hero->visitablePos());
  1118. if (tile.terType->isWater())
  1119. {
  1120. auto handler = VLC->objtypeh->getHandlerFor(Obj::BOAT, hero->getBoatType().getNum());
  1121. CGBoat * boat = dynamic_cast<CGBoat*>(handler->create());
  1122. handler->configureObject(boat, gs->getRandomGenerator());
  1123. boat->ID = Obj::BOAT;
  1124. boat->subID = hero->getBoatType().getNum();
  1125. boat->pos = hero->pos;
  1126. boat->appearance = handler->getTemplates().front();
  1127. boat->id = ObjectInstanceID(static_cast<si32>(gs->map->objects.size()));
  1128. map->objects.emplace_back(boat);
  1129. map->addBlockVisTiles(boat);
  1130. boat->hero = hero;
  1131. hero->boat = boat;
  1132. }
  1133. }
  1134. for(auto obj : map->objects) //prisons
  1135. {
  1136. if(obj && obj->ID == Obj::PRISON)
  1137. map->allHeroes[obj->subID] = dynamic_cast<CGHeroInstance*>(obj.get());
  1138. }
  1139. std::set<HeroTypeID> heroesToCreate = getUnusedAllowedHeroes(); //ids of heroes to be created and put into the pool
  1140. for(auto ph : map->predefinedHeroes)
  1141. {
  1142. if(!vstd::contains(heroesToCreate, HeroTypeID(ph->subID)))
  1143. continue;
  1144. ph->initHero(getRandomGenerator());
  1145. hpool.heroesPool[ph->subID] = ph;
  1146. hpool.pavailable[ph->subID] = 0xff;
  1147. heroesToCreate.erase(ph->type->getId());
  1148. map->allHeroes[ph->subID] = ph;
  1149. }
  1150. for(const HeroTypeID & htype : heroesToCreate) //all not used allowed heroes go with default state into the pool
  1151. {
  1152. auto * vhi = new CGHeroInstance();
  1153. vhi->initHero(getRandomGenerator(), htype);
  1154. int typeID = htype.getNum();
  1155. map->allHeroes[typeID] = vhi;
  1156. hpool.heroesPool[typeID] = vhi;
  1157. hpool.pavailable[typeID] = 0xff;
  1158. }
  1159. for(auto & elem : map->disposedHeroes)
  1160. {
  1161. hpool.pavailable[elem.heroId] = elem.players;
  1162. }
  1163. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1164. {
  1165. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1166. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->info1 != 0xFFFE) //exclude generated heroes
  1167. {
  1168. //find human player
  1169. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  1170. for (auto & elem : players)
  1171. {
  1172. if(elem.second.human)
  1173. {
  1174. humanPlayer = elem.first;
  1175. break;
  1176. }
  1177. }
  1178. assert(humanPlayer != PlayerColor::NEUTRAL);
  1179. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1180. if (chosenBonus->info1 == 0xFFFD) //most powerful
  1181. {
  1182. int maxB = -1;
  1183. for (int b=0; b<heroes.size(); ++b)
  1184. {
  1185. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1186. {
  1187. maxB = b;
  1188. }
  1189. }
  1190. if(maxB < 0)
  1191. logGlobal->warn("Cannot give bonus to hero cause there are no heroes!");
  1192. else
  1193. giveCampaignBonusToHero(heroes[maxB]);
  1194. }
  1195. else //specific hero
  1196. {
  1197. for (auto & heroe : heroes)
  1198. {
  1199. if (heroe->subID == chosenBonus->info1)
  1200. {
  1201. giveCampaignBonusToHero(heroe);
  1202. break;
  1203. }
  1204. }
  1205. }
  1206. }
  1207. }
  1208. }
  1209. void CGameState::giveCampaignBonusToHero(CGHeroInstance * hero)
  1210. {
  1211. const std::optional<CScenarioTravel::STravelBonus> & curBonus = scenarioOps->campState->getBonusForCurrentMap();
  1212. if(!curBonus)
  1213. return;
  1214. if(curBonus->isBonusForHero())
  1215. {
  1216. //apply bonus
  1217. switch (curBonus->type)
  1218. {
  1219. case CScenarioTravel::STravelBonus::SPELL:
  1220. hero->addSpellToSpellbook(SpellID(curBonus->info2));
  1221. break;
  1222. case CScenarioTravel::STravelBonus::MONSTER:
  1223. {
  1224. for(int i=0; i<GameConstants::ARMY_SIZE; i++)
  1225. {
  1226. if(hero->slotEmpty(SlotID(i)))
  1227. {
  1228. hero->addToSlot(SlotID(i), CreatureID(curBonus->info2), curBonus->info3);
  1229. break;
  1230. }
  1231. }
  1232. }
  1233. break;
  1234. case CScenarioTravel::STravelBonus::ARTIFACT:
  1235. if(!gs->giveHeroArtifact(hero, static_cast<ArtifactID>(curBonus->info2)))
  1236. logGlobal->error("Cannot give starting artifact - no free slots!");
  1237. break;
  1238. case CScenarioTravel::STravelBonus::SPELL_SCROLL:
  1239. {
  1240. CArtifactInstance * scroll = ArtifactUtils::createScroll(SpellID(curBonus->info2));
  1241. const auto slot = ArtifactUtils::getArtAnyPosition(hero, scroll->getTypeId());
  1242. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  1243. scroll->putAt(ArtifactLocation(hero, slot));
  1244. else
  1245. logGlobal->error("Cannot give starting scroll - no free slots!");
  1246. }
  1247. break;
  1248. case CScenarioTravel::STravelBonus::PRIMARY_SKILL:
  1249. {
  1250. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus->info2);
  1251. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1252. {
  1253. int val = ptr[g];
  1254. if (val == 0)
  1255. {
  1256. continue;
  1257. }
  1258. auto bb = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::CAMPAIGN_BONUS, val, *scenarioOps->campState->currentMap, g);
  1259. hero->addNewBonus(bb);
  1260. }
  1261. }
  1262. break;
  1263. case CScenarioTravel::STravelBonus::SECONDARY_SKILL:
  1264. hero->setSecSkillLevel(SecondarySkill(curBonus->info2), curBonus->info3, true);
  1265. break;
  1266. }
  1267. }
  1268. }
  1269. void CGameState::initFogOfWar()
  1270. {
  1271. logGlobal->debug("\tFog of war"); //FIXME: should be initialized after all bonuses are set
  1272. int layers = map->levels();
  1273. for(auto & elem : teams)
  1274. {
  1275. auto fow = elem.second.fogOfWarMap;
  1276. fow->resize(boost::extents[layers][map->width][map->height]);
  1277. std::fill(fow->data(), fow->data() + fow->num_elements(), 0);
  1278. for(CGObjectInstance *obj : map->objects)
  1279. {
  1280. if(!obj || !vstd::contains(elem.second.players, obj->tempOwner)) continue; //not a flagged object
  1281. std::unordered_set<int3> tiles;
  1282. getTilesInRange(tiles, obj->getSightCenter(), obj->getSightRadius(), obj->tempOwner, 1);
  1283. for(const int3 & tile : tiles)
  1284. {
  1285. (*elem.second.fogOfWarMap)[tile.z][tile.x][tile.y] = 1;
  1286. }
  1287. }
  1288. }
  1289. }
  1290. void CGameState::initStartingBonus()
  1291. {
  1292. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1293. return;
  1294. // These are the single scenario bonuses; predefined
  1295. // campaign bonuses are spread out over other init* functions.
  1296. logGlobal->debug("\tStarting bonuses");
  1297. for(auto & elem : players)
  1298. {
  1299. //starting bonus
  1300. if(scenarioOps->playerInfos[elem.first].bonus==PlayerSettings::RANDOM)
  1301. scenarioOps->playerInfos[elem.first].bonus = static_cast<PlayerSettings::Ebonus>(getRandomGenerator().nextInt(2));
  1302. switch(scenarioOps->playerInfos[elem.first].bonus)
  1303. {
  1304. case PlayerSettings::GOLD:
  1305. elem.second.resources[EGameResID::GOLD] += getRandomGenerator().nextInt(5, 10) * 100;
  1306. break;
  1307. case PlayerSettings::RESOURCE:
  1308. {
  1309. auto res = (*VLC->townh)[scenarioOps->playerInfos[elem.first].castle]->town->primaryRes;
  1310. if(res == EGameResID::WOOD_AND_ORE)
  1311. {
  1312. int amount = getRandomGenerator().nextInt(5, 10);
  1313. elem.second.resources[EGameResID::WOOD] += amount;
  1314. elem.second.resources[EGameResID::ORE] += amount;
  1315. }
  1316. else
  1317. {
  1318. elem.second.resources[res] += getRandomGenerator().nextInt(3, 6);
  1319. }
  1320. break;
  1321. }
  1322. case PlayerSettings::ARTIFACT:
  1323. {
  1324. if(elem.second.heroes.empty())
  1325. {
  1326. logGlobal->error("Cannot give starting artifact - no heroes!");
  1327. break;
  1328. }
  1329. const Artifact * toGive = VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE).toArtifact(VLC->artifacts());
  1330. CGHeroInstance *hero = elem.second.heroes[0];
  1331. if(!giveHeroArtifact(hero, toGive->getId()))
  1332. logGlobal->error("Cannot give starting artifact - no free slots!");
  1333. }
  1334. break;
  1335. }
  1336. }
  1337. }
  1338. void CGameState::initTowns()
  1339. {
  1340. logGlobal->debug("\tTowns");
  1341. //campaign bonuses for towns
  1342. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1343. {
  1344. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1345. if (chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::BUILDING)
  1346. {
  1347. for (int g=0; g<map->towns.size(); ++g)
  1348. {
  1349. PlayerState * owner = getPlayerState(map->towns[g]->getOwner());
  1350. if (owner)
  1351. {
  1352. PlayerInfo & pi = map->players[owner->color.getNum()];
  1353. if (owner->human && //human-owned
  1354. map->towns[g]->pos == pi.posOfMainTown)
  1355. {
  1356. BuildingID buildingId;
  1357. if(scenarioOps->campState->camp->header.version == CampaignVersion::VCMI)
  1358. buildingId = BuildingID(chosenBonus->info1);
  1359. else
  1360. buildingId = CBuildingHandler::campToERMU(chosenBonus->info1, map->towns[g]->subID, map->towns[g]->builtBuildings);
  1361. map->towns[g]->builtBuildings.insert(buildingId);
  1362. break;
  1363. }
  1364. }
  1365. }
  1366. }
  1367. }
  1368. CGTownInstance::universitySkills.clear();
  1369. for ( int i=0; i<4; i++)
  1370. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1371. for (auto & elem : map->towns)
  1372. {
  1373. CGTownInstance * vti =(elem);
  1374. if(!vti->town)
  1375. {
  1376. vti->town = (*VLC->townh)[vti->subID]->town;
  1377. }
  1378. if(vti->getNameTranslated().empty())
  1379. {
  1380. size_t nameID = getRandomGenerator().nextInt(vti->getTown()->getRandomNamesCount() - 1);
  1381. vti->setNameTranslated(vti->getTown()->getRandomNameTranslated(nameID));
  1382. }
  1383. static const BuildingID basicDwellings[] = { BuildingID::DWELL_FIRST, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3, BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7 };
  1384. static const BuildingID upgradedDwellings[] = { BuildingID::DWELL_UP_FIRST, BuildingID::DWELL_LVL_2_UP, BuildingID::DWELL_LVL_3_UP, BuildingID::DWELL_LVL_4_UP, BuildingID::DWELL_LVL_5_UP, BuildingID::DWELL_LVL_6_UP, BuildingID::DWELL_LVL_7_UP };
  1385. static const BuildingID hordes[] = { BuildingID::HORDE_PLACEHOLDER1, BuildingID::HORDE_PLACEHOLDER2, BuildingID::HORDE_PLACEHOLDER3, BuildingID::HORDE_PLACEHOLDER4, BuildingID::HORDE_PLACEHOLDER5, BuildingID::HORDE_PLACEHOLDER6, BuildingID::HORDE_PLACEHOLDER7 };
  1386. //init buildings
  1387. if(vstd::contains(vti->builtBuildings, BuildingID::DEFAULT)) //give standard set of buildings
  1388. {
  1389. vti->builtBuildings.erase(BuildingID::DEFAULT);
  1390. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1391. if(vti->tempOwner != PlayerColor::NEUTRAL)
  1392. vti->builtBuildings.insert(BuildingID::TAVERN);
  1393. auto definesBuildingsChances = VLC->settings()->getVector(EGameSettings::TOWNS_STARTING_DWELLING_CHANCES);
  1394. for(int i = 0; i < definesBuildingsChances.size(); i++)
  1395. {
  1396. if((getRandomGenerator().nextInt(1,100) <= definesBuildingsChances[i]))
  1397. {
  1398. vti->builtBuildings.insert(basicDwellings[i]);
  1399. }
  1400. }
  1401. }
  1402. // village hall must always exist
  1403. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1404. //init hordes
  1405. for (int i = 0; i < GameConstants::CREATURES_PER_TOWN; i++)
  1406. {
  1407. if (vstd::contains(vti->builtBuildings, hordes[i])) //if we have horde for this level
  1408. {
  1409. vti->builtBuildings.erase(hordes[i]);//remove old ID
  1410. if (vti->getTown()->hordeLvl.at(0) == i)//if town first horde is this one
  1411. {
  1412. vti->builtBuildings.insert(BuildingID::HORDE_1);//add it
  1413. //if we have upgraded dwelling as well
  1414. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  1415. vti->builtBuildings.insert(BuildingID::HORDE_1_UPGR);//add it as well
  1416. }
  1417. if (vti->getTown()->hordeLvl.at(1) == i)//if town second horde is this one
  1418. {
  1419. vti->builtBuildings.insert(BuildingID::HORDE_2);
  1420. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  1421. vti->builtBuildings.insert(BuildingID::HORDE_2_UPGR);
  1422. }
  1423. }
  1424. }
  1425. //#1444 - remove entries that don't have buildings defined (like some unused extra town hall buildings)
  1426. //But DO NOT remove horde placeholders before they are replaced
  1427. vstd::erase_if(vti->builtBuildings, [vti](const BuildingID & bid)
  1428. {
  1429. return !vti->getTown()->buildings.count(bid) || !vti->getTown()->buildings.at(bid);
  1430. });
  1431. if (vstd::contains(vti->builtBuildings, BuildingID::SHIPYARD) && vti->shipyardStatus()==IBoatGenerator::TILE_BLOCKED)
  1432. vti->builtBuildings.erase(BuildingID::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  1433. //Early check for #1444-like problems
  1434. for([[maybe_unused]] const auto & building : vti->builtBuildings)
  1435. {
  1436. assert(vti->getTown()->buildings.at(building) != nullptr);
  1437. }
  1438. //town events
  1439. for(CCastleEvent &ev : vti->events)
  1440. {
  1441. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1442. if (vstd::contains(ev.buildings,hordes[i])) //if we have horde for this level
  1443. {
  1444. ev.buildings.erase(hordes[i]);
  1445. if (vti->getTown()->hordeLvl.at(0) == i)
  1446. ev.buildings.insert(BuildingID::HORDE_1);
  1447. if (vti->getTown()->hordeLvl.at(1) == i)
  1448. ev.buildings.insert(BuildingID::HORDE_2);
  1449. }
  1450. }
  1451. //init spells
  1452. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1453. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1454. {
  1455. const auto * s = vti->obligatorySpells[z].toSpell();
  1456. vti->spells[s->level-1].push_back(s->id);
  1457. vti->possibleSpells -= s->id;
  1458. }
  1459. while(!vti->possibleSpells.empty())
  1460. {
  1461. ui32 total=0;
  1462. int sel = -1;
  1463. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1464. total += vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  1465. if (total == 0) // remaining spells have 0 probability
  1466. break;
  1467. auto r = getRandomGenerator().nextInt(total - 1);
  1468. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1469. {
  1470. r -= vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  1471. if(r<0)
  1472. {
  1473. sel = ps;
  1474. break;
  1475. }
  1476. }
  1477. if(sel<0)
  1478. sel=0;
  1479. const auto * s = vti->possibleSpells[sel].toSpell();
  1480. vti->spells[s->level-1].push_back(s->id);
  1481. vti->possibleSpells -= s->id;
  1482. }
  1483. vti->possibleSpells.clear();
  1484. if(vti->getOwner() != PlayerColor::NEUTRAL)
  1485. getPlayerState(vti->getOwner())->towns.emplace_back(vti);
  1486. }
  1487. }
  1488. void CGameState::initMapObjects()
  1489. {
  1490. logGlobal->debug("\tObject initialization");
  1491. // objCaller->preInit();
  1492. for(CGObjectInstance *obj : map->objects)
  1493. {
  1494. if(obj)
  1495. {
  1496. logGlobal->trace("Calling Init for object %d, %s, %s", obj->id.getNum(), obj->typeName, obj->subTypeName);
  1497. obj->initObj(getRandomGenerator());
  1498. }
  1499. }
  1500. for(CGObjectInstance *obj : map->objects)
  1501. {
  1502. if(!obj)
  1503. continue;
  1504. switch (obj->ID)
  1505. {
  1506. case Obj::QUEST_GUARD:
  1507. case Obj::SEER_HUT:
  1508. {
  1509. auto * q = dynamic_cast<CGSeerHut *>(obj);
  1510. assert (q);
  1511. q->setObjToKill();
  1512. }
  1513. }
  1514. }
  1515. CGSubterraneanGate::postInit(); //pairing subterranean gates
  1516. map->calculateGuardingGreaturePositions(); //calculate once again when all the guards are placed and initialized
  1517. }
  1518. void CGameState::placeHeroesInTowns()
  1519. {
  1520. for(auto & player : players)
  1521. {
  1522. if(player.first == PlayerColor::NEUTRAL)
  1523. continue;
  1524. for(CGHeroInstance * h : player.second.heroes)
  1525. {
  1526. for(CGTownInstance * t : player.second.towns)
  1527. {
  1528. if(h->visitablePos().z != t->visitablePos().z)
  1529. continue;
  1530. bool heroOnTownBlockableTile = t->blockingAt(h->visitablePos().x, h->visitablePos().y);
  1531. // current hero position is at one of blocking tiles of current town
  1532. // assume that this hero should be visiting the town (H3M format quirk) and move hero to correct position
  1533. if (heroOnTownBlockableTile)
  1534. {
  1535. int3 correctedPos = h->convertFromVisitablePos(t->visitablePos());
  1536. map->removeBlockVisTiles(h);
  1537. h->pos = correctedPos;
  1538. map->addBlockVisTiles(h);
  1539. assert(t->visitableAt(h->visitablePos().x, h->visitablePos().y));
  1540. }
  1541. }
  1542. }
  1543. }
  1544. }
  1545. void CGameState::initVisitingAndGarrisonedHeroes()
  1546. {
  1547. for(auto & player : players)
  1548. {
  1549. if(player.first == PlayerColor::NEUTRAL)
  1550. continue;
  1551. //init visiting and garrisoned heroes
  1552. for(CGHeroInstance * h : player.second.heroes)
  1553. {
  1554. for(CGTownInstance * t : player.second.towns)
  1555. {
  1556. if(h->visitablePos().z != t->visitablePos().z)
  1557. continue;
  1558. if (t->visitableAt(h->visitablePos().x, h->visitablePos().y))
  1559. {
  1560. assert(t->visitingHero == nullptr);
  1561. t->setVisitingHero(h);
  1562. }
  1563. }
  1564. }
  1565. }
  1566. for (auto hero : map->heroesOnMap)
  1567. {
  1568. if (hero->visitedTown)
  1569. {
  1570. assert (hero->visitedTown->visitingHero == hero);
  1571. }
  1572. }
  1573. }
  1574. BattleField CGameState::battleGetBattlefieldType(int3 tile, CRandomGenerator & rand)
  1575. {
  1576. if(!tile.valid() && curB)
  1577. tile = curB->tile;
  1578. else if(!tile.valid() && !curB)
  1579. return BattleField::NONE;
  1580. const TerrainTile &t = map->getTile(tile);
  1581. auto * topObject = t.visitableObjects.front();
  1582. if(topObject && topObject->getBattlefield() != BattleField::NONE)
  1583. {
  1584. return topObject->getBattlefield();
  1585. }
  1586. for(auto &obj : map->objects)
  1587. {
  1588. //look only for objects covering given tile
  1589. if( !obj || obj->pos.z != tile.z || !obj->coveringAt(tile.x, tile.y))
  1590. continue;
  1591. auto customBattlefield = obj->getBattlefield();
  1592. if(customBattlefield != BattleField::NONE)
  1593. return customBattlefield;
  1594. }
  1595. if(map->isCoastalTile(tile)) //coastal tile is always ground
  1596. return BattleField::fromString("sand_shore");
  1597. return BattleField(*RandomGeneratorUtil::nextItem(t.terType->battleFields, rand));
  1598. }
  1599. void CGameState::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  1600. {
  1601. assert(obj);
  1602. assert(obj->hasStackAtSlot(stackPos));
  1603. out = fillUpgradeInfo(obj->getStack(stackPos));
  1604. }
  1605. UpgradeInfo CGameState::fillUpgradeInfo(const CStackInstance &stack) const
  1606. {
  1607. UpgradeInfo ret;
  1608. const CCreature *base = stack.type;
  1609. if (stack.armyObj->ID == Obj::HERO)
  1610. {
  1611. auto hero = dynamic_cast<const CGHeroInstance *>(stack.armyObj);
  1612. hero->fillUpgradeInfo(ret, stack);
  1613. if (hero->visitedTown)
  1614. {
  1615. hero->visitedTown->fillUpgradeInfo(ret, stack);
  1616. }
  1617. else
  1618. {
  1619. auto object = vstd::frontOrNull(getVisitableObjs(hero->visitablePos()));
  1620. auto upgradeSource = dynamic_cast<const ICreatureUpgrader*>(object);
  1621. if (object != hero && upgradeSource != nullptr)
  1622. upgradeSource->fillUpgradeInfo(ret, stack);
  1623. }
  1624. }
  1625. if (stack.armyObj->ID == Obj::TOWN)
  1626. {
  1627. auto town = dynamic_cast<const CGTownInstance *>(stack.armyObj);
  1628. town->fillUpgradeInfo(ret, stack);
  1629. }
  1630. if(!ret.newID.empty())
  1631. ret.oldID = base->getId();
  1632. for (ResourceSet &cost : ret.cost)
  1633. cost.positive(); //upgrade cost can't be negative, ignore missing resources
  1634. return ret;
  1635. }
  1636. PlayerRelations::PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  1637. {
  1638. if ( color1 == color2 )
  1639. return PlayerRelations::SAME_PLAYER;
  1640. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  1641. return PlayerRelations::ENEMIES;
  1642. const TeamState * ts = getPlayerTeam(color1);
  1643. if (ts && vstd::contains(ts->players, color2))
  1644. return PlayerRelations::ALLIES;
  1645. return PlayerRelations::ENEMIES;
  1646. }
  1647. void CGameState::apply(CPack *pack)
  1648. {
  1649. ui16 typ = typeList.getTypeID(pack);
  1650. applier->getApplier(typ)->applyOnGS(this, pack);
  1651. }
  1652. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out)
  1653. {
  1654. calculatePaths(std::make_shared<SingleHeroPathfinderConfig>(out, this, hero));
  1655. }
  1656. void CGameState::calculatePaths(const std::shared_ptr<PathfinderConfig> & config)
  1657. {
  1658. //FIXME: creating pathfinder is costly, maybe reset / clear is enough?
  1659. CPathfinder pathfinder(this, config);
  1660. pathfinder.calculatePaths();
  1661. }
  1662. /**
  1663. * Tells if the tile is guarded by a monster as well as the position
  1664. * of the monster that will attack on it.
  1665. *
  1666. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1667. * the monster guarding the tile.
  1668. */
  1669. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1670. {
  1671. std::vector<CGObjectInstance*> guards;
  1672. const int3 originalPos = pos;
  1673. if (!map->isInTheMap(pos))
  1674. return guards;
  1675. const TerrainTile &posTile = map->getTile(pos);
  1676. if (posTile.visitable)
  1677. {
  1678. for (CGObjectInstance* obj : posTile.visitableObjects)
  1679. {
  1680. if(obj->blockVisit)
  1681. {
  1682. if (obj->ID == Obj::MONSTER) // Monster
  1683. guards.push_back(obj);
  1684. }
  1685. }
  1686. }
  1687. pos -= int3(1, 1, 0); // Start with top left.
  1688. for (int dx = 0; dx < 3; dx++)
  1689. {
  1690. for (int dy = 0; dy < 3; dy++)
  1691. {
  1692. if (map->isInTheMap(pos))
  1693. {
  1694. const auto & tile = map->getTile(pos);
  1695. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1696. {
  1697. for (CGObjectInstance* obj : tile.visitableObjects)
  1698. {
  1699. if (obj->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1700. {
  1701. guards.push_back(obj);
  1702. }
  1703. }
  1704. }
  1705. }
  1706. pos.y++;
  1707. }
  1708. pos.y -= 3;
  1709. pos.x++;
  1710. }
  1711. return guards;
  1712. }
  1713. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1714. {
  1715. return gs->map->guardingCreaturePositions[pos.z][pos.x][pos.y];
  1716. }
  1717. void CGameState::updateRumor()
  1718. {
  1719. static std::vector<RumorState::ERumorType> rumorTypes = {RumorState::TYPE_MAP, RumorState::TYPE_SPECIAL, RumorState::TYPE_RAND, RumorState::TYPE_RAND};
  1720. std::vector<RumorState::ERumorTypeSpecial> sRumorTypes = {
  1721. RumorState::RUMOR_OBELISKS, RumorState::RUMOR_ARTIFACTS, RumorState::RUMOR_ARMY, RumorState::RUMOR_INCOME};
  1722. if(map->grailPos.valid()) // Grail should always be on map, but I had related crash I didn't manage to reproduce
  1723. sRumorTypes.push_back(RumorState::RUMOR_GRAIL);
  1724. int rumorId = -1;
  1725. int rumorExtra = -1;
  1726. auto & rand = getRandomGenerator();
  1727. rumor.type = *RandomGeneratorUtil::nextItem(rumorTypes, rand);
  1728. do
  1729. {
  1730. switch(rumor.type)
  1731. {
  1732. case RumorState::TYPE_SPECIAL:
  1733. {
  1734. SThievesGuildInfo tgi;
  1735. obtainPlayersStats(tgi, 20);
  1736. rumorId = *RandomGeneratorUtil::nextItem(sRumorTypes, rand);
  1737. if(rumorId == RumorState::RUMOR_GRAIL)
  1738. {
  1739. rumorExtra = getTile(map->grailPos)->terType->getIndex();
  1740. break;
  1741. }
  1742. std::vector<PlayerColor> players = {};
  1743. switch(rumorId)
  1744. {
  1745. case RumorState::RUMOR_OBELISKS:
  1746. players = tgi.obelisks[0];
  1747. break;
  1748. case RumorState::RUMOR_ARTIFACTS:
  1749. players = tgi.artifacts[0];
  1750. break;
  1751. case RumorState::RUMOR_ARMY:
  1752. players = tgi.army[0];
  1753. break;
  1754. case RumorState::RUMOR_INCOME:
  1755. players = tgi.income[0];
  1756. break;
  1757. }
  1758. rumorExtra = RandomGeneratorUtil::nextItem(players, rand)->getNum();
  1759. break;
  1760. }
  1761. case RumorState::TYPE_MAP:
  1762. // Makes sure that map rumors only used if there enough rumors too choose from
  1763. if(!map->rumors.empty() && (map->rumors.size() > 1 || !rumor.last.count(RumorState::TYPE_MAP)))
  1764. {
  1765. rumorId = rand.nextInt((int)map->rumors.size() - 1);
  1766. break;
  1767. }
  1768. else
  1769. rumor.type = RumorState::TYPE_RAND;
  1770. [[fallthrough]];
  1771. case RumorState::TYPE_RAND:
  1772. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randtvrn");
  1773. rumorId = rand.nextInt((int)vector.size() - 1);
  1774. break;
  1775. }
  1776. }
  1777. while(!rumor.update(rumorId, rumorExtra));
  1778. }
  1779. bool CGameState::isVisible(int3 pos, const std::optional<PlayerColor> & player) const
  1780. {
  1781. if (!map->isInTheMap(pos))
  1782. return false;
  1783. if (!player)
  1784. return true;
  1785. if(player == PlayerColor::NEUTRAL)
  1786. return false;
  1787. if(player->isSpectator())
  1788. return true;
  1789. return (*getPlayerTeam(*player)->fogOfWarMap)[pos.z][pos.x][pos.y];
  1790. }
  1791. bool CGameState::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const
  1792. {
  1793. if(!player)
  1794. return true;
  1795. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  1796. if (player == obj->tempOwner)
  1797. return true;
  1798. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1799. return false;
  1800. //object is visible when at least one blocked tile is visible
  1801. for(int fy=0; fy < obj->getHeight(); ++fy)
  1802. {
  1803. for(int fx=0; fx < obj->getWidth(); ++fx)
  1804. {
  1805. int3 pos = obj->pos + int3(-fx, -fy, 0);
  1806. if ( map->isInTheMap(pos) &&
  1807. obj->coveringAt(pos.x, pos.y) &&
  1808. isVisible(pos, *player))
  1809. return true;
  1810. }
  1811. }
  1812. return false;
  1813. }
  1814. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1815. {
  1816. const TerrainTile * pom = &map->getTile(dst);
  1817. return map->checkForVisitableDir(src, pom, dst);
  1818. }
  1819. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(const PlayerColor & player) const
  1820. {
  1821. const MetaString messageWonSelf = MetaString::createFromTextID("core.genrltxt.659");
  1822. const MetaString messageWonOther = MetaString::createFromTextID("core.genrltxt.5");
  1823. const MetaString messageLostSelf = MetaString::createFromTextID("core.genrltxt.7");
  1824. const MetaString messageLostOther = MetaString::createFromTextID("core.genrltxt.8");
  1825. auto evaluateEvent = [=](const EventCondition & condition)
  1826. {
  1827. return this->checkForVictory(player, condition);
  1828. };
  1829. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1830. //cheater or tester, but has entered the code...
  1831. if (p->enteredWinningCheatCode)
  1832. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  1833. if (p->enteredLosingCheatCode)
  1834. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1835. for (const TriggeredEvent & event : map->triggeredEvents)
  1836. {
  1837. if (event.trigger.test(evaluateEvent))
  1838. {
  1839. if (event.effect.type == EventEffect::VICTORY)
  1840. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  1841. if (event.effect.type == EventEffect::DEFEAT)
  1842. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  1843. }
  1844. }
  1845. if (checkForStandardLoss(player))
  1846. {
  1847. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1848. }
  1849. return EVictoryLossCheckResult();
  1850. }
  1851. bool CGameState::checkForVictory(const PlayerColor & player, const EventCondition & condition) const
  1852. {
  1853. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1854. switch (condition.condition)
  1855. {
  1856. case EventCondition::STANDARD_WIN:
  1857. {
  1858. return player == checkForStandardWin();
  1859. }
  1860. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  1861. {
  1862. for(const auto & elem : p->heroes)
  1863. if(elem->hasArt(ArtifactID(condition.objectType)))
  1864. return true;
  1865. return false;
  1866. }
  1867. case EventCondition::HAVE_CREATURES:
  1868. {
  1869. //check if in players armies there is enough creatures
  1870. int total = 0; //creature counter
  1871. for(auto object : map->objects)
  1872. {
  1873. const CArmedInstance *ai = nullptr;
  1874. if(object
  1875. && object->tempOwner == player //object controlled by player
  1876. && (ai = dynamic_cast<const CArmedInstance *>(object.get()))) //contains army
  1877. {
  1878. for(const auto & elem : ai->Slots()) //iterate through army
  1879. if(elem.second->type->getId() == condition.objectType) //it's searched creature
  1880. total += elem.second->count;
  1881. }
  1882. }
  1883. return total >= condition.value;
  1884. }
  1885. case EventCondition::HAVE_RESOURCES:
  1886. {
  1887. return p->resources[condition.objectType] >= condition.value;
  1888. }
  1889. case EventCondition::HAVE_BUILDING:
  1890. {
  1891. if (condition.object) // specific town
  1892. {
  1893. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  1894. return (t->tempOwner == player && t->hasBuilt(BuildingID(condition.objectType)));
  1895. }
  1896. else // any town
  1897. {
  1898. for (const CGTownInstance * t : p->towns)
  1899. {
  1900. if (t->hasBuilt(BuildingID(condition.objectType)))
  1901. return true;
  1902. }
  1903. return false;
  1904. }
  1905. }
  1906. case EventCondition::DESTROY:
  1907. {
  1908. if (condition.object) // mode A - destroy specific object of this type
  1909. {
  1910. if(const auto * hero = dynamic_cast<const CGHeroInstance *>(condition.object))
  1911. return boost::range::find(gs->map->heroesOnMap, hero) == gs->map->heroesOnMap.end();
  1912. else
  1913. return getObj(condition.object->id) == nullptr;
  1914. }
  1915. else
  1916. {
  1917. for(const auto & elem : map->objects) // mode B - destroy all objects of this type
  1918. {
  1919. if(elem && elem->ID == condition.objectType)
  1920. return false;
  1921. }
  1922. return true;
  1923. }
  1924. }
  1925. case EventCondition::CONTROL:
  1926. {
  1927. // list of players that need to control object to fulfull condition
  1928. // NOTE: cgameinfocallback specified explicitly in order to get const version
  1929. const auto & team = CGameInfoCallback::getPlayerTeam(player)->players;
  1930. if (condition.object) // mode A - flag one specific object, like town
  1931. {
  1932. return team.count(condition.object->tempOwner) != 0;
  1933. }
  1934. else
  1935. {
  1936. for(const auto & elem : map->objects) // mode B - flag all objects of this type
  1937. {
  1938. //check not flagged objs
  1939. if ( elem && elem->ID == condition.objectType && team.count(elem->tempOwner) == 0 )
  1940. return false;
  1941. }
  1942. return true;
  1943. }
  1944. }
  1945. case EventCondition::TRANSPORT:
  1946. {
  1947. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  1948. return (t->visitingHero && t->visitingHero->hasArt(ArtifactID(condition.objectType))) ||
  1949. (t->garrisonHero && t->garrisonHero->hasArt(ArtifactID(condition.objectType)));
  1950. }
  1951. case EventCondition::DAYS_PASSED:
  1952. {
  1953. return (si32)gs->day > condition.value;
  1954. }
  1955. case EventCondition::IS_HUMAN:
  1956. {
  1957. return p->human ? condition.value == 1 : condition.value == 0;
  1958. }
  1959. case EventCondition::DAYS_WITHOUT_TOWN:
  1960. {
  1961. if (p->daysWithoutCastle)
  1962. return p->daysWithoutCastle >= condition.value;
  1963. else
  1964. return false;
  1965. }
  1966. case EventCondition::CONST_VALUE:
  1967. {
  1968. return condition.value; // just convert to bool
  1969. }
  1970. case EventCondition::HAVE_0:
  1971. {
  1972. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1973. //TODO: support new condition format
  1974. return false;
  1975. }
  1976. case EventCondition::HAVE_BUILDING_0:
  1977. {
  1978. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1979. //TODO: support new condition format
  1980. return false;
  1981. }
  1982. case EventCondition::DESTROY_0:
  1983. {
  1984. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1985. //TODO: support new condition format
  1986. return false;
  1987. }
  1988. default:
  1989. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  1990. return false;
  1991. }
  1992. }
  1993. PlayerColor CGameState::checkForStandardWin() const
  1994. {
  1995. //std victory condition is:
  1996. //all enemies lost
  1997. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  1998. TeamID winnerTeam = TeamID::NO_TEAM;
  1999. for(const auto & elem : players)
  2000. {
  2001. if(elem.second.status == EPlayerStatus::INGAME && elem.first < PlayerColor::PLAYER_LIMIT)
  2002. {
  2003. if(supposedWinner == PlayerColor::NEUTRAL)
  2004. {
  2005. //first player remaining ingame - candidate for victory
  2006. supposedWinner = elem.second.color;
  2007. winnerTeam = elem.second.team;
  2008. }
  2009. else if(winnerTeam != elem.second.team)
  2010. {
  2011. //current candidate has enemy remaining in game -> no vicotry
  2012. return PlayerColor::NEUTRAL;
  2013. }
  2014. }
  2015. }
  2016. return supposedWinner;
  2017. }
  2018. bool CGameState::checkForStandardLoss(const PlayerColor & player) const
  2019. {
  2020. //std loss condition is: player lost all towns and heroes
  2021. const PlayerState & pState = *CGameInfoCallback::getPlayerState(player);
  2022. return pState.checkVanquished();
  2023. }
  2024. struct statsHLP
  2025. {
  2026. using TStat = std::pair<PlayerColor, si64>;
  2027. //converts [<player's color, value>] to vec[place] -> platers
  2028. static std::vector< std::vector< PlayerColor > > getRank( std::vector<TStat> stats )
  2029. {
  2030. std::sort(stats.begin(), stats.end(), statsHLP());
  2031. //put first element
  2032. std::vector< std::vector<PlayerColor> > ret;
  2033. std::vector<PlayerColor> tmp;
  2034. tmp.push_back( stats[0].first );
  2035. ret.push_back( tmp );
  2036. //the rest of elements
  2037. for(int g=1; g<stats.size(); ++g)
  2038. {
  2039. if(stats[g].second == stats[g-1].second)
  2040. {
  2041. (ret.end()-1)->push_back( stats[g].first );
  2042. }
  2043. else
  2044. {
  2045. //create next occupied rank
  2046. std::vector<PlayerColor> tmp;
  2047. tmp.push_back(stats[g].first);
  2048. ret.push_back(tmp);
  2049. }
  2050. }
  2051. return ret;
  2052. }
  2053. bool operator()(const TStat & a, const TStat & b) const
  2054. {
  2055. return a.second > b.second;
  2056. }
  2057. static const CGHeroInstance * findBestHero(CGameState * gs, const PlayerColor & color)
  2058. {
  2059. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2060. if(h.empty())
  2061. return nullptr;
  2062. //best hero will be that with highest exp
  2063. int best = 0;
  2064. for(int b=1; b<h.size(); ++b)
  2065. {
  2066. if(h[b]->exp > h[best]->exp)
  2067. {
  2068. best = b;
  2069. }
  2070. }
  2071. return h[best];
  2072. }
  2073. //calculates total number of artifacts that belong to given player
  2074. static int getNumberOfArts(const PlayerState * ps)
  2075. {
  2076. int ret = 0;
  2077. for(auto h : ps->heroes)
  2078. {
  2079. ret += (int)h->artifactsInBackpack.size() + (int)h->artifactsWorn.size();
  2080. }
  2081. return ret;
  2082. }
  2083. // get total strength of player army
  2084. static si64 getArmyStrength(const PlayerState * ps)
  2085. {
  2086. si64 str = 0;
  2087. for(auto h : ps->heroes)
  2088. {
  2089. if(!h->inTownGarrison) //original h3 behavior
  2090. str += h->getArmyStrength();
  2091. }
  2092. return str;
  2093. }
  2094. // get total gold income
  2095. static int getIncome(const PlayerState * ps)
  2096. {
  2097. int totalIncome = 0;
  2098. const CGObjectInstance * heroOrTown = nullptr;
  2099. //Heroes can produce gold as well - skill, specialty or arts
  2100. for(const auto & h : ps->heroes)
  2101. {
  2102. totalIncome += h->valOfBonuses(Selector::typeSubtype(BonusType::GENERATE_RESOURCE, GameResID(EGameResID::GOLD)));
  2103. if(!heroOrTown)
  2104. heroOrTown = h;
  2105. }
  2106. //Add town income of all towns
  2107. for(const auto & t : ps->towns)
  2108. {
  2109. totalIncome += t->dailyIncome()[EGameResID::GOLD];
  2110. if(!heroOrTown)
  2111. heroOrTown = t;
  2112. }
  2113. /// FIXME: Dirty dirty hack
  2114. /// Stats helper need some access to gamestate.
  2115. std::vector<const CGObjectInstance *> ownedObjects;
  2116. for(const CGObjectInstance * obj : heroOrTown->cb->gameState()->map->objects)
  2117. {
  2118. if(obj && obj->tempOwner == ps->color)
  2119. ownedObjects.push_back(obj);
  2120. }
  2121. /// This is code from CPlayerSpecificInfoCallback::getMyObjects
  2122. /// I'm really need to find out about callback interface design...
  2123. for(const auto * object : ownedObjects)
  2124. {
  2125. //Mines
  2126. if ( object->ID == Obj::MINE )
  2127. {
  2128. const auto * mine = dynamic_cast<const CGMine *>(object);
  2129. assert(mine);
  2130. if (mine->producedResource == EGameResID::GOLD)
  2131. totalIncome += mine->producedQuantity;
  2132. }
  2133. }
  2134. return totalIncome;
  2135. }
  2136. };
  2137. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2138. {
  2139. auto playerInactive = [&](const PlayerColor & color)
  2140. {
  2141. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  2142. };
  2143. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2144. { \
  2145. std::vector< std::pair< PlayerColor, si64 > > stats; \
  2146. for(auto g = players.begin(); g != players.end(); ++g) \
  2147. { \
  2148. if(playerInactive(g->second.color)) \
  2149. continue; \
  2150. std::pair< PlayerColor, si64 > stat; \
  2151. stat.first = g->second.color; \
  2152. stat.second = VAL_GETTER; \
  2153. stats.push_back(stat); \
  2154. } \
  2155. tgi.FIELD = statsHLP::getRank(stats); \
  2156. }
  2157. for(auto & elem : players)
  2158. {
  2159. if(!playerInactive(elem.second.color))
  2160. tgi.playerColors.push_back(elem.second.color);
  2161. }
  2162. if(level >= 0) //num of towns & num of heroes
  2163. {
  2164. //num of towns
  2165. FILL_FIELD(numOfTowns, g->second.towns.size())
  2166. //num of heroes
  2167. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2168. }
  2169. if(level >= 1) //best hero's portrait
  2170. {
  2171. for(const auto & player : players)
  2172. {
  2173. if(playerInactive(player.second.color))
  2174. continue;
  2175. const CGHeroInstance * best = statsHLP::findBestHero(this, player.second.color);
  2176. InfoAboutHero iah;
  2177. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  2178. iah.army.clear();
  2179. tgi.colorToBestHero[player.second.color] = iah;
  2180. }
  2181. }
  2182. if(level >= 2) //gold
  2183. {
  2184. FILL_FIELD(gold, g->second.resources[EGameResID::GOLD])
  2185. }
  2186. if(level >= 2) //wood & ore
  2187. {
  2188. FILL_FIELD(woodOre, g->second.resources[EGameResID::WOOD] + g->second.resources[EGameResID::ORE])
  2189. }
  2190. if(level >= 3) //mercury, sulfur, crystal, gems
  2191. {
  2192. FILL_FIELD(mercSulfCrystGems, g->second.resources[EGameResID::MERCURY] + g->second.resources[EGameResID::SULFUR] + g->second.resources[EGameResID::CRYSTAL] + g->second.resources[EGameResID::GEMS])
  2193. }
  2194. if(level >= 3) //obelisks found
  2195. {
  2196. auto getObeliskVisited = [](const TeamID & t)
  2197. {
  2198. if(CGObelisk::visited.count(t))
  2199. return CGObelisk::visited[t];
  2200. else
  2201. return ui8(0);
  2202. };
  2203. FILL_FIELD(obelisks, getObeliskVisited(gs->getPlayerTeam(g->second.color)->id))
  2204. }
  2205. if(level >= 4) //artifacts
  2206. {
  2207. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2208. }
  2209. if(level >= 4) //army strength
  2210. {
  2211. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  2212. }
  2213. if(level >= 5) //income
  2214. {
  2215. FILL_FIELD(income, statsHLP::getIncome(&g->second))
  2216. }
  2217. if(level >= 2) //best hero's stats
  2218. {
  2219. //already set in lvl 1 handling
  2220. }
  2221. if(level >= 3) //personality
  2222. {
  2223. for(const auto & player : players)
  2224. {
  2225. if(playerInactive(player.second.color)) //do nothing for neutral player
  2226. continue;
  2227. if(player.second.human)
  2228. {
  2229. tgi.personality[player.second.color] = EAiTactic::NONE;
  2230. }
  2231. else //AI
  2232. {
  2233. tgi.personality[player.second.color] = map->players[player.second.color.getNum()].aiTactic;
  2234. }
  2235. }
  2236. }
  2237. if(level >= 4) //best creature
  2238. {
  2239. //best creatures belonging to player (highest AI value)
  2240. for(const auto & player : players)
  2241. {
  2242. if(playerInactive(player.second.color)) //do nothing for neutral player
  2243. continue;
  2244. int bestCre = -1; //best creature's ID
  2245. for(const auto & elem : player.second.heroes)
  2246. {
  2247. for(const auto & it : elem->Slots())
  2248. {
  2249. int toCmp = it.second->type->getId(); //ID of creature we should compare with the best one
  2250. if(bestCre == -1 || VLC->creh->objects[bestCre]->getAIValue() < VLC->creh->objects[toCmp]->getAIValue())
  2251. {
  2252. bestCre = toCmp;
  2253. }
  2254. }
  2255. }
  2256. tgi.bestCreature[player.second.color] = bestCre;
  2257. }
  2258. }
  2259. #undef FILL_FIELD
  2260. }
  2261. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2262. {
  2263. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2264. for(const auto & player : players)
  2265. for(auto availableHero : player.second.availableHeroes)
  2266. if(availableHero)
  2267. pool.erase((*availableHero).subID);
  2268. return pool;
  2269. }
  2270. void CGameState::buildBonusSystemTree()
  2271. {
  2272. buildGlobalTeamPlayerTree();
  2273. attachArmedObjects();
  2274. for(CGTownInstance *t : map->towns)
  2275. {
  2276. t->deserializationFix();
  2277. }
  2278. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2279. // are provided on initializing / deserializing
  2280. // NOTE: calling deserializationFix() might be more correct option, but might lead to side effects
  2281. for (auto hero : map->heroesOnMap)
  2282. hero->boatDeserializationFix();
  2283. }
  2284. void CGameState::deserializationFix()
  2285. {
  2286. buildGlobalTeamPlayerTree();
  2287. attachArmedObjects();
  2288. }
  2289. void CGameState::buildGlobalTeamPlayerTree()
  2290. {
  2291. for(auto & team : teams)
  2292. {
  2293. TeamState * t = &team.second;
  2294. t->attachTo(globalEffects);
  2295. for(const PlayerColor & teamMember : team.second.players)
  2296. {
  2297. PlayerState *p = getPlayerState(teamMember);
  2298. assert(p);
  2299. p->attachTo(*t);
  2300. }
  2301. }
  2302. }
  2303. void CGameState::attachArmedObjects()
  2304. {
  2305. for(CGObjectInstance *obj : map->objects)
  2306. {
  2307. if(auto * armed = dynamic_cast<CArmedInstance *>(obj))
  2308. {
  2309. armed->whatShouldBeAttached().attachTo(armed->whereShouldBeAttached(this));
  2310. }
  2311. }
  2312. }
  2313. bool CGameState::giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid)
  2314. {
  2315. CArtifact * const artifact = VLC->arth->objects[aid]; //pointer to constant object
  2316. CArtifactInstance * ai = ArtifactUtils::createNewArtifactInstance(artifact);
  2317. map->addNewArtifactInstance(ai);
  2318. auto slot = ArtifactUtils::getArtAnyPosition(h, aid);
  2319. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  2320. {
  2321. ai->putAt(ArtifactLocation(h, slot));
  2322. return true;
  2323. }
  2324. else
  2325. {
  2326. return false;
  2327. }
  2328. }
  2329. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  2330. {
  2331. std::set<HeroTypeID> ret;
  2332. for(int i = 0; i < map->allowedHeroes.size(); i++)
  2333. if(map->allowedHeroes[i] || alsoIncludeNotAllowed)
  2334. ret.insert(HeroTypeID(i));
  2335. for(const auto & playerSettingPair : scenarioOps->playerInfos) //remove uninitialized yet heroes picked for start by other players
  2336. {
  2337. if(playerSettingPair.second.hero != PlayerSettings::RANDOM)
  2338. ret -= HeroTypeID(playerSettingPair.second.hero);
  2339. }
  2340. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2341. {
  2342. if(hero->type)
  2343. ret -= hero->type->getId();
  2344. else
  2345. ret -= HeroTypeID(hero->subID);
  2346. }
  2347. for(auto obj : map->objects) //prisons
  2348. if(obj && obj->ID == Obj::PRISON)
  2349. ret -= HeroTypeID(obj->subID);
  2350. return ret;
  2351. }
  2352. std::vector<CGameState::CampaignHeroReplacement> CGameState::generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes)
  2353. {
  2354. std::vector<CampaignHeroReplacement> campaignHeroReplacements;
  2355. //selecting heroes by type
  2356. for(auto obj : map->objects)
  2357. {
  2358. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2359. {
  2360. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2361. if(heroPlaceholder->subID != 0xFF) //select by type
  2362. {
  2363. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [heroPlaceholder](CGHeroInstance * hero)
  2364. {
  2365. return hero->subID == heroPlaceholder->subID;
  2366. });
  2367. if(it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  2368. {
  2369. auto * hero = *it;
  2370. crossoverHeroes.removeHeroFromBothLists(hero);
  2371. campaignHeroReplacements.emplace_back(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id);
  2372. }
  2373. }
  2374. }
  2375. }
  2376. //selecting heroes by power
  2377. range::sort(crossoverHeroes.heroesFromPreviousScenario, [](const CGHeroInstance * a, const CGHeroInstance * b)
  2378. {
  2379. return a->getHeroStrength() > b->getHeroStrength();
  2380. }); //sort, descending strength
  2381. // sort hero placeholders descending power
  2382. std::vector<CGHeroPlaceholder *> heroPlaceholders;
  2383. for(auto obj : map->objects)
  2384. {
  2385. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2386. {
  2387. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2388. if(heroPlaceholder->subID == 0xFF) //select by power
  2389. {
  2390. heroPlaceholders.push_back(heroPlaceholder);
  2391. }
  2392. }
  2393. }
  2394. range::sort(heroPlaceholders, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  2395. {
  2396. return a->power > b->power;
  2397. });
  2398. for(int i = 0; i < heroPlaceholders.size(); ++i)
  2399. {
  2400. auto * heroPlaceholder = heroPlaceholders[i];
  2401. if(crossoverHeroes.heroesFromPreviousScenario.size() > i)
  2402. {
  2403. auto * hero = crossoverHeroes.heroesFromPreviousScenario[i];
  2404. campaignHeroReplacements.emplace_back(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id);
  2405. }
  2406. }
  2407. return campaignHeroReplacements;
  2408. }
  2409. void CGameState::replaceHeroesPlaceholders(const std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements)
  2410. {
  2411. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  2412. {
  2413. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(getObjInstance(campaignHeroReplacement.heroPlaceholderId));
  2414. CGHeroInstance *heroToPlace = campaignHeroReplacement.hero;
  2415. heroToPlace->id = campaignHeroReplacement.heroPlaceholderId;
  2416. heroToPlace->tempOwner = heroPlaceholder->tempOwner;
  2417. heroToPlace->pos = heroPlaceholder->pos;
  2418. heroToPlace->type = VLC->heroh->objects[heroToPlace->subID];
  2419. heroToPlace->appearance = VLC->objtypeh->getHandlerFor(Obj::HERO,
  2420. heroToPlace->type->heroClass->getIndex())->getTemplates().front();
  2421. for(auto &&i : heroToPlace->stacks)
  2422. i.second->type = VLC->creh->objects[i.second->getCreatureID()];
  2423. auto fixArtifact = [&](CArtifactInstance * art)
  2424. {
  2425. art->artType = VLC->arth->objects[art->artType->getId()];
  2426. gs->map->artInstances.emplace_back(art);
  2427. art->id = ArtifactInstanceID((si32)gs->map->artInstances.size() - 1);
  2428. };
  2429. for(auto &&i : heroToPlace->artifactsWorn)
  2430. fixArtifact(i.second.artifact);
  2431. for(auto &&i : heroToPlace->artifactsInBackpack)
  2432. fixArtifact(i.artifact);
  2433. map->removeBlockVisTiles(heroPlaceholder, true);
  2434. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  2435. map->instanceNames.erase(heroPlaceholder->instanceName);
  2436. map->heroesOnMap.emplace_back(heroToPlace);
  2437. map->objects[heroToPlace->id.getNum()] = heroToPlace;
  2438. map->addBlockVisTiles(heroToPlace);
  2439. map->instanceNames[heroToPlace->instanceName] = heroToPlace;
  2440. delete heroPlaceholder;
  2441. scenarioOps->campState->getCurrentScenario().placedCrossoverHeroes.push_back(CCampaignState::crossoverSerialize(heroToPlace));
  2442. }
  2443. }
  2444. bool CGameState::isUsedHero(const HeroTypeID & hid) const
  2445. {
  2446. return getUsedHero(hid);
  2447. }
  2448. CGHeroInstance * CGameState::getUsedHero(const HeroTypeID & hid) const
  2449. {
  2450. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2451. {
  2452. if(hero->type && hero->type->getId() == hid)
  2453. {
  2454. return hero;
  2455. }
  2456. }
  2457. for(auto obj : map->objects) //prisons
  2458. {
  2459. if(obj && obj->ID == Obj::PRISON )
  2460. {
  2461. auto * hero = dynamic_cast<CGHeroInstance *>(obj.get());
  2462. assert(hero);
  2463. if ( hero->type && hero->type->getId() == hid )
  2464. return hero;
  2465. }
  2466. }
  2467. return nullptr;
  2468. }
  2469. bool RumorState::update(int id, int extra)
  2470. {
  2471. if(vstd::contains(last, type))
  2472. {
  2473. if(last[type].first != id)
  2474. {
  2475. last[type].first = id;
  2476. last[type].second = extra;
  2477. }
  2478. else
  2479. return false;
  2480. }
  2481. else
  2482. last[type] = std::make_pair(id, extra);
  2483. return true;
  2484. }
  2485. InfoAboutArmy::InfoAboutArmy():
  2486. owner(PlayerColor::NEUTRAL)
  2487. {}
  2488. InfoAboutArmy::InfoAboutArmy(const CArmedInstance *Army, bool detailed)
  2489. {
  2490. initFromArmy(Army, detailed);
  2491. }
  2492. void InfoAboutArmy::initFromArmy(const CArmedInstance *Army, bool detailed)
  2493. {
  2494. army = ArmyDescriptor(Army, detailed);
  2495. owner = Army->tempOwner;
  2496. name = Army->getObjectName();
  2497. }
  2498. void InfoAboutHero::assign(const InfoAboutHero & iah)
  2499. {
  2500. vstd::clear_pointer(details);
  2501. InfoAboutArmy::operator = (iah);
  2502. details = (iah.details ? new Details(*iah.details) : nullptr);
  2503. hclass = iah.hclass;
  2504. portrait = iah.portrait;
  2505. }
  2506. InfoAboutHero::InfoAboutHero(): portrait(-1) {}
  2507. InfoAboutHero::InfoAboutHero(const InfoAboutHero & iah): InfoAboutArmy(iah)
  2508. {
  2509. assign(iah);
  2510. }
  2511. InfoAboutHero::InfoAboutHero(const CGHeroInstance * h, InfoAboutHero::EInfoLevel infoLevel):
  2512. portrait(-1)
  2513. {
  2514. initFromHero(h, infoLevel);
  2515. }
  2516. InfoAboutHero::~InfoAboutHero()
  2517. {
  2518. vstd::clear_pointer(details);
  2519. }
  2520. InfoAboutHero & InfoAboutHero::operator=(const InfoAboutHero & iah)
  2521. {
  2522. assign(iah);
  2523. return *this;
  2524. }
  2525. void InfoAboutHero::initFromHero(const CGHeroInstance *h, InfoAboutHero::EInfoLevel infoLevel)
  2526. {
  2527. vstd::clear_pointer(details);
  2528. if(!h)
  2529. return;
  2530. bool detailed = ( (infoLevel == EInfoLevel::DETAILED) || (infoLevel == EInfoLevel::INBATTLE) );
  2531. initFromArmy(h, detailed);
  2532. hclass = h->type->heroClass;
  2533. name = h->getNameTranslated();
  2534. portrait = h->portrait;
  2535. if(detailed)
  2536. {
  2537. //include details about hero
  2538. details = new Details();
  2539. details->luck = h->luckVal();
  2540. details->morale = h->moraleVal();
  2541. details->mana = h->mana;
  2542. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2543. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2544. {
  2545. details->primskills[i] = h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i));
  2546. }
  2547. if (infoLevel == EInfoLevel::INBATTLE)
  2548. details->manaLimit = h->manaLimit();
  2549. else
  2550. details->manaLimit = -1; //we do not want to leak max mana info outside battle so set to meaningless value
  2551. }
  2552. }
  2553. InfoAboutTown::InfoAboutTown():
  2554. details(nullptr),
  2555. tType(nullptr),
  2556. built(0),
  2557. fortLevel(0)
  2558. {
  2559. }
  2560. InfoAboutTown::InfoAboutTown(const CGTownInstance *t, bool detailed):
  2561. details(nullptr),
  2562. tType(nullptr),
  2563. built(0),
  2564. fortLevel(0)
  2565. {
  2566. initFromTown(t, detailed);
  2567. }
  2568. InfoAboutTown::~InfoAboutTown()
  2569. {
  2570. vstd::clear_pointer(details);
  2571. }
  2572. void InfoAboutTown::initFromTown(const CGTownInstance *t, bool detailed)
  2573. {
  2574. initFromArmy(t, detailed);
  2575. army = ArmyDescriptor(t->getUpperArmy(), detailed);
  2576. built = t->builded;
  2577. fortLevel = t->fortLevel();
  2578. name = t->getNameTranslated();
  2579. tType = t->getTown();
  2580. vstd::clear_pointer(details);
  2581. if(detailed)
  2582. {
  2583. //include details about hero
  2584. details = new Details();
  2585. TResources income = t->dailyIncome();
  2586. details->goldIncome = income[EGameResID::GOLD];
  2587. details->customRes = t->hasBuilt(BuildingID::RESOURCE_SILO);
  2588. details->hallLevel = t->hallLevel();
  2589. details->garrisonedHero = t->garrisonHero;
  2590. }
  2591. }
  2592. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2593. : isDetailed(detailed)
  2594. {
  2595. for(const auto & elem : army->Slots())
  2596. {
  2597. if(detailed)
  2598. (*this)[elem.first] = *elem.second;
  2599. else
  2600. (*this)[elem.first] = CStackBasicDescriptor(elem.second->type, (int)elem.second->getQuantityID());
  2601. }
  2602. }
  2603. ArmyDescriptor::ArmyDescriptor()
  2604. : isDetailed(false)
  2605. {
  2606. }
  2607. int ArmyDescriptor::getStrength() const
  2608. {
  2609. ui64 ret = 0;
  2610. if(isDetailed)
  2611. {
  2612. for(const auto & elem : *this)
  2613. ret += elem.second.type->getAIValue() * elem.second.count;
  2614. }
  2615. else
  2616. {
  2617. for(const auto & elem : *this)
  2618. ret += elem.second.type->getAIValue() * CCreature::estimateCreatureCount(elem.second.count);
  2619. }
  2620. return static_cast<int>(ret);
  2621. }
  2622. TeamState::TeamState()
  2623. {
  2624. setNodeType(TEAM);
  2625. fogOfWarMap = std::make_shared<boost::multi_array<ui8, 3>>();
  2626. }
  2627. TeamState::TeamState(TeamState && other) noexcept:
  2628. CBonusSystemNode(std::move(other)),
  2629. id(other.id)
  2630. {
  2631. std::swap(players, other.players);
  2632. std::swap(fogOfWarMap, other.fogOfWarMap);
  2633. }
  2634. CRandomGenerator & CGameState::getRandomGenerator()
  2635. {
  2636. return rand;
  2637. }
  2638. VCMI_LIB_NAMESPACE_END