CGameState.cpp 56 KB

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