CGameState.cpp 52 KB

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