CGameState.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799
  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 hero = map->tryTakeFromHeroPool(heroTypeId);
  480. if (!hero)
  481. {
  482. auto handler = LIBRARY->objtypeh->getHandlerFor(Obj::HERO, heroTypeId.toHeroType()->heroClass->getIndex());
  483. auto object = handler->create(cb, handler->getTemplates().front());
  484. hero = std::dynamic_pointer_cast<CGHeroInstance>(object);
  485. hero->ID = Obj::HERO;
  486. hero->setHeroType(heroTypeId);
  487. }
  488. hero->tempOwner = playerColor;
  489. hero->setAnchorPos(townPos + hero->getVisitableOffset());
  490. map->getEditManager()->insertObject(hero);
  491. }
  492. void CGameState::placeStartingHeroes()
  493. {
  494. logGlobal->debug("\tGiving starting hero");
  495. for(auto & playerSettingPair : scenarioOps->playerInfos)
  496. {
  497. auto playerColor = playerSettingPair.first;
  498. auto & playerInfo = map->players[playerColor.getNum()];
  499. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  500. {
  501. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  502. if (campaign && campaign->playerHasStartingHero(playerColor))
  503. continue;
  504. HeroTypeID heroTypeId = pickNextHeroType(playerColor);
  505. if(playerSettingPair.second.hero == HeroTypeID::NONE || playerSettingPair.second.hero == HeroTypeID::RANDOM)
  506. playerSettingPair.second.hero = heroTypeId;
  507. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  508. }
  509. }
  510. }
  511. void CGameState::removeHeroPlaceholders()
  512. {
  513. // remove any hero placeholders that remain on map after (potential) campaign heroes placement
  514. for(auto obj : map->getObjects<CGHeroPlaceholder>())
  515. {
  516. map->eraseObject(obj->id);
  517. }
  518. }
  519. void CGameState::initHeroes()
  520. {
  521. //heroes instances initialization
  522. for (auto heroID : map->getHeroesOnMap())
  523. {
  524. auto hero = getHero(heroID);
  525. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  526. {
  527. logGlobal->warn("Hero with uninitialized owner!");
  528. continue;
  529. }
  530. hero->initHero(getRandomGenerator());
  531. }
  532. // generate boats for all heroes on water
  533. for (auto heroID : map->getHeroesOnMap())
  534. {
  535. auto hero = getHero(heroID);
  536. assert(map->isInTheMap(hero->visitablePos()));
  537. const auto & tile = map->getTile(hero->visitablePos());
  538. if (hero->ID == Obj::PRISON)
  539. continue;
  540. if (tile.isWater())
  541. {
  542. auto handler = LIBRARY->objtypeh->getHandlerFor(Obj::BOAT, hero->getBoatType().getNum());
  543. auto boat = std::dynamic_pointer_cast<CGBoat>(handler->create(cb, nullptr));
  544. handler->configureObject(boat.get(), getRandomGenerator());
  545. boat->setAnchorPos(hero->anchorPos());
  546. boat->appearance = handler->getTemplates().front();
  547. map->addNewObject(boat);
  548. hero->setBoat(boat.get());
  549. }
  550. }
  551. std::set<HeroTypeID> heroesToCreate = getUnusedAllowedHeroes(); //ids of heroes to be created and put into the pool
  552. for(const HeroTypeID & htype : heroesToCreate) //all not used allowed heroes go with default state into the pool
  553. {
  554. CGHeroInstance * heroInPool = map->tryGetFromHeroPool(htype);
  555. // some heroes are created as part of map loading (sod+ h3m maps)
  556. // instances for h3 heroes from roe/ab h3m maps and heroes from mods at this point don't exist -> create them
  557. if (!heroInPool)
  558. {
  559. auto newHeroPtr = std::make_shared<CGHeroInstance>(cb);
  560. newHeroPtr->subID = htype.getNum();
  561. map->addToHeroPool(newHeroPtr);
  562. heroInPool = newHeroPtr.get();
  563. }
  564. map->generateUniqueInstanceName(heroInPool);
  565. heroInPool->initHero(getRandomGenerator());
  566. heroesPool->addHeroToPool(htype);
  567. }
  568. for(auto & elem : map->disposedHeroes)
  569. heroesPool->setAvailability(elem.heroId, elem.players);
  570. if (campaign)
  571. campaign->initHeroes();
  572. }
  573. void CGameState::initFogOfWar()
  574. {
  575. logGlobal->debug("\tFog of war"); //FIXME: should be initialized after all bonuses are set
  576. int layers = map->levels();
  577. for(auto & elem : teams)
  578. {
  579. auto & fow = elem.second.fogOfWarMap;
  580. fow.resize(boost::extents[layers][map->width][map->height]);
  581. std::fill(fow.data(), fow.data() + fow.num_elements(), 0);
  582. for(const auto & obj : map->getObjects())
  583. {
  584. if(!vstd::contains(elem.second.players, obj->getOwner()))
  585. continue; //not a flagged object
  586. std::unordered_set<int3> tiles;
  587. getTilesInRange(tiles, obj->getSightCenter(), obj->getSightRadius(), ETileVisibility::HIDDEN, obj->tempOwner);
  588. for(const int3 & tile : tiles)
  589. {
  590. elem.second.fogOfWarMap[tile.z][tile.x][tile.y] = 1;
  591. }
  592. }
  593. }
  594. }
  595. void CGameState::initStartingBonus()
  596. {
  597. if (scenarioOps->mode == EStartMode::CAMPAIGN)
  598. return;
  599. // These are the single scenario bonuses; predefined
  600. // campaign bonuses are spread out over other init* functions.
  601. logGlobal->debug("\tStarting bonuses");
  602. for(auto & elem : players)
  603. {
  604. //starting bonus
  605. if(scenarioOps->playerInfos[elem.first].bonus == PlayerStartingBonus::RANDOM)
  606. scenarioOps->playerInfos[elem.first].bonus = static_cast<PlayerStartingBonus>(getRandomGenerator().nextInt(2));
  607. switch(scenarioOps->playerInfos[elem.first].bonus)
  608. {
  609. case PlayerStartingBonus::GOLD:
  610. elem.second.resources[EGameResID::GOLD] += getRandomGenerator().nextInt(5, 10) * 100;
  611. break;
  612. case PlayerStartingBonus::RESOURCE:
  613. {
  614. auto res = (*LIBRARY->townh)[scenarioOps->playerInfos[elem.first].castle]->town->primaryRes;
  615. if(res == EGameResID::WOOD_AND_ORE)
  616. {
  617. int amount = getRandomGenerator().nextInt(5, 10);
  618. elem.second.resources[EGameResID::WOOD] += amount;
  619. elem.second.resources[EGameResID::ORE] += amount;
  620. }
  621. else
  622. {
  623. elem.second.resources[res] += getRandomGenerator().nextInt(3, 6);
  624. }
  625. break;
  626. }
  627. case PlayerStartingBonus::ARTIFACT:
  628. {
  629. if(elem.second.getHeroes().empty())
  630. {
  631. logGlobal->error("Cannot give starting artifact - no heroes!");
  632. break;
  633. }
  634. const Artifact * toGive = pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE).toEntity(LIBRARY);
  635. CGHeroInstance *hero = elem.second.getHeroes()[0];
  636. if(!giveHeroArtifact(hero, toGive->getId()))
  637. logGlobal->error("Cannot give starting artifact - no free slots!");
  638. }
  639. break;
  640. }
  641. }
  642. }
  643. void CGameState::initTownNames()
  644. {
  645. std::map<FactionID, std::vector<int>> availableNames;
  646. for(const auto & faction : LIBRARY->townh->getDefaultAllowed())
  647. {
  648. std::vector<int> potentialNames;
  649. if(faction.toFaction()->town->getRandomNamesCount() > 0)
  650. {
  651. for(int i = 0; i < faction.toFaction()->town->getRandomNamesCount(); ++i)
  652. potentialNames.push_back(i);
  653. availableNames[faction] = potentialNames;
  654. }
  655. }
  656. for (const auto & townID : map->getAllTowns())
  657. {
  658. auto vti = getTown(townID);
  659. if(!vti->getNameTextID().empty())
  660. continue;
  661. FactionID faction = vti->getFactionID();
  662. if(availableNames.empty())
  663. {
  664. logGlobal->warn("Failed to find available name for a random town!");
  665. vti->setNameTextId("core.genrltxt.508"); // Unnamed
  666. continue;
  667. }
  668. // If town has no available names (for example - all were picked) - pick names from some other faction that still has names available
  669. if(!availableNames.count(faction))
  670. faction = RandomGeneratorUtil::nextItem(availableNames, getRandomGenerator())->first;
  671. auto nameIt = RandomGeneratorUtil::nextItem(availableNames[faction], getRandomGenerator());
  672. vti->setNameTextId(faction.toFaction()->town->getRandomNameTextID(*nameIt));
  673. availableNames[faction].erase(nameIt);
  674. if(availableNames[faction].empty())
  675. availableNames.erase(faction);
  676. }
  677. }
  678. void CGameState::initTowns()
  679. {
  680. logGlobal->debug("\tTowns");
  681. if (campaign)
  682. campaign->initTowns();
  683. map->townUniversitySkills.clear();
  684. map->townUniversitySkills.push_back(SecondarySkill(SecondarySkill::FIRE_MAGIC));
  685. map->townUniversitySkills.push_back(SecondarySkill(SecondarySkill::AIR_MAGIC));
  686. map->townUniversitySkills.push_back(SecondarySkill(SecondarySkill::WATER_MAGIC));
  687. map->townUniversitySkills.push_back(SecondarySkill(SecondarySkill::EARTH_MAGIC));
  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((getRandomGenerator().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, getRandomGenerator());
  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()
  795. {
  796. logGlobal->debug("\tObject initialization");
  797. for(auto & obj : map->getObjects())
  798. obj->initObj(getRandomGenerator());
  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(cb); //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 & rand)
  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, rand));
  908. }
  909. void CGameState::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  910. {
  911. assert(obj);
  912. assert(obj->hasStackAtSlot(stackPos));
  913. out = fillUpgradeInfo(obj->getStack(stackPos));
  914. }
  915. UpgradeInfo CGameState::fillUpgradeInfo(const CStackInstance & stack) const
  916. {
  917. const CCreature *base = stack.getCreature();
  918. UpgradeInfo ret(base->getId());
  919. if (stack.getArmy()->ID == Obj::HERO)
  920. {
  921. auto hero = dynamic_cast<const CGHeroInstance *>(stack.getArmy());
  922. hero->fillUpgradeInfo(ret, stack);
  923. if (hero->getVisitedTown())
  924. {
  925. hero->getVisitedTown()->fillUpgradeInfo(ret, stack);
  926. }
  927. else
  928. {
  929. auto object = vstd::frontOrNull(getVisitableObjs(hero->visitablePos()));
  930. auto upgradeSource = dynamic_cast<const ICreatureUpgrader*>(object);
  931. if (object != hero && upgradeSource != nullptr)
  932. upgradeSource->fillUpgradeInfo(ret, stack);
  933. }
  934. }
  935. if (stack.getArmy()->ID == Obj::TOWN)
  936. {
  937. auto town = dynamic_cast<const CGTownInstance *>(stack.getArmy());
  938. town->fillUpgradeInfo(ret, stack);
  939. }
  940. return ret;
  941. }
  942. PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  943. {
  944. if ( color1 == color2 )
  945. return PlayerRelations::SAME_PLAYER;
  946. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  947. return PlayerRelations::ENEMIES;
  948. const TeamState * ts = getPlayerTeam(color1);
  949. if (ts && vstd::contains(ts->players, color2))
  950. return PlayerRelations::ALLIES;
  951. return PlayerRelations::ENEMIES;
  952. }
  953. void CGameState::apply(CPackForClient & pack)
  954. {
  955. pack.applyGs(this);
  956. }
  957. void CGameState::calculatePaths(const std::shared_ptr<PathfinderConfig> & config) const
  958. {
  959. CPathfinder pathfinder(*const_cast<CGameState*>(this), config);
  960. pathfinder.calculatePaths();
  961. }
  962. /**
  963. * Tells if the tile is guarded by a monster as well as the position
  964. * of the monster that will attack on it.
  965. *
  966. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  967. * the monster guarding the tile.
  968. */
  969. std::vector<const CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  970. {
  971. std::vector<const CGObjectInstance*> guards;
  972. const int3 originalPos = pos;
  973. if (!map->isInTheMap(pos))
  974. return guards;
  975. const TerrainTile &posTile = map->getTile(pos);
  976. if (posTile.visitable())
  977. {
  978. for (ObjectInstanceID objectID : posTile.visitableObjects)
  979. {
  980. const CGObjectInstance * object = getObjInstance(objectID);
  981. if(object->isBlockedVisitable())
  982. {
  983. if (object->ID == Obj::MONSTER) // Monster
  984. guards.push_back(object);
  985. }
  986. }
  987. }
  988. pos -= int3(1, 1, 0); // Start with top left.
  989. for (int dx = 0; dx < 3; dx++)
  990. {
  991. for (int dy = 0; dy < 3; dy++)
  992. {
  993. if (map->isInTheMap(pos))
  994. {
  995. const auto & tile = map->getTile(pos);
  996. if (tile.visitable() && (tile.isWater() == posTile.isWater()))
  997. {
  998. for (ObjectInstanceID objectID : tile.visitableObjects)
  999. {
  1000. const CGObjectInstance * object = getObjInstance(objectID);
  1001. if (object->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1002. {
  1003. guards.push_back(object);
  1004. }
  1005. }
  1006. }
  1007. }
  1008. pos.y++;
  1009. }
  1010. pos.y -= 3;
  1011. pos.x++;
  1012. }
  1013. return guards;
  1014. }
  1015. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1016. {
  1017. return getMap().guardingCreaturePositions[pos.z][pos.x][pos.y];
  1018. }
  1019. bool CGameState::isVisible(int3 pos, const std::optional<PlayerColor> & player) const
  1020. {
  1021. if (!map->isInTheMap(pos))
  1022. return false;
  1023. if (!player)
  1024. return true;
  1025. if(player == PlayerColor::NEUTRAL)
  1026. return false;
  1027. if(player->isSpectator())
  1028. return true;
  1029. return getPlayerTeam(*player)->fogOfWarMap[pos.z][pos.x][pos.y];
  1030. }
  1031. bool CGameState::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const
  1032. {
  1033. if(!player)
  1034. return true;
  1035. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  1036. if (player == obj->tempOwner)
  1037. return true;
  1038. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1039. return false;
  1040. //object is visible when at least one blocked tile is visible
  1041. for(int fy=0; fy < obj->getHeight(); ++fy)
  1042. {
  1043. for(int fx=0; fx < obj->getWidth(); ++fx)
  1044. {
  1045. int3 pos = obj->anchorPos() + int3(-fx, -fy, 0);
  1046. if ( map->isInTheMap(pos) &&
  1047. obj->coveringAt(pos) &&
  1048. isVisible(pos, *player))
  1049. return true;
  1050. }
  1051. }
  1052. return false;
  1053. }
  1054. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1055. {
  1056. const TerrainTile * pom = &map->getTile(dst);
  1057. return map->checkForVisitableDir(src, pom, dst);
  1058. }
  1059. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(const PlayerColor & player) const
  1060. {
  1061. const MetaString messageWonSelf = MetaString::createFromTextID("core.genrltxt.659");
  1062. const MetaString messageWonOther = MetaString::createFromTextID("core.genrltxt.5");
  1063. const MetaString messageLostSelf = MetaString::createFromTextID("core.genrltxt.7");
  1064. const MetaString messageLostOther = MetaString::createFromTextID("core.genrltxt.8");
  1065. auto evaluateEvent = [this, player](const EventCondition & condition)
  1066. {
  1067. return this->checkForVictory(player, condition);
  1068. };
  1069. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1070. //cheater or tester, but has entered the code...
  1071. if (p->enteredWinningCheatCode)
  1072. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  1073. if (p->enteredLosingCheatCode)
  1074. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1075. for (const TriggeredEvent & event : map->triggeredEvents)
  1076. {
  1077. if (event.trigger.test(evaluateEvent))
  1078. {
  1079. if (event.effect.type == EventEffect::VICTORY)
  1080. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  1081. if (event.effect.type == EventEffect::DEFEAT)
  1082. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  1083. }
  1084. }
  1085. if (checkForStandardLoss(player))
  1086. {
  1087. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1088. }
  1089. return EVictoryLossCheckResult();
  1090. }
  1091. bool CGameState::checkForVictory(const PlayerColor & player, const EventCondition & condition) const
  1092. {
  1093. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1094. switch (condition.condition)
  1095. {
  1096. case EventCondition::STANDARD_WIN:
  1097. {
  1098. return player == checkForStandardWin();
  1099. }
  1100. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  1101. {
  1102. for(const auto & elem : p->getHeroes())
  1103. if(elem->hasArt(condition.objectType.as<ArtifactID>()))
  1104. return true;
  1105. return false;
  1106. }
  1107. case EventCondition::HAVE_CREATURES:
  1108. {
  1109. //check if in players armies there is enough creatures
  1110. int total = 0; //creature counter
  1111. for(auto ai : map->getObjects<CArmedInstance>())
  1112. {
  1113. if(ai->getOwner() == player)
  1114. {
  1115. for(const auto & elem : ai->Slots()) //iterate through army
  1116. if(elem.second->getId() == condition.objectType.as<CreatureID>()) //it's searched creature
  1117. total += elem.second->count;
  1118. }
  1119. }
  1120. return total >= condition.value;
  1121. }
  1122. case EventCondition::HAVE_RESOURCES:
  1123. {
  1124. return p->resources[condition.objectType.as<GameResID>()] >= condition.value;
  1125. }
  1126. case EventCondition::HAVE_BUILDING:
  1127. {
  1128. if (condition.objectID != ObjectInstanceID::NONE) // specific town
  1129. {
  1130. const auto * t = getTown(condition.objectID);
  1131. return (t->tempOwner == player && t->hasBuilt(condition.objectType.as<BuildingID>()));
  1132. }
  1133. else // any town
  1134. {
  1135. for (const CGTownInstance * t : p->getTowns())
  1136. {
  1137. if (t->hasBuilt(condition.objectType.as<BuildingID>()))
  1138. return true;
  1139. }
  1140. return false;
  1141. }
  1142. }
  1143. case EventCondition::DESTROY:
  1144. {
  1145. if (condition.objectID != ObjectInstanceID::NONE) // mode A - destroy specific object of this type
  1146. {
  1147. return p->destroyedObjects.count(condition.objectID);
  1148. }
  1149. else
  1150. {
  1151. for(const auto & elem : map->getObjects()) // mode B - destroy all objects of this type
  1152. {
  1153. if(elem && elem->ID == condition.objectType.as<MapObjectID>())
  1154. return false;
  1155. }
  1156. return true;
  1157. }
  1158. }
  1159. case EventCondition::CONTROL:
  1160. {
  1161. // list of players that need to control object to fulfull condition
  1162. // NOTE: cgameinfocallback specified explicitly in order to get const version
  1163. const auto * team = CGameInfoCallback::getPlayerTeam(player);
  1164. if (condition.objectID != ObjectInstanceID::NONE) // mode A - flag one specific object, like town
  1165. {
  1166. const auto * object = getObjInstance(condition.objectID);
  1167. if (!object)
  1168. return false;
  1169. return team->players.count(object->getOwner()) != 0;
  1170. }
  1171. else
  1172. {
  1173. for(const auto & elem : map->getObjects()) // mode B - flag all objects of this type
  1174. {
  1175. //check not flagged objs
  1176. if ( elem && elem->ID == condition.objectType.as<MapObjectID>() && team->players.count(elem->getOwner()) == 0 )
  1177. return false;
  1178. }
  1179. return true;
  1180. }
  1181. }
  1182. case EventCondition::TRANSPORT:
  1183. {
  1184. const auto * t = getTown(condition.objectID);
  1185. bool garrisonedWon = t->getGarrisonHero() && t->getGarrisonHero()->getOwner() == player && t->getGarrisonHero()->hasArt(condition.objectType.as<ArtifactID>());
  1186. bool visitingWon = t->getVisitingHero() && t->getVisitingHero()->getOwner() == player && t->getVisitingHero()->hasArt(condition.objectType.as<ArtifactID>());
  1187. return garrisonedWon || visitingWon;
  1188. }
  1189. case EventCondition::DAYS_PASSED:
  1190. {
  1191. return day > condition.value;
  1192. }
  1193. case EventCondition::IS_HUMAN:
  1194. {
  1195. return p->human ? condition.value == 1 : condition.value == 0;
  1196. }
  1197. case EventCondition::DAYS_WITHOUT_TOWN:
  1198. {
  1199. if (p->daysWithoutCastle)
  1200. return p->daysWithoutCastle >= condition.value;
  1201. else
  1202. return false;
  1203. }
  1204. case EventCondition::CONST_VALUE:
  1205. {
  1206. return condition.value; // just convert to bool
  1207. }
  1208. default:
  1209. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  1210. return false;
  1211. }
  1212. }
  1213. PlayerColor CGameState::checkForStandardWin() const
  1214. {
  1215. //std victory condition is:
  1216. //all enemies lost
  1217. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  1218. TeamID winnerTeam = TeamID::NO_TEAM;
  1219. for(const auto & elem : players)
  1220. {
  1221. if(elem.second.status == EPlayerStatus::WINNER)
  1222. return elem.second.color;
  1223. if(elem.second.status == EPlayerStatus::INGAME && elem.first.isValidPlayer())
  1224. {
  1225. if(supposedWinner == PlayerColor::NEUTRAL)
  1226. {
  1227. //first player remaining ingame - candidate for victory
  1228. supposedWinner = elem.second.color;
  1229. winnerTeam = elem.second.team;
  1230. }
  1231. else if(winnerTeam != elem.second.team)
  1232. {
  1233. //current candidate has enemy remaining in game -> no vicotry
  1234. return PlayerColor::NEUTRAL;
  1235. }
  1236. }
  1237. }
  1238. return supposedWinner;
  1239. }
  1240. bool CGameState::checkForStandardLoss(const PlayerColor & player) const
  1241. {
  1242. //std loss condition is: player lost all towns and heroes
  1243. const PlayerState & pState = *CGameInfoCallback::getPlayerState(player);
  1244. return pState.checkVanquished();
  1245. }
  1246. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  1247. {
  1248. auto playerInactive = [&](const PlayerColor & color)
  1249. {
  1250. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  1251. };
  1252. #define FILL_FIELD(FIELD, VAL_GETTER) \
  1253. { \
  1254. std::vector< std::pair< PlayerColor, si64 > > stats; \
  1255. for(auto g = players.begin(); g != players.end(); ++g) \
  1256. { \
  1257. if(playerInactive(g->second.color)) \
  1258. continue; \
  1259. std::pair< PlayerColor, si64 > stat; \
  1260. stat.first = g->second.color; \
  1261. stat.second = VAL_GETTER; \
  1262. stats.push_back(stat); \
  1263. } \
  1264. tgi.FIELD = Statistic::getRank(stats); \
  1265. }
  1266. for(auto & elem : players)
  1267. {
  1268. if(!playerInactive(elem.second.color))
  1269. tgi.playerColors.push_back(elem.second.color);
  1270. }
  1271. if(level >= 0) //num of towns & num of heroes
  1272. {
  1273. //num of towns
  1274. FILL_FIELD(numOfTowns, g->second.getTowns().size())
  1275. //num of heroes
  1276. FILL_FIELD(numOfHeroes, g->second.getHeroes().size())
  1277. }
  1278. if(level >= 1) //best hero's portrait
  1279. {
  1280. for(const auto & player : players)
  1281. {
  1282. if(playerInactive(player.second.color))
  1283. continue;
  1284. const CGHeroInstance * best = Statistic::findBestHero(this, player.second.color);
  1285. InfoAboutHero iah;
  1286. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  1287. iah.army.clear();
  1288. tgi.colorToBestHero[player.second.color] = iah;
  1289. }
  1290. }
  1291. if(level >= 2) //gold
  1292. {
  1293. FILL_FIELD(gold, g->second.resources[EGameResID::GOLD])
  1294. }
  1295. if(level >= 2) //wood & ore
  1296. {
  1297. FILL_FIELD(woodOre, g->second.resources[EGameResID::WOOD] + g->second.resources[EGameResID::ORE])
  1298. }
  1299. if(level >= 3) //mercury, sulfur, crystal, gems
  1300. {
  1301. FILL_FIELD(mercSulfCrystGems, g->second.resources[EGameResID::MERCURY] + g->second.resources[EGameResID::SULFUR] + g->second.resources[EGameResID::CRYSTAL] + g->second.resources[EGameResID::GEMS])
  1302. }
  1303. if(level >= 3) //obelisks found
  1304. {
  1305. FILL_FIELD(obelisks, Statistic::getObeliskVisited(this, getPlayerTeam(g->second.color)->id))
  1306. }
  1307. if(level >= 4) //artifacts
  1308. {
  1309. FILL_FIELD(artifacts, Statistic::getNumberOfArts(&g->second))
  1310. }
  1311. if(level >= 4) //army strength
  1312. {
  1313. FILL_FIELD(army, Statistic::getArmyStrength(&g->second))
  1314. }
  1315. if(level >= 5) //income
  1316. {
  1317. FILL_FIELD(income, Statistic::getIncome(this, &g->second))
  1318. }
  1319. if(level >= 2) //best hero's stats
  1320. {
  1321. //already set in lvl 1 handling
  1322. }
  1323. if(level >= 3) //personality
  1324. {
  1325. for(const auto & player : players)
  1326. {
  1327. if(playerInactive(player.second.color)) //do nothing for neutral player
  1328. continue;
  1329. if(player.second.human)
  1330. {
  1331. tgi.personality[player.second.color] = EAiTactic::NONE;
  1332. }
  1333. else //AI
  1334. {
  1335. tgi.personality[player.second.color] = map->players[player.second.color.getNum()].aiTactic;
  1336. }
  1337. }
  1338. }
  1339. if(level >= 4) //best creature
  1340. {
  1341. //best creatures belonging to player (highest AI value)
  1342. for(const auto & player : players)
  1343. {
  1344. if(playerInactive(player.second.color)) //do nothing for neutral player
  1345. continue;
  1346. CreatureID bestCre; //best creature's ID
  1347. for(const auto & elem : player.second.getHeroes())
  1348. {
  1349. for(const auto & it : elem->Slots())
  1350. {
  1351. CreatureID toCmp = it.second->getId(); //ID of creature we should compare with the best one
  1352. if(bestCre == CreatureID::NONE || bestCre.toEntity(LIBRARY)->getAIValue() < toCmp.toEntity(LIBRARY)->getAIValue())
  1353. {
  1354. bestCre = toCmp;
  1355. }
  1356. }
  1357. }
  1358. tgi.bestCreature[player.second.color] = bestCre;
  1359. }
  1360. }
  1361. #undef FILL_FIELD
  1362. }
  1363. void CGameState::buildBonusSystemTree()
  1364. {
  1365. buildGlobalTeamPlayerTree();
  1366. for(auto & armed : map->getObjects<CArmedInstance>())
  1367. armed->attachToBonusSystem(*this);
  1368. for(auto & art : map->getArtifacts())
  1369. art->attachToBonusSystem(*this);
  1370. }
  1371. void CGameState::restoreBonusSystemTree()
  1372. {
  1373. heroesPool->setGameState(this);
  1374. buildGlobalTeamPlayerTree();
  1375. for(auto & armed : map->getObjects<CArmedInstance>())
  1376. armed->restoreBonusSystem(*this);
  1377. for(auto & art : map->getArtifacts())
  1378. art->attachToBonusSystem(*this);
  1379. for(auto & heroID : map->getHeroesInPool())
  1380. map->tryGetFromHeroPool(heroID)->artDeserializationFix(*this, map->tryGetFromHeroPool(heroID));
  1381. if (campaign)
  1382. campaign->setGamestate(this);
  1383. }
  1384. void CGameState::buildGlobalTeamPlayerTree()
  1385. {
  1386. for(auto & team : teams)
  1387. {
  1388. TeamState * t = &team.second;
  1389. t->attachTo(globalEffects);
  1390. for(const PlayerColor & teamMember : team.second.players)
  1391. {
  1392. PlayerState *p = getPlayerState(teamMember);
  1393. assert(p);
  1394. p->attachTo(*t);
  1395. }
  1396. }
  1397. }
  1398. bool CGameState::giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid)
  1399. {
  1400. CArtifactInstance * ai = createArtifact(aid);
  1401. auto slot = ArtifactUtils::getArtAnyPosition(h, aid);
  1402. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  1403. {
  1404. map->putArtifactInstance(*h, ai->getId(), slot);
  1405. return true;
  1406. }
  1407. else
  1408. {
  1409. return false;
  1410. }
  1411. }
  1412. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  1413. {
  1414. std::set<HeroTypeID> ret = map->allowedHeroes;
  1415. for(const auto & playerSettingPair : scenarioOps->playerInfos) //remove uninitialized yet heroes picked for start by other players
  1416. {
  1417. if(playerSettingPair.second.hero != HeroTypeID::RANDOM)
  1418. ret -= HeroTypeID(playerSettingPair.second.hero);
  1419. }
  1420. for (auto heroID : map->getHeroesOnMap())
  1421. ret -= getHero(heroID)->getHeroTypeID();
  1422. return ret;
  1423. }
  1424. bool CGameState::isUsedHero(const HeroTypeID & hid) const
  1425. {
  1426. return getUsedHero(hid);
  1427. }
  1428. CGHeroInstance * CGameState::getUsedHero(const HeroTypeID & hid) const
  1429. {
  1430. for(auto hero : map->getObjects<CGHeroInstance>()) //prisons
  1431. {
  1432. if (hero->getHeroTypeID() == hid)
  1433. return hero;
  1434. }
  1435. return nullptr;
  1436. }
  1437. TeamState::TeamState()
  1438. {
  1439. setNodeType(TEAM);
  1440. }
  1441. vstd::RNG & CGameState::getRandomGenerator()
  1442. {
  1443. return cb->getRandomGenerator();
  1444. }
  1445. ArtifactID CGameState::pickRandomArtifact(vstd::RNG & rand, int flags, std::function<bool(ArtifactID)> accepts)
  1446. {
  1447. std::set<ArtifactID> potentialPicks;
  1448. // Select artifacts that satisfy provided criteria
  1449. for (auto const & artifactID : map->allowedArtifact)
  1450. {
  1451. if (!LIBRARY->arth->legalArtifact(artifactID))
  1452. continue;
  1453. auto const * artifact = artifactID.toArtifact();
  1454. assert(artifact->aClass != CArtifact::ART_SPECIAL); // should be filtered out when allowedArtifacts is initialized
  1455. if ((flags & CArtifact::ART_TREASURE) == 0 && artifact->aClass == CArtifact::ART_TREASURE)
  1456. continue;
  1457. if ((flags & CArtifact::ART_MINOR) == 0 && artifact->aClass == CArtifact::ART_MINOR)
  1458. continue;
  1459. if ((flags & CArtifact::ART_MAJOR) == 0 && artifact->aClass == CArtifact::ART_MAJOR)
  1460. continue;
  1461. if ((flags & CArtifact::ART_RELIC) == 0 && artifact->aClass == CArtifact::ART_RELIC)
  1462. continue;
  1463. if (!accepts(artifact->getId()))
  1464. continue;
  1465. potentialPicks.insert(artifact->getId());
  1466. }
  1467. return pickRandomArtifact(rand, potentialPicks);
  1468. }
  1469. ArtifactID CGameState::pickRandomArtifact(vstd::RNG & rand, std::set<ArtifactID> potentialPicks)
  1470. {
  1471. // No allowed artifacts at all - give Grail - this can't be banned (hopefully)
  1472. // FIXME: investigate how such cases are handled by H3 - some heavily customized user-made maps likely rely on H3 behavior
  1473. if (potentialPicks.empty())
  1474. {
  1475. logGlobal->warn("Failed to find artifact that matches requested parameters!");
  1476. return ArtifactID::GRAIL;
  1477. }
  1478. // Find how many times least used artifacts were picked by randomizer
  1479. int leastUsedTimes = std::numeric_limits<int>::max();
  1480. for (auto const & artifact : potentialPicks)
  1481. if (allocatedArtifacts[artifact] < leastUsedTimes)
  1482. leastUsedTimes = allocatedArtifacts[artifact];
  1483. // Pick all artifacts that were used least number of times
  1484. std::set<ArtifactID> preferredPicks;
  1485. for (auto const & artifact : potentialPicks)
  1486. if (allocatedArtifacts[artifact] == leastUsedTimes)
  1487. preferredPicks.insert(artifact);
  1488. assert(!preferredPicks.empty());
  1489. ArtifactID artID = *RandomGeneratorUtil::nextItem(preferredPicks, rand);
  1490. allocatedArtifacts[artID] += 1; // record +1 more usage
  1491. return artID;
  1492. }
  1493. ArtifactID CGameState::pickRandomArtifact(vstd::RNG & rand, std::function<bool(ArtifactID)> accepts)
  1494. {
  1495. return pickRandomArtifact(rand, 0xff, std::move(accepts));
  1496. }
  1497. ArtifactID CGameState::pickRandomArtifact(vstd::RNG & rand, int flags)
  1498. {
  1499. return pickRandomArtifact(rand, flags, [](const ArtifactID &) { return true; });
  1500. }
  1501. CArtifactInstance * CGameState::createScroll(const SpellID & spellId)
  1502. {
  1503. return map->createScroll(spellId);
  1504. }
  1505. CArtifactInstance * CGameState::createArtifact(const ArtifactID & artID, const SpellID & spellId)
  1506. {
  1507. return map->createArtifact(artID, spellId);
  1508. }
  1509. void CGameState::saveGame(CSaveFile & file) const
  1510. {
  1511. ActiveModsInSaveList activeModsDummy;
  1512. logGlobal->info("Saving game state");
  1513. file.save(*getMapHeader());
  1514. file.save(*getStartInfo());
  1515. file.save(activeModsDummy);
  1516. file.save(*this);
  1517. }
  1518. void CGameState::loadGame(CLoadFile & file)
  1519. {
  1520. logGlobal->info("Loading game state...");
  1521. CMapHeader dummyHeader;
  1522. auto startInfo = std::make_shared<StartInfo>();
  1523. ActiveModsInSaveList dummyActiveMods;
  1524. file.load(dummyHeader);
  1525. if (file.hasFeature(ESerializationVersion::NO_RAW_POINTERS_IN_SERIALIZER))
  1526. {
  1527. file.load(startInfo);
  1528. file.load(dummyActiveMods);
  1529. file.load(*this);
  1530. }
  1531. else
  1532. {
  1533. bool dummyA = false;
  1534. uint32_t dummyB = 0;
  1535. uint16_t dummyC = 0;
  1536. file.load(startInfo);
  1537. file.load(dummyActiveMods);
  1538. file.load(dummyA);
  1539. file.load(dummyB);
  1540. file.load(dummyC);
  1541. file.load(*this);
  1542. }
  1543. }
  1544. void CGameState::saveCompatibilityRegisterMissingArtifacts()
  1545. {
  1546. for( const auto & newArtifact : saveCompatibilityUnregisteredArtifacts)
  1547. map->saveCompatibilityAddMissingArtifact(newArtifact);
  1548. saveCompatibilityUnregisteredArtifacts.clear();
  1549. }
  1550. VCMI_LIB_NAMESPACE_END