CGameState.cpp 54 KB

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