CGameState.cpp 61 KB

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