CGameState.cpp 56 KB

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