CGameState.cpp 47 KB

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