CGameState.cpp 51 KB

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