CGameState.cpp 50 KB

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