CGameState.cpp 61 KB

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