CGameState.cpp 55 KB

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