CGameState.cpp 50 KB

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