CGameState.cpp 51 KB

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