CGameState.cpp 47 KB

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