CGameState.cpp 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193
  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 "EVictoryLossCheckResult.h"
  13. #include "InfoAboutArmy.h"
  14. #include "TavernHeroesPool.h"
  15. #include "CGameStateCampaign.h"
  16. #include "SThievesGuildInfo.h"
  17. #include "../ArtifactUtils.h"
  18. #include "../CBuildingHandler.h"
  19. #include "../CGeneralTextHandler.h"
  20. #include "../CHeroHandler.h"
  21. #include "../CPlayerState.h"
  22. #include "../CStopWatch.h"
  23. #include "../GameSettings.h"
  24. #include "../StartInfo.h"
  25. #include "../TerrainHandler.h"
  26. #include "../VCMIDirs.h"
  27. #include "../VCMI_Lib.h"
  28. #include "../battle/BattleInfo.h"
  29. #include "../campaign/CampaignState.h"
  30. #include "../filesystem/ResourcePath.h"
  31. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  32. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  33. #include "../mapObjectConstructors/DwellingInstanceConstructor.h"
  34. #include "../mapObjects/CGHeroInstance.h"
  35. #include "../mapObjects/CGTownInstance.h"
  36. #include "../mapping/CMap.h"
  37. #include "../mapping/CMapEditManager.h"
  38. #include "../mapping/CMapService.h"
  39. #include "../modding/IdentifierStorage.h"
  40. #include "../pathfinder/CPathfinder.h"
  41. #include "../pathfinder/PathfinderOptions.h"
  42. #include "../registerTypes/RegisterTypes.h"
  43. #include "../rmg/CMapGenerator.h"
  44. #include "../serializer/CMemorySerializer.h"
  45. #include "../serializer/CTypeList.h"
  46. #include "../spells/CSpellHandler.h"
  47. VCMI_LIB_NAMESPACE_BEGIN
  48. boost::shared_mutex CGameState::mutex;
  49. template <typename T> class CApplyOnGS;
  50. class CBaseForGSApply
  51. {
  52. public:
  53. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  54. virtual ~CBaseForGSApply() = default;
  55. template<typename U> static CBaseForGSApply *getApplier(const U * t=nullptr)
  56. {
  57. return new CApplyOnGS<U>();
  58. }
  59. };
  60. template <typename T> class CApplyOnGS : public CBaseForGSApply
  61. {
  62. public:
  63. void applyOnGS(CGameState *gs, void *pack) const override
  64. {
  65. T *ptr = static_cast<T*>(pack);
  66. boost::unique_lock<boost::shared_mutex> lock(CGameState::mutex);
  67. ptr->applyGs(gs);
  68. }
  69. };
  70. static CGObjectInstance * createObject(const Obj & id, int subid, const int3 & pos, const PlayerColor & owner)
  71. {
  72. CGObjectInstance * nobj;
  73. switch(id)
  74. {
  75. case Obj::HERO:
  76. {
  77. auto handler = VLC->objtypeh->getHandlerFor(id, VLC->heroh->objects[subid]->heroClass->getIndex());
  78. nobj = handler->create(handler->getTemplates().front());
  79. break;
  80. }
  81. case Obj::TOWN:
  82. nobj = new CGTownInstance();
  83. break;
  84. default: //rest of objects
  85. nobj = new CGObjectInstance();
  86. break;
  87. }
  88. nobj->ID = id;
  89. nobj->subID = subid;
  90. nobj->pos = pos;
  91. nobj->tempOwner = owner;
  92. if (id != Obj::HERO)
  93. nobj->appearance = VLC->objtypeh->getHandlerFor(id, subid)->getTemplates().front();
  94. return nobj;
  95. }
  96. HeroTypeID CGameState::pickNextHeroType(const PlayerColor & owner)
  97. {
  98. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  99. if(ps.hero >= HeroTypeID(0) && !isUsedHero(HeroTypeID(ps.hero))) //we haven't used selected hero
  100. {
  101. return HeroTypeID(ps.hero);
  102. }
  103. return pickUnusedHeroTypeRandomly(owner);
  104. }
  105. HeroTypeID CGameState::pickUnusedHeroTypeRandomly(const PlayerColor & owner)
  106. {
  107. //list of available heroes for this faction and others
  108. std::vector<HeroTypeID> factionHeroes;
  109. std::vector<HeroTypeID> otherHeroes;
  110. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  111. for(const HeroTypeID & hid : getUnusedAllowedHeroes())
  112. {
  113. if(VLC->heroh->objects[hid.getNum()]->heroClass->faction == ps.castle)
  114. factionHeroes.push_back(hid);
  115. else
  116. otherHeroes.push_back(hid);
  117. }
  118. // select random hero native to "our" faction
  119. if(!factionHeroes.empty())
  120. {
  121. return *RandomGeneratorUtil::nextItem(factionHeroes, getRandomGenerator());
  122. }
  123. logGlobal->warn("Cannot find free hero of appropriate faction for player %s - trying to get first available...", owner.toString());
  124. if(!otherHeroes.empty())
  125. {
  126. return *RandomGeneratorUtil::nextItem(otherHeroes, getRandomGenerator());
  127. }
  128. logGlobal->error("No free allowed heroes!");
  129. auto notAllowedHeroesButStillBetterThanCrash = getUnusedAllowedHeroes(true);
  130. if(!notAllowedHeroesButStillBetterThanCrash.empty())
  131. return *notAllowedHeroesButStillBetterThanCrash.begin();
  132. logGlobal->error("No free heroes at all!");
  133. assert(0); //current code can't handle this situation
  134. return HeroTypeID::NONE; // no available heroes at all
  135. }
  136. std::pair<Obj,int> CGameState::pickObject (CGObjectInstance *obj)
  137. {
  138. switch(obj->ID)
  139. {
  140. case Obj::RANDOM_ART:
  141. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  142. case Obj::RANDOM_TREASURE_ART:
  143. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE));
  144. case Obj::RANDOM_MINOR_ART:
  145. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_MINOR));
  146. case Obj::RANDOM_MAJOR_ART:
  147. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_MAJOR));
  148. case Obj::RANDOM_RELIC_ART:
  149. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_RELIC));
  150. case Obj::RANDOM_HERO:
  151. return std::make_pair(Obj::HERO, pickNextHeroType(obj->tempOwner));
  152. case Obj::RANDOM_MONSTER:
  153. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator()));
  154. case Obj::RANDOM_MONSTER_L1:
  155. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 1));
  156. case Obj::RANDOM_MONSTER_L2:
  157. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 2));
  158. case Obj::RANDOM_MONSTER_L3:
  159. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 3));
  160. case Obj::RANDOM_MONSTER_L4:
  161. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 4));
  162. case Obj::RANDOM_RESOURCE:
  163. return std::make_pair(Obj::RESOURCE,getRandomGenerator().nextInt(6)); //now it's OH3 style, use %8 for mithril
  164. case Obj::RANDOM_TOWN:
  165. {
  166. PlayerColor align = (dynamic_cast<CGTownInstance *>(obj))->alignmentToPlayer;
  167. si32 f; // can be negative (for random)
  168. if(!align.isValidPlayer()) //same as owner / random
  169. {
  170. if(!obj->tempOwner.isValidPlayer())
  171. f = -1; //random
  172. else
  173. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  174. }
  175. else
  176. {
  177. f = scenarioOps->getIthPlayersSettings(align).castle;
  178. }
  179. if(f<0)
  180. {
  181. do
  182. {
  183. f = getRandomGenerator().nextInt((int)VLC->townh->size() - 1);
  184. }
  185. while ((*VLC->townh)[f]->town == nullptr); // find playable faction
  186. }
  187. return std::make_pair(Obj::TOWN,f);
  188. }
  189. case Obj::RANDOM_MONSTER_L5:
  190. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 5));
  191. case Obj::RANDOM_MONSTER_L6:
  192. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 6));
  193. case Obj::RANDOM_MONSTER_L7:
  194. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 7));
  195. case Obj::RANDOM_DWELLING:
  196. case Obj::RANDOM_DWELLING_LVL:
  197. case Obj::RANDOM_DWELLING_FACTION:
  198. {
  199. auto * dwl = dynamic_cast<CGDwelling *>(obj);
  200. int faction;
  201. //if castle alignment available
  202. if(auto * info = dynamic_cast<CCreGenAsCastleInfo *>(dwl->info))
  203. {
  204. faction = getRandomGenerator().nextInt((int)VLC->townh->size() - 1);
  205. if(info->asCastle && !info->instanceId.empty())
  206. {
  207. auto iter = map->instanceNames.find(info->instanceId);
  208. if(iter == map->instanceNames.end())
  209. logGlobal->error("Map object not found: %s", info->instanceId);
  210. else
  211. {
  212. auto elem = iter->second;
  213. if(elem->ID==Obj::RANDOM_TOWN)
  214. {
  215. randomizeObject(elem.get()); //we have to randomize the castle first
  216. faction = elem->subID;
  217. }
  218. else if(elem->ID==Obj::TOWN)
  219. faction = elem->subID;
  220. else
  221. logGlobal->error("Map object must be town: %s", info->instanceId);
  222. }
  223. }
  224. else if(info->asCastle)
  225. {
  226. for(auto & elem : map->objects)
  227. {
  228. if(!elem)
  229. continue;
  230. if(elem->ID==Obj::RANDOM_TOWN
  231. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  232. {
  233. randomizeObject(elem); //we have to randomize the castle first
  234. faction = elem->subID;
  235. break;
  236. }
  237. else if(elem->ID==Obj::TOWN
  238. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  239. {
  240. faction = elem->subID;
  241. break;
  242. }
  243. }
  244. }
  245. else
  246. {
  247. std::set<int> temp;
  248. for(int i = 0; i < info->allowedFactions.size(); i++)
  249. if(info->allowedFactions[i])
  250. temp.insert(i);
  251. if(temp.empty())
  252. logGlobal->error("Random faction selection failed. Nothing is allowed. Fall back to random.");
  253. else
  254. faction = *RandomGeneratorUtil::nextItem(temp, getRandomGenerator());
  255. }
  256. }
  257. else // castle alignment fixed
  258. faction = obj->subID;
  259. int level;
  260. //if level set to range
  261. if(auto * info = dynamic_cast<CCreGenLeveledInfo *>(dwl->info))
  262. {
  263. level = getRandomGenerator().nextInt(info->minLevel, info->maxLevel) - 1;
  264. }
  265. else // fixed level
  266. {
  267. level = obj->subID;
  268. }
  269. delete dwl->info;
  270. dwl->info = nullptr;
  271. std::pair<Obj, int> result(Obj::NO_OBJ, -1);
  272. CreatureID cid;
  273. if((*VLC->townh)[faction]->town)
  274. cid = (*VLC->townh)[faction]->town->creatures[level][0];
  275. else
  276. {
  277. //neutral faction
  278. std::vector<CCreature*> possibleCreatures;
  279. std::copy_if(VLC->creh->objects.begin(), VLC->creh->objects.end(), std::back_inserter(possibleCreatures), [faction](const CCreature * c)
  280. {
  281. return c->getFaction().getNum() == faction;
  282. });
  283. assert(!possibleCreatures.empty());
  284. cid = (*RandomGeneratorUtil::nextItem(possibleCreatures, getRandomGenerator()))->getId();
  285. }
  286. //NOTE: this will pick last dwelling with this creature (Mantis #900)
  287. //check for block map equality is better but more complex solution
  288. auto testID = [&](const Obj & primaryID) -> void
  289. {
  290. auto dwellingIDs = VLC->objtypeh->knownSubObjects(primaryID);
  291. for (si32 entry : dwellingIDs)
  292. {
  293. const auto * handler = dynamic_cast<const DwellingInstanceConstructor *>(VLC->objtypeh->getHandlerFor(primaryID, entry).get());
  294. if (handler->producesCreature(VLC->creh->objects[cid]))
  295. result = std::make_pair(primaryID, entry);
  296. }
  297. };
  298. testID(Obj::CREATURE_GENERATOR1);
  299. if (result.first == Obj::NO_OBJ)
  300. testID(Obj::CREATURE_GENERATOR4);
  301. if (result.first == Obj::NO_OBJ)
  302. {
  303. logGlobal->error("Error: failed to find dwelling for %s of level %d", (*VLC->townh)[faction]->getNameTranslated(), int(level));
  304. result = std::make_pair(Obj::CREATURE_GENERATOR1, *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1), getRandomGenerator()));
  305. }
  306. return result;
  307. }
  308. }
  309. return std::make_pair(Obj::NO_OBJ,-1);
  310. }
  311. void CGameState::randomizeObject(CGObjectInstance *cur)
  312. {
  313. std::pair<Obj,int> ran = pickObject(cur);
  314. if(ran.first == Obj::NO_OBJ || ran.second<0) //this is not a random object, or we couldn't find anything
  315. {
  316. if(cur->ID==Obj::TOWN || cur->ID==Obj::MONSTER)
  317. cur->setType(cur->ID, cur->subID); // update def, if necessary
  318. }
  319. else if(ran.first==Obj::HERO)//special code for hero
  320. {
  321. auto * h = dynamic_cast<CGHeroInstance *>(cur);
  322. cur->setType(ran.first, ran.second);
  323. map->heroesOnMap.emplace_back(h);
  324. }
  325. else if(ran.first==Obj::TOWN)//special code for town
  326. {
  327. auto * t = dynamic_cast<CGTownInstance *>(cur);
  328. cur->setType(ran.first, ran.second);
  329. map->towns.emplace_back(t);
  330. }
  331. else
  332. {
  333. cur->setType(ran.first, ran.second);
  334. }
  335. }
  336. int CGameState::getDate(Date mode) const
  337. {
  338. int temp;
  339. switch (mode)
  340. {
  341. case Date::DAY:
  342. return day;
  343. case Date::DAY_OF_WEEK: //day of week
  344. temp = (day)%7; // 1 - Monday, 7 - Sunday
  345. return temp ? temp : 7;
  346. case Date::WEEK: //current week
  347. temp = ((day-1)/7)+1;
  348. if (!(temp%4))
  349. return 4;
  350. else
  351. return (temp%4);
  352. case Date::MONTH: //current month
  353. return ((day-1)/28)+1;
  354. case Date::DAY_OF_MONTH: //day of month
  355. temp = (day)%28;
  356. if (temp)
  357. return temp;
  358. else return 28;
  359. }
  360. return 0;
  361. }
  362. CGameState::CGameState()
  363. {
  364. gs = this;
  365. heroesPool = std::make_unique<TavernHeroesPool>();
  366. applier = std::make_shared<CApplier<CBaseForGSApply>>();
  367. registerTypesClientPacks1(*applier);
  368. registerTypesClientPacks2(*applier);
  369. globalEffects.setNodeType(CBonusSystemNode::GLOBAL_EFFECTS);
  370. }
  371. CGameState::~CGameState()
  372. {
  373. map.dellNull();
  374. }
  375. void CGameState::preInit(Services * services)
  376. {
  377. this->services = services;
  378. }
  379. void CGameState::init(const IMapService * mapService, StartInfo * si, Load::ProgressAccumulator & progressTracking, bool allowSavingRandomMap)
  380. {
  381. preInitAuto();
  382. logGlobal->info("\tUsing random seed: %d", si->seedToBeUsed);
  383. getRandomGenerator().setSeed(si->seedToBeUsed);
  384. scenarioOps = CMemorySerializer::deepCopy(*si).release();
  385. initialOpts = CMemorySerializer::deepCopy(*si).release();
  386. si = nullptr;
  387. switch(scenarioOps->mode)
  388. {
  389. case StartInfo::NEW_GAME:
  390. initNewGame(mapService, allowSavingRandomMap, progressTracking);
  391. break;
  392. case StartInfo::CAMPAIGN:
  393. initCampaign();
  394. break;
  395. default:
  396. logGlobal->error("Wrong mode: %d", static_cast<int>(scenarioOps->mode));
  397. return;
  398. }
  399. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  400. logGlobal->info("Map loaded!");
  401. checkMapChecksum();
  402. day = 0;
  403. logGlobal->debug("Initialization:");
  404. initGlobalBonuses();
  405. initPlayerStates();
  406. if (campaign)
  407. campaign->placeCampaignHeroes();
  408. removeHeroPlaceholders();
  409. initGrailPosition();
  410. initRandomFactionsForPlayers();
  411. randomizeMapObjects();
  412. placeStartingHeroes();
  413. initStartingResources();
  414. initHeroes();
  415. initStartingBonus();
  416. initTowns();
  417. placeHeroesInTowns();
  418. initMapObjects();
  419. buildBonusSystemTree();
  420. initVisitingAndGarrisonedHeroes();
  421. initFogOfWar();
  422. // Explicitly initialize static variables
  423. for(auto & elem : players)
  424. {
  425. CGKeys::playerKeyMap[elem.first] = std::set<ui8>();
  426. }
  427. for(auto & elem : teams)
  428. {
  429. CGObelisk::visited[elem.first] = 0;
  430. }
  431. logGlobal->debug("\tChecking objectives");
  432. map->checkForObjectives(); //needs to be run when all objects are properly placed
  433. auto seedAfterInit = getRandomGenerator().nextInt();
  434. logGlobal->info("Seed after init is %d (before was %d)", seedAfterInit, scenarioOps->seedToBeUsed);
  435. if(scenarioOps->seedPostInit > 0)
  436. {
  437. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  438. assert(scenarioOps->seedPostInit == seedAfterInit);
  439. }
  440. else
  441. {
  442. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  443. }
  444. }
  445. void CGameState::updateEntity(Metatype metatype, int32_t index, const JsonNode & data)
  446. {
  447. switch(metatype)
  448. {
  449. case Metatype::ARTIFACT_INSTANCE:
  450. logGlobal->error("Artifact instance update is not implemented");
  451. break;
  452. case Metatype::CREATURE_INSTANCE:
  453. logGlobal->error("Creature instance update is not implemented");
  454. break;
  455. case Metatype::HERO_INSTANCE:
  456. //index is hero type
  457. if(index >= 0 && index < map->allHeroes.size())
  458. {
  459. CGHeroInstance * hero = map->allHeroes.at(index);
  460. hero->updateFrom(data);
  461. }
  462. else
  463. {
  464. logGlobal->error("Update entity: hero index %s is out of range [%d,%d]", index, 0, map->allHeroes.size());
  465. }
  466. break;
  467. case Metatype::MAP_OBJECT_INSTANCE:
  468. if(index >= 0 && index < map->objects.size())
  469. {
  470. CGObjectInstance * obj = getObjInstance(ObjectInstanceID(index));
  471. obj->updateFrom(data);
  472. }
  473. else
  474. {
  475. logGlobal->error("Update entity: object index %s is out of range [%d,%d]", index, 0, map->objects.size());
  476. }
  477. break;
  478. default:
  479. services->updateEntity(metatype, index, data);
  480. break;
  481. }
  482. }
  483. void CGameState::updateOnLoad(StartInfo * si)
  484. {
  485. preInitAuto();
  486. scenarioOps->playerInfos = si->playerInfos;
  487. for(auto & i : si->playerInfos)
  488. gs->players[i.first].human = i.second.isControlledByHuman();
  489. }
  490. void CGameState::preInitAuto()
  491. {
  492. if(services == nullptr)
  493. {
  494. logGlobal->error("Game state preinit missing");
  495. preInit(VLC);
  496. }
  497. }
  498. void CGameState::initNewGame(const IMapService * mapService, bool allowSavingRandomMap, Load::ProgressAccumulator & progressTracking)
  499. {
  500. if(scenarioOps->createRandomMap())
  501. {
  502. logGlobal->info("Create random map.");
  503. CStopWatch sw;
  504. // Gen map
  505. CMapGenerator mapGenerator(*scenarioOps->mapGenOptions, scenarioOps->seedToBeUsed);
  506. progressTracking.include(mapGenerator);
  507. std::unique_ptr<CMap> randomMap = mapGenerator.generate();
  508. progressTracking.exclude(mapGenerator);
  509. if(allowSavingRandomMap)
  510. {
  511. try
  512. {
  513. auto path = VCMIDirs::get().userCachePath() / "RandomMaps";
  514. boost::filesystem::create_directories(path);
  515. std::shared_ptr<CMapGenOptions> options = scenarioOps->mapGenOptions;
  516. const std::string templateName = options->getMapTemplate()->getName();
  517. const ui32 seed = scenarioOps->seedToBeUsed;
  518. const std::string fileName = boost::str(boost::format("%s_%d.vmap") % templateName % seed );
  519. const auto fullPath = path / fileName;
  520. mapService->saveMap(randomMap, fullPath);
  521. logGlobal->info("Random map has been saved to:");
  522. logGlobal->info(fullPath.string());
  523. }
  524. catch(...)
  525. {
  526. logGlobal->error("Saving random map failed with exception");
  527. }
  528. }
  529. map = randomMap.release();
  530. // Update starting options
  531. for(int i = 0; i < map->players.size(); ++i)
  532. {
  533. const auto & playerInfo = map->players[i];
  534. if(playerInfo.canAnyonePlay())
  535. {
  536. PlayerSettings & playerSettings = scenarioOps->playerInfos[PlayerColor(i)];
  537. playerSettings.compOnly = !playerInfo.canHumanPlay;
  538. playerSettings.castle = playerInfo.defaultCastle();
  539. if(playerSettings.isControlledByAI() && playerSettings.name.empty())
  540. {
  541. playerSettings.name = VLC->generaltexth->allTexts[468];
  542. }
  543. playerSettings.color = PlayerColor(i);
  544. }
  545. else
  546. {
  547. scenarioOps->playerInfos.erase(PlayerColor(i));
  548. }
  549. }
  550. logGlobal->info("Generated random map in %i ms.", sw.getDiff());
  551. }
  552. else
  553. {
  554. logGlobal->info("Open map file: %s", scenarioOps->mapname);
  555. const ResourcePath mapURI(scenarioOps->mapname, EResType::MAP);
  556. map = mapService->loadMap(mapURI).release();
  557. }
  558. }
  559. void CGameState::initCampaign()
  560. {
  561. campaign = std::make_unique<CGameStateCampaign>(this);
  562. map = campaign->getCurrentMap().release();
  563. }
  564. void CGameState::checkMapChecksum()
  565. {
  566. logGlobal->info("\tOur checksum for the map: %d", map->checksum);
  567. if(scenarioOps->mapfileChecksum)
  568. {
  569. logGlobal->info("\tServer checksum for %s: %d", scenarioOps->mapname, scenarioOps->mapfileChecksum);
  570. if(map->checksum != scenarioOps->mapfileChecksum)
  571. {
  572. logGlobal->error("Wrong map checksum!!!");
  573. throw std::runtime_error("Wrong checksum");
  574. }
  575. }
  576. else
  577. {
  578. scenarioOps->mapfileChecksum = map->checksum;
  579. }
  580. }
  581. void CGameState::initGlobalBonuses()
  582. {
  583. const JsonNode & baseBonuses = VLC->settings()->getValue(EGameSettings::BONUSES_GLOBAL);
  584. logGlobal->debug("\tLoading global bonuses");
  585. for(const auto & b : baseBonuses.Struct())
  586. {
  587. auto bonus = JsonUtils::parseBonus(b.second);
  588. bonus->source = BonusSource::GLOBAL;//for all
  589. bonus->sid = -1; //there is one global object
  590. globalEffects.addNewBonus(bonus);
  591. }
  592. VLC->creh->loadCrExpBon(globalEffects);
  593. }
  594. void CGameState::initGrailPosition()
  595. {
  596. logGlobal->debug("\tPicking grail position");
  597. //pick grail location
  598. if(map->grailPos.x < 0 || map->grailRadius) //grail not set or set within a radius around some place
  599. {
  600. if(!map->grailRadius) //radius not given -> anywhere on map
  601. map->grailRadius = map->width * 2;
  602. std::vector<int3> allowedPos;
  603. static const int BORDER_WIDTH = 9; // grail must be at least 9 tiles away from border
  604. // add all not blocked tiles in range
  605. for (int z = 0; z < map->levels(); z++)
  606. {
  607. for(int x = BORDER_WIDTH; x < map->width - BORDER_WIDTH ; x++)
  608. {
  609. for(int y = BORDER_WIDTH; y < map->height - BORDER_WIDTH; y++)
  610. {
  611. const TerrainTile &t = map->getTile(int3(x, y, z));
  612. if(!t.blocked
  613. && !t.visitable
  614. && t.terType->isLand()
  615. && t.terType->isPassable()
  616. && (int)map->grailPos.dist2dSQ(int3(x, y, z)) <= (map->grailRadius * map->grailRadius))
  617. allowedPos.emplace_back(x, y, z);
  618. }
  619. }
  620. }
  621. //remove tiles with holes
  622. for(auto & elem : map->objects)
  623. if(elem && elem->ID == Obj::HOLE)
  624. allowedPos -= elem->pos;
  625. if(!allowedPos.empty())
  626. {
  627. map->grailPos = *RandomGeneratorUtil::nextItem(allowedPos, getRandomGenerator());
  628. }
  629. else
  630. {
  631. logGlobal->warn("Grail cannot be placed, no appropriate tile found!");
  632. }
  633. }
  634. }
  635. void CGameState::initRandomFactionsForPlayers()
  636. {
  637. logGlobal->debug("\tPicking random factions for players");
  638. for(auto & elem : scenarioOps->playerInfos)
  639. {
  640. if(elem.second.castle==FactionID::RANDOM)
  641. {
  642. auto randomID = getRandomGenerator().nextInt((int)map->players[elem.first.getNum()].allowedFactions.size() - 1);
  643. auto iter = map->players[elem.first.getNum()].allowedFactions.begin();
  644. std::advance(iter, randomID);
  645. elem.second.castle = *iter;
  646. }
  647. }
  648. }
  649. void CGameState::randomizeMapObjects()
  650. {
  651. logGlobal->debug("\tRandomizing objects");
  652. for(CGObjectInstance *obj : map->objects)
  653. {
  654. if(!obj) continue;
  655. randomizeObject(obj);
  656. //handle Favouring Winds - mark tiles under it
  657. if(obj->ID == Obj::FAVORABLE_WINDS)
  658. {
  659. for (int i = 0; i < obj->getWidth() ; i++)
  660. {
  661. for (int j = 0; j < obj->getHeight() ; j++)
  662. {
  663. int3 pos = obj->pos - int3(i,j,0);
  664. if(map->isInTheMap(pos)) map->getTile(pos).extTileFlags |= 128;
  665. }
  666. }
  667. }
  668. }
  669. }
  670. void CGameState::initPlayerStates()
  671. {
  672. logGlobal->debug("\tCreating player entries in gs");
  673. for(auto & elem : scenarioOps->playerInfos)
  674. {
  675. PlayerState & p = players[elem.first];
  676. p.color=elem.first;
  677. p.human = elem.second.isControlledByHuman();
  678. p.team = map->players[elem.first.getNum()].team;
  679. teams[p.team].id = p.team;//init team
  680. teams[p.team].players.insert(elem.first);//add player to team
  681. }
  682. }
  683. void CGameState::placeStartingHero(const PlayerColor & playerColor, const HeroTypeID & heroTypeId, int3 townPos)
  684. {
  685. for(auto town : map->towns)
  686. {
  687. if(town->getPosition() == townPos)
  688. {
  689. townPos = town->visitablePos();
  690. break;
  691. }
  692. }
  693. CGObjectInstance * hero = createObject(Obj::HERO, heroTypeId.getNum(), townPos, playerColor);
  694. hero->pos += hero->getVisitableOffset();
  695. map->getEditManager()->insertObject(hero);
  696. }
  697. void CGameState::placeStartingHeroes()
  698. {
  699. logGlobal->debug("\tGiving starting hero");
  700. for(auto & playerSettingPair : scenarioOps->playerInfos)
  701. {
  702. auto playerColor = playerSettingPair.first;
  703. auto & playerInfo = map->players[playerColor.getNum()];
  704. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  705. {
  706. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  707. if (campaign && campaign->playerHasStartingHero(playerColor))
  708. continue;
  709. int heroTypeId = pickNextHeroType(playerColor);
  710. if(playerSettingPair.second.hero == HeroTypeID::NONE)
  711. playerSettingPair.second.hero = heroTypeId;
  712. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  713. }
  714. }
  715. }
  716. void CGameState::removeHeroPlaceholders()
  717. {
  718. // remove any hero placeholders that remain on map after (potential) campaign heroes placement
  719. for(auto obj : map->objects)
  720. {
  721. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  722. {
  723. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  724. map->removeBlockVisTiles(heroPlaceholder, true);
  725. map->instanceNames.erase(obj->instanceName);
  726. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  727. delete heroPlaceholder;
  728. }
  729. }
  730. }
  731. void CGameState::initStartingResources()
  732. {
  733. logGlobal->debug("\tSetting up resources");
  734. const JsonNode config(JsonPath::builtin("config/startres.json"));
  735. const JsonVector &vector = config["difficulty"].Vector();
  736. const JsonNode &level = vector[scenarioOps->difficulty];
  737. TResources startresAI(level["ai"]);
  738. TResources startresHuman(level["human"]);
  739. for (auto & elem : players)
  740. {
  741. PlayerState &p = elem.second;
  742. if (p.human)
  743. p.resources = startresHuman;
  744. else
  745. p.resources = startresAI;
  746. }
  747. if (campaign)
  748. campaign->initStartingResources();
  749. }
  750. void CGameState::initHeroes()
  751. {
  752. for(auto hero : map->heroesOnMap) //heroes instances initialization
  753. {
  754. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  755. {
  756. logGlobal->warn("Hero with uninitialized owner!");
  757. continue;
  758. }
  759. hero->initHero(getRandomGenerator());
  760. getPlayerState(hero->getOwner())->heroes.push_back(hero);
  761. map->allHeroes[hero->type->getIndex()] = hero;
  762. }
  763. // generate boats for all heroes on water
  764. for(auto hero : map->heroesOnMap)
  765. {
  766. assert(map->isInTheMap(hero->visitablePos()));
  767. const auto & tile = map->getTile(hero->visitablePos());
  768. if (tile.terType->isWater())
  769. {
  770. auto handler = VLC->objtypeh->getHandlerFor(Obj::BOAT, hero->getBoatType().getNum());
  771. CGBoat * boat = dynamic_cast<CGBoat*>(handler->create());
  772. handler->configureObject(boat, gs->getRandomGenerator());
  773. boat->ID = Obj::BOAT;
  774. boat->subID = hero->getBoatType().getNum();
  775. boat->pos = hero->pos;
  776. boat->appearance = handler->getTemplates().front();
  777. boat->id = ObjectInstanceID(static_cast<si32>(gs->map->objects.size()));
  778. map->objects.emplace_back(boat);
  779. map->addBlockVisTiles(boat);
  780. hero->attachToBoat(boat);
  781. }
  782. }
  783. for(auto obj : map->objects) //prisons
  784. {
  785. if(obj && obj->ID == Obj::PRISON)
  786. map->allHeroes[obj->subID] = dynamic_cast<CGHeroInstance*>(obj.get());
  787. }
  788. std::set<HeroTypeID> heroesToCreate = getUnusedAllowedHeroes(); //ids of heroes to be created and put into the pool
  789. for(auto ph : map->predefinedHeroes)
  790. {
  791. if(!vstd::contains(heroesToCreate, HeroTypeID(ph->subID)))
  792. continue;
  793. ph->initHero(getRandomGenerator());
  794. heroesPool->addHeroToPool(ph);
  795. heroesToCreate.erase(ph->type->getId());
  796. map->allHeroes[ph->subID] = ph;
  797. }
  798. for(const HeroTypeID & htype : heroesToCreate) //all not used allowed heroes go with default state into the pool
  799. {
  800. auto * vhi = new CGHeroInstance();
  801. vhi->initHero(getRandomGenerator(), htype);
  802. int typeID = htype.getNum();
  803. map->allHeroes[typeID] = vhi;
  804. heroesPool->addHeroToPool(vhi);
  805. }
  806. for(auto & elem : map->disposedHeroes)
  807. heroesPool->setAvailability(elem.heroId, elem.players);
  808. if (campaign)
  809. campaign->initHeroes();
  810. }
  811. void CGameState::initFogOfWar()
  812. {
  813. logGlobal->debug("\tFog of war"); //FIXME: should be initialized after all bonuses are set
  814. int layers = map->levels();
  815. for(auto & elem : teams)
  816. {
  817. auto fow = elem.second.fogOfWarMap;
  818. fow->resize(boost::extents[layers][map->width][map->height]);
  819. std::fill(fow->data(), fow->data() + fow->num_elements(), 0);
  820. for(CGObjectInstance *obj : map->objects)
  821. {
  822. if(!obj || !vstd::contains(elem.second.players, obj->tempOwner)) continue; //not a flagged object
  823. std::unordered_set<int3> tiles;
  824. getTilesInRange(tiles, obj->getSightCenter(), obj->getSightRadius(), obj->tempOwner, 1);
  825. for(const int3 & tile : tiles)
  826. {
  827. (*elem.second.fogOfWarMap)[tile.z][tile.x][tile.y] = 1;
  828. }
  829. }
  830. }
  831. }
  832. void CGameState::initStartingBonus()
  833. {
  834. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  835. return;
  836. // These are the single scenario bonuses; predefined
  837. // campaign bonuses are spread out over other init* functions.
  838. logGlobal->debug("\tStarting bonuses");
  839. for(auto & elem : players)
  840. {
  841. //starting bonus
  842. if(scenarioOps->playerInfos[elem.first].bonus==PlayerSettings::RANDOM)
  843. scenarioOps->playerInfos[elem.first].bonus = static_cast<PlayerSettings::Ebonus>(getRandomGenerator().nextInt(2));
  844. switch(scenarioOps->playerInfos[elem.first].bonus)
  845. {
  846. case PlayerSettings::GOLD:
  847. elem.second.resources[EGameResID::GOLD] += getRandomGenerator().nextInt(5, 10) * 100;
  848. break;
  849. case PlayerSettings::RESOURCE:
  850. {
  851. auto res = (*VLC->townh)[scenarioOps->playerInfos[elem.first].castle]->town->primaryRes;
  852. if(res == EGameResID::WOOD_AND_ORE)
  853. {
  854. int amount = getRandomGenerator().nextInt(5, 10);
  855. elem.second.resources[EGameResID::WOOD] += amount;
  856. elem.second.resources[EGameResID::ORE] += amount;
  857. }
  858. else
  859. {
  860. elem.second.resources[res] += getRandomGenerator().nextInt(3, 6);
  861. }
  862. break;
  863. }
  864. case PlayerSettings::ARTIFACT:
  865. {
  866. if(elem.second.heroes.empty())
  867. {
  868. logGlobal->error("Cannot give starting artifact - no heroes!");
  869. break;
  870. }
  871. const Artifact * toGive = VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE).toArtifact(VLC->artifacts());
  872. CGHeroInstance *hero = elem.second.heroes[0];
  873. if(!giveHeroArtifact(hero, toGive->getId()))
  874. logGlobal->error("Cannot give starting artifact - no free slots!");
  875. }
  876. break;
  877. }
  878. }
  879. }
  880. void CGameState::initTowns()
  881. {
  882. logGlobal->debug("\tTowns");
  883. if (campaign)
  884. campaign->initTowns();
  885. CGTownInstance::universitySkills.clear();
  886. for ( int i=0; i<4; i++)
  887. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  888. for (auto & elem : map->towns)
  889. {
  890. CGTownInstance * vti =(elem);
  891. if(!vti->town)
  892. {
  893. vti->town = (*VLC->townh)[vti->subID]->town;
  894. }
  895. if(vti->getNameTranslated().empty())
  896. {
  897. size_t nameID = getRandomGenerator().nextInt(vti->getTown()->getRandomNamesCount() - 1);
  898. vti->setNameTranslated(vti->getTown()->getRandomNameTranslated(nameID));
  899. }
  900. 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 };
  901. 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 };
  902. 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 };
  903. //init buildings
  904. if(vstd::contains(vti->builtBuildings, BuildingID::DEFAULT)) //give standard set of buildings
  905. {
  906. vti->builtBuildings.erase(BuildingID::DEFAULT);
  907. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  908. if(vti->tempOwner != PlayerColor::NEUTRAL)
  909. vti->builtBuildings.insert(BuildingID::TAVERN);
  910. auto definesBuildingsChances = VLC->settings()->getVector(EGameSettings::TOWNS_STARTING_DWELLING_CHANCES);
  911. for(int i = 0; i < definesBuildingsChances.size(); i++)
  912. {
  913. if((getRandomGenerator().nextInt(1,100) <= definesBuildingsChances[i]))
  914. {
  915. vti->builtBuildings.insert(basicDwellings[i]);
  916. }
  917. }
  918. }
  919. // village hall must always exist
  920. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  921. //init hordes
  922. for (int i = 0; i < GameConstants::CREATURES_PER_TOWN; i++)
  923. {
  924. if (vstd::contains(vti->builtBuildings, hordes[i])) //if we have horde for this level
  925. {
  926. vti->builtBuildings.erase(hordes[i]);//remove old ID
  927. if (vti->getTown()->hordeLvl.at(0) == i)//if town first horde is this one
  928. {
  929. vti->builtBuildings.insert(BuildingID::HORDE_1);//add it
  930. //if we have upgraded dwelling as well
  931. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  932. vti->builtBuildings.insert(BuildingID::HORDE_1_UPGR);//add it as well
  933. }
  934. if (vti->getTown()->hordeLvl.at(1) == i)//if town second horde is this one
  935. {
  936. vti->builtBuildings.insert(BuildingID::HORDE_2);
  937. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  938. vti->builtBuildings.insert(BuildingID::HORDE_2_UPGR);
  939. }
  940. }
  941. }
  942. //#1444 - remove entries that don't have buildings defined (like some unused extra town hall buildings)
  943. //But DO NOT remove horde placeholders before they are replaced
  944. vstd::erase_if(vti->builtBuildings, [vti](const BuildingID & bid)
  945. {
  946. return !vti->getTown()->buildings.count(bid) || !vti->getTown()->buildings.at(bid);
  947. });
  948. if (vstd::contains(vti->builtBuildings, BuildingID::SHIPYARD) && vti->shipyardStatus()==IBoatGenerator::TILE_BLOCKED)
  949. vti->builtBuildings.erase(BuildingID::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  950. //Early check for #1444-like problems
  951. for([[maybe_unused]] const auto & building : vti->builtBuildings)
  952. {
  953. assert(vti->getTown()->buildings.at(building) != nullptr);
  954. }
  955. //town events
  956. for(CCastleEvent &ev : vti->events)
  957. {
  958. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  959. if (vstd::contains(ev.buildings,hordes[i])) //if we have horde for this level
  960. {
  961. ev.buildings.erase(hordes[i]);
  962. if (vti->getTown()->hordeLvl.at(0) == i)
  963. ev.buildings.insert(BuildingID::HORDE_1);
  964. if (vti->getTown()->hordeLvl.at(1) == i)
  965. ev.buildings.insert(BuildingID::HORDE_2);
  966. }
  967. }
  968. //init spells
  969. vti->spells.resize(GameConstants::SPELL_LEVELS);
  970. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  971. {
  972. const auto * s = vti->obligatorySpells[z].toSpell();
  973. vti->spells[s->getLevel()-1].push_back(s->id);
  974. vti->possibleSpells -= s->id;
  975. }
  976. while(!vti->possibleSpells.empty())
  977. {
  978. ui32 total=0;
  979. int sel = -1;
  980. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  981. total += vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  982. if (total == 0) // remaining spells have 0 probability
  983. break;
  984. auto r = getRandomGenerator().nextInt(total - 1);
  985. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  986. {
  987. r -= vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  988. if(r<0)
  989. {
  990. sel = ps;
  991. break;
  992. }
  993. }
  994. if(sel<0)
  995. sel=0;
  996. const auto * s = vti->possibleSpells[sel].toSpell();
  997. vti->spells[s->getLevel()-1].push_back(s->id);
  998. vti->possibleSpells -= s->id;
  999. }
  1000. vti->possibleSpells.clear();
  1001. if(vti->getOwner() != PlayerColor::NEUTRAL)
  1002. getPlayerState(vti->getOwner())->towns.emplace_back(vti);
  1003. }
  1004. }
  1005. void CGameState::initMapObjects()
  1006. {
  1007. logGlobal->debug("\tObject initialization");
  1008. // objCaller->preInit();
  1009. for(CGObjectInstance *obj : map->objects)
  1010. {
  1011. if(obj)
  1012. {
  1013. logGlobal->trace("Calling Init for object %d, %s, %s", obj->id.getNum(), obj->typeName, obj->subTypeName);
  1014. obj->initObj(getRandomGenerator());
  1015. }
  1016. }
  1017. for(CGObjectInstance *obj : map->objects)
  1018. {
  1019. if(!obj)
  1020. continue;
  1021. switch (obj->ID)
  1022. {
  1023. case Obj::QUEST_GUARD:
  1024. case Obj::SEER_HUT:
  1025. {
  1026. auto * q = dynamic_cast<CGSeerHut *>(obj);
  1027. assert (q);
  1028. q->setObjToKill();
  1029. }
  1030. }
  1031. }
  1032. CGSubterraneanGate::postInit(); //pairing subterranean gates
  1033. map->calculateGuardingGreaturePositions(); //calculate once again when all the guards are placed and initialized
  1034. }
  1035. void CGameState::placeHeroesInTowns()
  1036. {
  1037. for(auto & player : players)
  1038. {
  1039. if(player.first == PlayerColor::NEUTRAL)
  1040. continue;
  1041. for(CGHeroInstance * h : player.second.heroes)
  1042. {
  1043. for(CGTownInstance * t : player.second.towns)
  1044. {
  1045. if(h->visitablePos().z != t->visitablePos().z)
  1046. continue;
  1047. bool heroOnTownBlockableTile = t->blockingAt(h->visitablePos().x, h->visitablePos().y);
  1048. // current hero position is at one of blocking tiles of current town
  1049. // assume that this hero should be visiting the town (H3M format quirk) and move hero to correct position
  1050. if (heroOnTownBlockableTile)
  1051. {
  1052. int3 correctedPos = h->convertFromVisitablePos(t->visitablePos());
  1053. map->removeBlockVisTiles(h);
  1054. h->pos = correctedPos;
  1055. map->addBlockVisTiles(h);
  1056. assert(t->visitableAt(h->visitablePos().x, h->visitablePos().y));
  1057. }
  1058. }
  1059. }
  1060. }
  1061. }
  1062. void CGameState::initVisitingAndGarrisonedHeroes()
  1063. {
  1064. for(auto & player : players)
  1065. {
  1066. if(player.first == PlayerColor::NEUTRAL)
  1067. continue;
  1068. //init visiting and garrisoned heroes
  1069. for(CGHeroInstance * h : player.second.heroes)
  1070. {
  1071. for(CGTownInstance * t : player.second.towns)
  1072. {
  1073. if(h->visitablePos().z != t->visitablePos().z)
  1074. continue;
  1075. if (t->visitableAt(h->visitablePos().x, h->visitablePos().y))
  1076. {
  1077. assert(t->visitingHero == nullptr);
  1078. t->setVisitingHero(h);
  1079. }
  1080. }
  1081. }
  1082. }
  1083. for (auto hero : map->heroesOnMap)
  1084. {
  1085. if (hero->visitedTown)
  1086. {
  1087. assert (hero->visitedTown->visitingHero == hero);
  1088. }
  1089. }
  1090. }
  1091. const BattleInfo * CGameState::getBattle(const PlayerColor & player) const
  1092. {
  1093. if (!player.isValidPlayer())
  1094. return nullptr;
  1095. for (const auto & battlePtr : currentBattles)
  1096. if (battlePtr->sides[0].color == player || battlePtr->sides[1].color == player)
  1097. return battlePtr.get();
  1098. return nullptr;
  1099. }
  1100. const BattleInfo * CGameState::getBattle(const BattleID & battle) const
  1101. {
  1102. for (const auto & battlePtr : currentBattles)
  1103. if (battlePtr->battleID == battle)
  1104. return battlePtr.get();
  1105. return nullptr;
  1106. }
  1107. BattleInfo * CGameState::getBattle(const BattleID & battle)
  1108. {
  1109. for (const auto & battlePtr : currentBattles)
  1110. if (battlePtr->battleID == battle)
  1111. return battlePtr.get();
  1112. return nullptr;
  1113. }
  1114. BattleField CGameState::battleGetBattlefieldType(int3 tile, CRandomGenerator & rand)
  1115. {
  1116. assert(tile.valid());
  1117. if(!tile.valid())
  1118. return BattleField::NONE;
  1119. const TerrainTile &t = map->getTile(tile);
  1120. auto * topObject = t.visitableObjects.front();
  1121. if(topObject && topObject->getBattlefield() != BattleField::NONE)
  1122. {
  1123. return topObject->getBattlefield();
  1124. }
  1125. for(auto &obj : map->objects)
  1126. {
  1127. //look only for objects covering given tile
  1128. if( !obj || obj->pos.z != tile.z || !obj->coveringAt(tile.x, tile.y))
  1129. continue;
  1130. auto customBattlefield = obj->getBattlefield();
  1131. if(customBattlefield != BattleField::NONE)
  1132. return customBattlefield;
  1133. }
  1134. if(map->isCoastalTile(tile)) //coastal tile is always ground
  1135. return BattleField(*VLC->identifiers()->getIdentifier("core", "battlefield.sand_shore"));
  1136. return BattleField(*RandomGeneratorUtil::nextItem(t.terType->battleFields, rand));
  1137. }
  1138. void CGameState::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  1139. {
  1140. assert(obj);
  1141. assert(obj->hasStackAtSlot(stackPos));
  1142. out = fillUpgradeInfo(obj->getStack(stackPos));
  1143. }
  1144. UpgradeInfo CGameState::fillUpgradeInfo(const CStackInstance &stack) const
  1145. {
  1146. UpgradeInfo ret;
  1147. const CCreature *base = stack.type;
  1148. if (stack.armyObj->ID == Obj::HERO)
  1149. {
  1150. auto hero = dynamic_cast<const CGHeroInstance *>(stack.armyObj);
  1151. hero->fillUpgradeInfo(ret, stack);
  1152. if (hero->visitedTown)
  1153. {
  1154. hero->visitedTown->fillUpgradeInfo(ret, stack);
  1155. }
  1156. else
  1157. {
  1158. auto object = vstd::frontOrNull(getVisitableObjs(hero->visitablePos()));
  1159. auto upgradeSource = dynamic_cast<const ICreatureUpgrader*>(object);
  1160. if (object != hero && upgradeSource != nullptr)
  1161. upgradeSource->fillUpgradeInfo(ret, stack);
  1162. }
  1163. }
  1164. if (stack.armyObj->ID == Obj::TOWN)
  1165. {
  1166. auto town = dynamic_cast<const CGTownInstance *>(stack.armyObj);
  1167. town->fillUpgradeInfo(ret, stack);
  1168. }
  1169. if(!ret.newID.empty())
  1170. ret.oldID = base->getId();
  1171. for (ResourceSet &cost : ret.cost)
  1172. cost.positive(); //upgrade cost can't be negative, ignore missing resources
  1173. return ret;
  1174. }
  1175. PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  1176. {
  1177. if ( color1 == color2 )
  1178. return PlayerRelations::SAME_PLAYER;
  1179. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  1180. return PlayerRelations::ENEMIES;
  1181. const TeamState * ts = getPlayerTeam(color1);
  1182. if (ts && vstd::contains(ts->players, color2))
  1183. return PlayerRelations::ALLIES;
  1184. return PlayerRelations::ENEMIES;
  1185. }
  1186. void CGameState::apply(CPack *pack)
  1187. {
  1188. ui16 typ = typeList.getTypeID(pack);
  1189. applier->getApplier(typ)->applyOnGS(this, pack);
  1190. }
  1191. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out)
  1192. {
  1193. calculatePaths(std::make_shared<SingleHeroPathfinderConfig>(out, this, hero));
  1194. }
  1195. void CGameState::calculatePaths(const std::shared_ptr<PathfinderConfig> & config)
  1196. {
  1197. //FIXME: creating pathfinder is costly, maybe reset / clear is enough?
  1198. CPathfinder pathfinder(this, config);
  1199. pathfinder.calculatePaths();
  1200. }
  1201. /**
  1202. * Tells if the tile is guarded by a monster as well as the position
  1203. * of the monster that will attack on it.
  1204. *
  1205. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1206. * the monster guarding the tile.
  1207. */
  1208. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1209. {
  1210. std::vector<CGObjectInstance*> guards;
  1211. const int3 originalPos = pos;
  1212. if (!map->isInTheMap(pos))
  1213. return guards;
  1214. const TerrainTile &posTile = map->getTile(pos);
  1215. if (posTile.visitable)
  1216. {
  1217. for (CGObjectInstance* obj : posTile.visitableObjects)
  1218. {
  1219. if(obj->isBlockedVisitable())
  1220. {
  1221. if (obj->ID == Obj::MONSTER) // Monster
  1222. guards.push_back(obj);
  1223. }
  1224. }
  1225. }
  1226. pos -= int3(1, 1, 0); // Start with top left.
  1227. for (int dx = 0; dx < 3; dx++)
  1228. {
  1229. for (int dy = 0; dy < 3; dy++)
  1230. {
  1231. if (map->isInTheMap(pos))
  1232. {
  1233. const auto & tile = map->getTile(pos);
  1234. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1235. {
  1236. for (CGObjectInstance* obj : tile.visitableObjects)
  1237. {
  1238. if (obj->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1239. {
  1240. guards.push_back(obj);
  1241. }
  1242. }
  1243. }
  1244. }
  1245. pos.y++;
  1246. }
  1247. pos.y -= 3;
  1248. pos.x++;
  1249. }
  1250. return guards;
  1251. }
  1252. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1253. {
  1254. return gs->map->guardingCreaturePositions[pos.z][pos.x][pos.y];
  1255. }
  1256. void CGameState::updateRumor()
  1257. {
  1258. static std::vector<RumorState::ERumorType> rumorTypes = {RumorState::TYPE_MAP, RumorState::TYPE_SPECIAL, RumorState::TYPE_RAND, RumorState::TYPE_RAND};
  1259. std::vector<RumorState::ERumorTypeSpecial> sRumorTypes = {
  1260. RumorState::RUMOR_OBELISKS, RumorState::RUMOR_ARTIFACTS, RumorState::RUMOR_ARMY, RumorState::RUMOR_INCOME};
  1261. if(map->grailPos.valid()) // Grail should always be on map, but I had related crash I didn't manage to reproduce
  1262. sRumorTypes.push_back(RumorState::RUMOR_GRAIL);
  1263. int rumorId = -1;
  1264. int rumorExtra = -1;
  1265. auto & rand = getRandomGenerator();
  1266. rumor.type = *RandomGeneratorUtil::nextItem(rumorTypes, rand);
  1267. do
  1268. {
  1269. switch(rumor.type)
  1270. {
  1271. case RumorState::TYPE_SPECIAL:
  1272. {
  1273. SThievesGuildInfo tgi;
  1274. obtainPlayersStats(tgi, 20);
  1275. rumorId = *RandomGeneratorUtil::nextItem(sRumorTypes, rand);
  1276. if(rumorId == RumorState::RUMOR_GRAIL)
  1277. {
  1278. rumorExtra = getTile(map->grailPos)->terType->getIndex();
  1279. break;
  1280. }
  1281. std::vector<PlayerColor> players = {};
  1282. switch(rumorId)
  1283. {
  1284. case RumorState::RUMOR_OBELISKS:
  1285. players = tgi.obelisks[0];
  1286. break;
  1287. case RumorState::RUMOR_ARTIFACTS:
  1288. players = tgi.artifacts[0];
  1289. break;
  1290. case RumorState::RUMOR_ARMY:
  1291. players = tgi.army[0];
  1292. break;
  1293. case RumorState::RUMOR_INCOME:
  1294. players = tgi.income[0];
  1295. break;
  1296. }
  1297. rumorExtra = RandomGeneratorUtil::nextItem(players, rand)->getNum();
  1298. break;
  1299. }
  1300. case RumorState::TYPE_MAP:
  1301. // Makes sure that map rumors only used if there enough rumors too choose from
  1302. if(!map->rumors.empty() && (map->rumors.size() > 1 || !rumor.last.count(RumorState::TYPE_MAP)))
  1303. {
  1304. rumorId = rand.nextInt((int)map->rumors.size() - 1);
  1305. break;
  1306. }
  1307. else
  1308. rumor.type = RumorState::TYPE_RAND;
  1309. [[fallthrough]];
  1310. case RumorState::TYPE_RAND:
  1311. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randtvrn");
  1312. rumorId = rand.nextInt((int)vector.size() - 1);
  1313. break;
  1314. }
  1315. }
  1316. while(!rumor.update(rumorId, rumorExtra));
  1317. }
  1318. bool CGameState::isVisible(int3 pos, const std::optional<PlayerColor> & player) const
  1319. {
  1320. if (!map->isInTheMap(pos))
  1321. return false;
  1322. if (!player)
  1323. return true;
  1324. if(player == PlayerColor::NEUTRAL)
  1325. return false;
  1326. if(player->isSpectator())
  1327. return true;
  1328. return (*getPlayerTeam(*player)->fogOfWarMap)[pos.z][pos.x][pos.y];
  1329. }
  1330. bool CGameState::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const
  1331. {
  1332. if(!player)
  1333. return true;
  1334. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  1335. if (player == obj->tempOwner)
  1336. return true;
  1337. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1338. return false;
  1339. //object is visible when at least one blocked tile is visible
  1340. for(int fy=0; fy < obj->getHeight(); ++fy)
  1341. {
  1342. for(int fx=0; fx < obj->getWidth(); ++fx)
  1343. {
  1344. int3 pos = obj->pos + int3(-fx, -fy, 0);
  1345. if ( map->isInTheMap(pos) &&
  1346. obj->coveringAt(pos.x, pos.y) &&
  1347. isVisible(pos, *player))
  1348. return true;
  1349. }
  1350. }
  1351. return false;
  1352. }
  1353. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1354. {
  1355. const TerrainTile * pom = &map->getTile(dst);
  1356. return map->checkForVisitableDir(src, pom, dst);
  1357. }
  1358. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(const PlayerColor & player) const
  1359. {
  1360. const MetaString messageWonSelf = MetaString::createFromTextID("core.genrltxt.659");
  1361. const MetaString messageWonOther = MetaString::createFromTextID("core.genrltxt.5");
  1362. const MetaString messageLostSelf = MetaString::createFromTextID("core.genrltxt.7");
  1363. const MetaString messageLostOther = MetaString::createFromTextID("core.genrltxt.8");
  1364. auto evaluateEvent = [=](const EventCondition & condition)
  1365. {
  1366. return this->checkForVictory(player, condition);
  1367. };
  1368. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1369. //cheater or tester, but has entered the code...
  1370. if (p->enteredWinningCheatCode)
  1371. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  1372. if (p->enteredLosingCheatCode)
  1373. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1374. for (const TriggeredEvent & event : map->triggeredEvents)
  1375. {
  1376. if (event.trigger.test(evaluateEvent))
  1377. {
  1378. if (event.effect.type == EventEffect::VICTORY)
  1379. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  1380. if (event.effect.type == EventEffect::DEFEAT)
  1381. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  1382. }
  1383. }
  1384. if (checkForStandardLoss(player))
  1385. {
  1386. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1387. }
  1388. return EVictoryLossCheckResult();
  1389. }
  1390. bool CGameState::checkForVictory(const PlayerColor & player, const EventCondition & condition) const
  1391. {
  1392. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1393. switch (condition.condition)
  1394. {
  1395. case EventCondition::STANDARD_WIN:
  1396. {
  1397. return player == checkForStandardWin();
  1398. }
  1399. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  1400. {
  1401. for(const auto & elem : p->heroes)
  1402. if(elem->hasArt(ArtifactID(condition.objectType)))
  1403. return true;
  1404. return false;
  1405. }
  1406. case EventCondition::HAVE_CREATURES:
  1407. {
  1408. //check if in players armies there is enough creatures
  1409. int total = 0; //creature counter
  1410. for(auto object : map->objects)
  1411. {
  1412. const CArmedInstance *ai = nullptr;
  1413. if(object
  1414. && object->tempOwner == player //object controlled by player
  1415. && (ai = dynamic_cast<const CArmedInstance *>(object.get()))) //contains army
  1416. {
  1417. for(const auto & elem : ai->Slots()) //iterate through army
  1418. if(elem.second->type->getIndex() == condition.objectType) //it's searched creature
  1419. total += elem.second->count;
  1420. }
  1421. }
  1422. return total >= condition.value;
  1423. }
  1424. case EventCondition::HAVE_RESOURCES:
  1425. {
  1426. return p->resources[condition.objectType] >= condition.value;
  1427. }
  1428. case EventCondition::HAVE_BUILDING:
  1429. {
  1430. if (condition.object) // specific town
  1431. {
  1432. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  1433. return (t->tempOwner == player && t->hasBuilt(BuildingID(condition.objectType)));
  1434. }
  1435. else // any town
  1436. {
  1437. for (const CGTownInstance * t : p->towns)
  1438. {
  1439. if (t->hasBuilt(BuildingID(condition.objectType)))
  1440. return true;
  1441. }
  1442. return false;
  1443. }
  1444. }
  1445. case EventCondition::DESTROY:
  1446. {
  1447. if (condition.object) // mode A - destroy specific object of this type
  1448. {
  1449. if(const auto * hero = dynamic_cast<const CGHeroInstance *>(condition.object))
  1450. return boost::range::find(gs->map->heroesOnMap, hero) == gs->map->heroesOnMap.end();
  1451. else
  1452. return getObj(condition.object->id) == nullptr;
  1453. }
  1454. else
  1455. {
  1456. for(const auto & elem : map->objects) // mode B - destroy all objects of this type
  1457. {
  1458. if(elem && elem->ID.getNum() == condition.objectType)
  1459. return false;
  1460. }
  1461. return true;
  1462. }
  1463. }
  1464. case EventCondition::CONTROL:
  1465. {
  1466. // list of players that need to control object to fulfull condition
  1467. // NOTE: cgameinfocallback specified explicitly in order to get const version
  1468. const auto & team = CGameInfoCallback::getPlayerTeam(player)->players;
  1469. if (condition.object) // mode A - flag one specific object, like town
  1470. {
  1471. return team.count(condition.object->tempOwner) != 0;
  1472. }
  1473. else
  1474. {
  1475. for(const auto & elem : map->objects) // mode B - flag all objects of this type
  1476. {
  1477. //check not flagged objs
  1478. if ( elem && elem->ID.getNum() == condition.objectType && team.count(elem->tempOwner) == 0 )
  1479. return false;
  1480. }
  1481. return true;
  1482. }
  1483. }
  1484. case EventCondition::TRANSPORT:
  1485. {
  1486. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  1487. return (t->visitingHero && t->visitingHero->hasArt(ArtifactID(condition.objectType))) ||
  1488. (t->garrisonHero && t->garrisonHero->hasArt(ArtifactID(condition.objectType)));
  1489. }
  1490. case EventCondition::DAYS_PASSED:
  1491. {
  1492. return (si32)gs->day > condition.value;
  1493. }
  1494. case EventCondition::IS_HUMAN:
  1495. {
  1496. return p->human ? condition.value == 1 : condition.value == 0;
  1497. }
  1498. case EventCondition::DAYS_WITHOUT_TOWN:
  1499. {
  1500. if (p->daysWithoutCastle)
  1501. return p->daysWithoutCastle >= condition.value;
  1502. else
  1503. return false;
  1504. }
  1505. case EventCondition::CONST_VALUE:
  1506. {
  1507. return condition.value; // just convert to bool
  1508. }
  1509. case EventCondition::HAVE_0:
  1510. {
  1511. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1512. //TODO: support new condition format
  1513. return false;
  1514. }
  1515. case EventCondition::HAVE_BUILDING_0:
  1516. {
  1517. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1518. //TODO: support new condition format
  1519. return false;
  1520. }
  1521. case EventCondition::DESTROY_0:
  1522. {
  1523. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1524. //TODO: support new condition format
  1525. return false;
  1526. }
  1527. default:
  1528. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  1529. return false;
  1530. }
  1531. }
  1532. PlayerColor CGameState::checkForStandardWin() const
  1533. {
  1534. //std victory condition is:
  1535. //all enemies lost
  1536. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  1537. TeamID winnerTeam = TeamID::NO_TEAM;
  1538. for(const auto & elem : players)
  1539. {
  1540. if(elem.second.status == EPlayerStatus::INGAME && elem.first.isValidPlayer())
  1541. {
  1542. if(supposedWinner == PlayerColor::NEUTRAL)
  1543. {
  1544. //first player remaining ingame - candidate for victory
  1545. supposedWinner = elem.second.color;
  1546. winnerTeam = elem.second.team;
  1547. }
  1548. else if(winnerTeam != elem.second.team)
  1549. {
  1550. //current candidate has enemy remaining in game -> no vicotry
  1551. return PlayerColor::NEUTRAL;
  1552. }
  1553. }
  1554. }
  1555. return supposedWinner;
  1556. }
  1557. bool CGameState::checkForStandardLoss(const PlayerColor & player) const
  1558. {
  1559. //std loss condition is: player lost all towns and heroes
  1560. const PlayerState & pState = *CGameInfoCallback::getPlayerState(player);
  1561. return pState.checkVanquished();
  1562. }
  1563. struct statsHLP
  1564. {
  1565. using TStat = std::pair<PlayerColor, si64>;
  1566. //converts [<player's color, value>] to vec[place] -> platers
  1567. static std::vector< std::vector< PlayerColor > > getRank( std::vector<TStat> stats )
  1568. {
  1569. std::sort(stats.begin(), stats.end(), statsHLP());
  1570. //put first element
  1571. std::vector< std::vector<PlayerColor> > ret;
  1572. std::vector<PlayerColor> tmp;
  1573. tmp.push_back( stats[0].first );
  1574. ret.push_back( tmp );
  1575. //the rest of elements
  1576. for(int g=1; g<stats.size(); ++g)
  1577. {
  1578. if(stats[g].second == stats[g-1].second)
  1579. {
  1580. (ret.end()-1)->push_back( stats[g].first );
  1581. }
  1582. else
  1583. {
  1584. //create next occupied rank
  1585. std::vector<PlayerColor> tmp;
  1586. tmp.push_back(stats[g].first);
  1587. ret.push_back(tmp);
  1588. }
  1589. }
  1590. return ret;
  1591. }
  1592. bool operator()(const TStat & a, const TStat & b) const
  1593. {
  1594. return a.second > b.second;
  1595. }
  1596. static const CGHeroInstance * findBestHero(CGameState * gs, const PlayerColor & color)
  1597. {
  1598. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  1599. if(h.empty())
  1600. return nullptr;
  1601. //best hero will be that with highest exp
  1602. int best = 0;
  1603. for(int b=1; b<h.size(); ++b)
  1604. {
  1605. if(h[b]->exp > h[best]->exp)
  1606. {
  1607. best = b;
  1608. }
  1609. }
  1610. return h[best];
  1611. }
  1612. //calculates total number of artifacts that belong to given player
  1613. static int getNumberOfArts(const PlayerState * ps)
  1614. {
  1615. int ret = 0;
  1616. for(auto h : ps->heroes)
  1617. {
  1618. ret += (int)h->artifactsInBackpack.size() + (int)h->artifactsWorn.size();
  1619. }
  1620. return ret;
  1621. }
  1622. // get total strength of player army
  1623. static si64 getArmyStrength(const PlayerState * ps)
  1624. {
  1625. si64 str = 0;
  1626. for(auto h : ps->heroes)
  1627. {
  1628. if(!h->inTownGarrison) //original h3 behavior
  1629. str += h->getArmyStrength();
  1630. }
  1631. return str;
  1632. }
  1633. // get total gold income
  1634. static int getIncome(const PlayerState * ps)
  1635. {
  1636. int totalIncome = 0;
  1637. const CGObjectInstance * heroOrTown = nullptr;
  1638. //Heroes can produce gold as well - skill, specialty or arts
  1639. for(const auto & h : ps->heroes)
  1640. {
  1641. totalIncome += h->valOfBonuses(Selector::typeSubtype(BonusType::GENERATE_RESOURCE, GameResID(EGameResID::GOLD)));
  1642. if(!heroOrTown)
  1643. heroOrTown = h;
  1644. }
  1645. //Add town income of all towns
  1646. for(const auto & t : ps->towns)
  1647. {
  1648. totalIncome += t->dailyIncome()[EGameResID::GOLD];
  1649. if(!heroOrTown)
  1650. heroOrTown = t;
  1651. }
  1652. /// FIXME: Dirty dirty hack
  1653. /// Stats helper need some access to gamestate.
  1654. std::vector<const CGObjectInstance *> ownedObjects;
  1655. for(const CGObjectInstance * obj : heroOrTown->cb->gameState()->map->objects)
  1656. {
  1657. if(obj && obj->tempOwner == ps->color)
  1658. ownedObjects.push_back(obj);
  1659. }
  1660. /// This is code from CPlayerSpecificInfoCallback::getMyObjects
  1661. /// I'm really need to find out about callback interface design...
  1662. for(const auto * object : ownedObjects)
  1663. {
  1664. //Mines
  1665. if ( object->ID == Obj::MINE )
  1666. {
  1667. const auto * mine = dynamic_cast<const CGMine *>(object);
  1668. assert(mine);
  1669. if (mine->producedResource == EGameResID::GOLD)
  1670. totalIncome += mine->producedQuantity;
  1671. }
  1672. }
  1673. return totalIncome;
  1674. }
  1675. };
  1676. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  1677. {
  1678. auto playerInactive = [&](const PlayerColor & color)
  1679. {
  1680. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  1681. };
  1682. #define FILL_FIELD(FIELD, VAL_GETTER) \
  1683. { \
  1684. std::vector< std::pair< PlayerColor, si64 > > stats; \
  1685. for(auto g = players.begin(); g != players.end(); ++g) \
  1686. { \
  1687. if(playerInactive(g->second.color)) \
  1688. continue; \
  1689. std::pair< PlayerColor, si64 > stat; \
  1690. stat.first = g->second.color; \
  1691. stat.second = VAL_GETTER; \
  1692. stats.push_back(stat); \
  1693. } \
  1694. tgi.FIELD = statsHLP::getRank(stats); \
  1695. }
  1696. for(auto & elem : players)
  1697. {
  1698. if(!playerInactive(elem.second.color))
  1699. tgi.playerColors.push_back(elem.second.color);
  1700. }
  1701. if(level >= 0) //num of towns & num of heroes
  1702. {
  1703. //num of towns
  1704. FILL_FIELD(numOfTowns, g->second.towns.size())
  1705. //num of heroes
  1706. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  1707. }
  1708. if(level >= 1) //best hero's portrait
  1709. {
  1710. for(const auto & player : players)
  1711. {
  1712. if(playerInactive(player.second.color))
  1713. continue;
  1714. const CGHeroInstance * best = statsHLP::findBestHero(this, player.second.color);
  1715. InfoAboutHero iah;
  1716. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  1717. iah.army.clear();
  1718. tgi.colorToBestHero[player.second.color] = iah;
  1719. }
  1720. }
  1721. if(level >= 2) //gold
  1722. {
  1723. FILL_FIELD(gold, g->second.resources[EGameResID::GOLD])
  1724. }
  1725. if(level >= 2) //wood & ore
  1726. {
  1727. FILL_FIELD(woodOre, g->second.resources[EGameResID::WOOD] + g->second.resources[EGameResID::ORE])
  1728. }
  1729. if(level >= 3) //mercury, sulfur, crystal, gems
  1730. {
  1731. FILL_FIELD(mercSulfCrystGems, g->second.resources[EGameResID::MERCURY] + g->second.resources[EGameResID::SULFUR] + g->second.resources[EGameResID::CRYSTAL] + g->second.resources[EGameResID::GEMS])
  1732. }
  1733. if(level >= 3) //obelisks found
  1734. {
  1735. auto getObeliskVisited = [](const TeamID & t)
  1736. {
  1737. if(CGObelisk::visited.count(t))
  1738. return CGObelisk::visited[t];
  1739. else
  1740. return ui8(0);
  1741. };
  1742. FILL_FIELD(obelisks, getObeliskVisited(gs->getPlayerTeam(g->second.color)->id))
  1743. }
  1744. if(level >= 4) //artifacts
  1745. {
  1746. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  1747. }
  1748. if(level >= 4) //army strength
  1749. {
  1750. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  1751. }
  1752. if(level >= 5) //income
  1753. {
  1754. FILL_FIELD(income, statsHLP::getIncome(&g->second))
  1755. }
  1756. if(level >= 2) //best hero's stats
  1757. {
  1758. //already set in lvl 1 handling
  1759. }
  1760. if(level >= 3) //personality
  1761. {
  1762. for(const auto & player : players)
  1763. {
  1764. if(playerInactive(player.second.color)) //do nothing for neutral player
  1765. continue;
  1766. if(player.second.human)
  1767. {
  1768. tgi.personality[player.second.color] = EAiTactic::NONE;
  1769. }
  1770. else //AI
  1771. {
  1772. tgi.personality[player.second.color] = map->players[player.second.color.getNum()].aiTactic;
  1773. }
  1774. }
  1775. }
  1776. if(level >= 4) //best creature
  1777. {
  1778. //best creatures belonging to player (highest AI value)
  1779. for(const auto & player : players)
  1780. {
  1781. if(playerInactive(player.second.color)) //do nothing for neutral player
  1782. continue;
  1783. int bestCre = -1; //best creature's ID
  1784. for(const auto & elem : player.second.heroes)
  1785. {
  1786. for(const auto & it : elem->Slots())
  1787. {
  1788. int toCmp = it.second->type->getId(); //ID of creature we should compare with the best one
  1789. if(bestCre == -1 || VLC->creh->objects[bestCre]->getAIValue() < VLC->creh->objects[toCmp]->getAIValue())
  1790. {
  1791. bestCre = toCmp;
  1792. }
  1793. }
  1794. }
  1795. tgi.bestCreature[player.second.color] = bestCre;
  1796. }
  1797. }
  1798. #undef FILL_FIELD
  1799. }
  1800. void CGameState::buildBonusSystemTree()
  1801. {
  1802. buildGlobalTeamPlayerTree();
  1803. attachArmedObjects();
  1804. for(CGTownInstance *t : map->towns)
  1805. {
  1806. t->deserializationFix();
  1807. }
  1808. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  1809. // are provided on initializing / deserializing
  1810. // NOTE: calling deserializationFix() might be more correct option, but might lead to side effects
  1811. for (auto hero : map->heroesOnMap)
  1812. hero->boatDeserializationFix();
  1813. }
  1814. void CGameState::deserializationFix()
  1815. {
  1816. buildGlobalTeamPlayerTree();
  1817. attachArmedObjects();
  1818. }
  1819. void CGameState::buildGlobalTeamPlayerTree()
  1820. {
  1821. for(auto & team : teams)
  1822. {
  1823. TeamState * t = &team.second;
  1824. t->attachTo(globalEffects);
  1825. for(const PlayerColor & teamMember : team.second.players)
  1826. {
  1827. PlayerState *p = getPlayerState(teamMember);
  1828. assert(p);
  1829. p->attachTo(*t);
  1830. }
  1831. }
  1832. }
  1833. void CGameState::attachArmedObjects()
  1834. {
  1835. for(CGObjectInstance *obj : map->objects)
  1836. {
  1837. if(auto * armed = dynamic_cast<CArmedInstance *>(obj))
  1838. {
  1839. armed->whatShouldBeAttached().attachTo(armed->whereShouldBeAttached(this));
  1840. }
  1841. }
  1842. }
  1843. bool CGameState::giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid)
  1844. {
  1845. CArtifact * const artifact = VLC->arth->objects[aid]; //pointer to constant object
  1846. CArtifactInstance * ai = ArtifactUtils::createNewArtifactInstance(artifact);
  1847. map->addNewArtifactInstance(ai);
  1848. auto slot = ArtifactUtils::getArtAnyPosition(h, aid);
  1849. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  1850. {
  1851. ai->putAt(ArtifactLocation(h, slot));
  1852. return true;
  1853. }
  1854. else
  1855. {
  1856. return false;
  1857. }
  1858. }
  1859. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  1860. {
  1861. std::set<HeroTypeID> ret;
  1862. for(int i = 0; i < map->allowedHeroes.size(); i++)
  1863. if(map->allowedHeroes[i] || alsoIncludeNotAllowed)
  1864. ret.insert(HeroTypeID(i));
  1865. for(const auto & playerSettingPair : scenarioOps->playerInfos) //remove uninitialized yet heroes picked for start by other players
  1866. {
  1867. if(playerSettingPair.second.hero.getNum() != PlayerSettings::RANDOM)
  1868. ret -= HeroTypeID(playerSettingPair.second.hero);
  1869. }
  1870. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1871. {
  1872. if(hero->type)
  1873. ret -= hero->type->getId();
  1874. else
  1875. ret -= HeroTypeID(hero->subID);
  1876. }
  1877. for(auto obj : map->objects) //prisons
  1878. if(obj && obj->ID == Obj::PRISON)
  1879. ret -= HeroTypeID(obj->subID);
  1880. return ret;
  1881. }
  1882. bool CGameState::isUsedHero(const HeroTypeID & hid) const
  1883. {
  1884. return getUsedHero(hid);
  1885. }
  1886. CGHeroInstance * CGameState::getUsedHero(const HeroTypeID & hid) const
  1887. {
  1888. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1889. {
  1890. if(hero->type && hero->type->getId() == hid)
  1891. {
  1892. return hero;
  1893. }
  1894. }
  1895. for(auto obj : map->objects) //prisons
  1896. {
  1897. if(obj && obj->ID == Obj::PRISON )
  1898. {
  1899. auto * hero = dynamic_cast<CGHeroInstance *>(obj.get());
  1900. assert(hero);
  1901. if ( hero->type && hero->type->getId() == hid )
  1902. return hero;
  1903. }
  1904. }
  1905. return nullptr;
  1906. }
  1907. bool RumorState::update(int id, int extra)
  1908. {
  1909. if(vstd::contains(last, type))
  1910. {
  1911. if(last[type].first != id)
  1912. {
  1913. last[type].first = id;
  1914. last[type].second = extra;
  1915. }
  1916. else
  1917. return false;
  1918. }
  1919. else
  1920. last[type] = std::make_pair(id, extra);
  1921. return true;
  1922. }
  1923. TeamState::TeamState()
  1924. {
  1925. setNodeType(TEAM);
  1926. fogOfWarMap = std::make_shared<boost::multi_array<ui8, 3>>();
  1927. }
  1928. TeamState::TeamState(TeamState && other) noexcept:
  1929. CBonusSystemNode(std::move(other)),
  1930. id(other.id)
  1931. {
  1932. std::swap(players, other.players);
  1933. std::swap(fogOfWarMap, other.fogOfWarMap);
  1934. }
  1935. CRandomGenerator & CGameState::getRandomGenerator()
  1936. {
  1937. return rand;
  1938. }
  1939. VCMI_LIB_NAMESPACE_END