CGameState.cpp 55 KB

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