CGameState.cpp 50 KB

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