2
0

CGameState.cpp 59 KB

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