CGameState.cpp 50 KB

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