CGameState.cpp 52 KB

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