CGameState.cpp 60 KB

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