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