CGameState.cpp 50 KB

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