CGameState.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983
  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<ui8>();
  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. auto * hero = dynamic_cast<CGHeroInstance *>(object);
  464. auto * town = dynamic_cast<CGTownInstance *>(object);
  465. if (hero && hero->ID != Obj::PRISON)
  466. map->heroesOnMap.emplace_back(hero);
  467. if (town)
  468. map->towns.emplace_back(town);
  469. //handle Favouring Winds - mark tiles under it
  470. if(object->ID == Obj::FAVORABLE_WINDS)
  471. {
  472. for (int i = 0; i < object->getWidth() ; i++)
  473. {
  474. for (int j = 0; j < object->getHeight() ; j++)
  475. {
  476. int3 pos = object->pos - int3(i,j,0);
  477. if(map->isInTheMap(pos)) map->getTile(pos).extTileFlags |= 128;
  478. }
  479. }
  480. }
  481. }
  482. }
  483. void CGameState::initPlayerStates()
  484. {
  485. logGlobal->debug("\tCreating player entries in gs");
  486. for(auto & elem : scenarioOps->playerInfos)
  487. {
  488. PlayerState & p = players[elem.first];
  489. p.color=elem.first;
  490. p.human = elem.second.isControlledByHuman();
  491. p.team = map->players[elem.first.getNum()].team;
  492. teams[p.team].id = p.team;//init team
  493. teams[p.team].players.insert(elem.first);//add player to team
  494. }
  495. }
  496. void CGameState::placeStartingHero(const PlayerColor & playerColor, const HeroTypeID & heroTypeId, int3 townPos)
  497. {
  498. for(auto town : map->towns)
  499. {
  500. if(town->getPosition() == townPos)
  501. {
  502. townPos = town->visitablePos();
  503. break;
  504. }
  505. }
  506. auto handler = VLC->objtypeh->getHandlerFor(Obj::HERO, VLC->heroh->objects[heroTypeId]->heroClass->getIndex());
  507. CGObjectInstance * obj = handler->create(handler->getTemplates().front());
  508. CGHeroInstance * hero = dynamic_cast<CGHeroInstance *>(obj);
  509. hero->ID = Obj::HERO;
  510. hero->setHeroType(heroTypeId);
  511. hero->tempOwner = playerColor;
  512. hero->pos = townPos;
  513. hero->pos += hero->getVisitableOffset();
  514. map->getEditManager()->insertObject(hero);
  515. }
  516. void CGameState::placeStartingHeroes()
  517. {
  518. logGlobal->debug("\tGiving starting hero");
  519. for(auto & playerSettingPair : scenarioOps->playerInfos)
  520. {
  521. auto playerColor = playerSettingPair.first;
  522. auto & playerInfo = map->players[playerColor.getNum()];
  523. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  524. {
  525. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  526. if (campaign && campaign->playerHasStartingHero(playerColor))
  527. continue;
  528. HeroTypeID heroTypeId = pickNextHeroType(playerColor);
  529. if(playerSettingPair.second.hero == HeroTypeID::NONE)
  530. playerSettingPair.second.hero = heroTypeId;
  531. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  532. }
  533. }
  534. }
  535. void CGameState::removeHeroPlaceholders()
  536. {
  537. // remove any hero placeholders that remain on map after (potential) campaign heroes placement
  538. for(auto obj : map->objects)
  539. {
  540. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  541. {
  542. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  543. map->removeBlockVisTiles(heroPlaceholder, true);
  544. map->instanceNames.erase(obj->instanceName);
  545. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  546. delete heroPlaceholder;
  547. }
  548. }
  549. }
  550. void CGameState::initHeroes()
  551. {
  552. for(auto hero : map->heroesOnMap) //heroes instances initialization
  553. {
  554. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  555. {
  556. logGlobal->warn("Hero with uninitialized owner!");
  557. continue;
  558. }
  559. hero->initHero(getRandomGenerator());
  560. getPlayerState(hero->getOwner())->heroes.push_back(hero);
  561. map->allHeroes[hero->getHeroType()] = hero;
  562. }
  563. // generate boats for all heroes on water
  564. for(auto hero : map->heroesOnMap)
  565. {
  566. assert(map->isInTheMap(hero->visitablePos()));
  567. const auto & tile = map->getTile(hero->visitablePos());
  568. if (tile.terType->isWater())
  569. {
  570. auto handler = VLC->objtypeh->getHandlerFor(Obj::BOAT, hero->getBoatType().getNum());
  571. CGBoat * boat = dynamic_cast<CGBoat*>(handler->create());
  572. handler->configureObject(boat, gs->getRandomGenerator());
  573. boat->pos = hero->pos;
  574. boat->appearance = handler->getTemplates().front();
  575. boat->id = ObjectInstanceID(static_cast<si32>(gs->map->objects.size()));
  576. map->objects.emplace_back(boat);
  577. map->addBlockVisTiles(boat);
  578. hero->attachToBoat(boat);
  579. }
  580. }
  581. for(auto obj : map->objects) //prisons
  582. {
  583. if(obj && obj->ID == Obj::PRISON)
  584. {
  585. auto * hero = dynamic_cast<CGHeroInstance*>(obj.get());
  586. hero->initHero(getRandomGenerator());
  587. map->allHeroes[hero->getHeroType()] = hero;
  588. }
  589. }
  590. std::set<HeroTypeID> heroesToCreate = getUnusedAllowedHeroes(); //ids of heroes to be created and put into the pool
  591. for(auto ph : map->predefinedHeroes)
  592. {
  593. if(!vstd::contains(heroesToCreate, ph->getHeroType()))
  594. continue;
  595. ph->initHero(getRandomGenerator());
  596. heroesPool->addHeroToPool(ph);
  597. heroesToCreate.erase(ph->type->getId());
  598. map->allHeroes[ph->getHeroType()] = ph;
  599. }
  600. for(const HeroTypeID & htype : heroesToCreate) //all not used allowed heroes go with default state into the pool
  601. {
  602. auto * vhi = new CGHeroInstance();
  603. vhi->initHero(getRandomGenerator(), htype);
  604. int typeID = htype.getNum();
  605. map->allHeroes[typeID] = vhi;
  606. heroesPool->addHeroToPool(vhi);
  607. }
  608. for(auto & elem : map->disposedHeroes)
  609. heroesPool->setAvailability(elem.heroId, elem.players);
  610. if (campaign)
  611. campaign->initHeroes();
  612. }
  613. void CGameState::initFogOfWar()
  614. {
  615. logGlobal->debug("\tFog of war"); //FIXME: should be initialized after all bonuses are set
  616. int layers = map->levels();
  617. for(auto & elem : teams)
  618. {
  619. auto fow = elem.second.fogOfWarMap;
  620. fow->resize(boost::extents[layers][map->width][map->height]);
  621. std::fill(fow->data(), fow->data() + fow->num_elements(), 0);
  622. for(CGObjectInstance *obj : map->objects)
  623. {
  624. if(!obj || !vstd::contains(elem.second.players, obj->tempOwner)) continue; //not a flagged object
  625. std::unordered_set<int3> tiles;
  626. getTilesInRange(tiles, obj->getSightCenter(), obj->getSightRadius(), ETileVisibility::HIDDEN, obj->tempOwner);
  627. for(const int3 & tile : tiles)
  628. {
  629. (*elem.second.fogOfWarMap)[tile.z][tile.x][tile.y] = 1;
  630. }
  631. }
  632. }
  633. }
  634. void CGameState::initStartingBonus()
  635. {
  636. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  637. return;
  638. // These are the single scenario bonuses; predefined
  639. // campaign bonuses are spread out over other init* functions.
  640. logGlobal->debug("\tStarting bonuses");
  641. for(auto & elem : players)
  642. {
  643. //starting bonus
  644. if(scenarioOps->playerInfos[elem.first].bonus == PlayerStartingBonus::RANDOM)
  645. scenarioOps->playerInfos[elem.first].bonus = static_cast<PlayerStartingBonus>(getRandomGenerator().nextInt(2));
  646. switch(scenarioOps->playerInfos[elem.first].bonus)
  647. {
  648. case PlayerStartingBonus::GOLD:
  649. elem.second.resources[EGameResID::GOLD] += getRandomGenerator().nextInt(5, 10) * 100;
  650. break;
  651. case PlayerStartingBonus::RESOURCE:
  652. {
  653. auto res = (*VLC->townh)[scenarioOps->playerInfos[elem.first].castle]->town->primaryRes;
  654. if(res == EGameResID::WOOD_AND_ORE)
  655. {
  656. int amount = getRandomGenerator().nextInt(5, 10);
  657. elem.second.resources[EGameResID::WOOD] += amount;
  658. elem.second.resources[EGameResID::ORE] += amount;
  659. }
  660. else
  661. {
  662. elem.second.resources[res] += getRandomGenerator().nextInt(3, 6);
  663. }
  664. break;
  665. }
  666. case PlayerStartingBonus::ARTIFACT:
  667. {
  668. if(elem.second.heroes.empty())
  669. {
  670. logGlobal->error("Cannot give starting artifact - no heroes!");
  671. break;
  672. }
  673. const Artifact * toGive = VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE).toArtifact(VLC->artifacts());
  674. CGHeroInstance *hero = elem.second.heroes[0];
  675. if(!giveHeroArtifact(hero, toGive->getId()))
  676. logGlobal->error("Cannot give starting artifact - no free slots!");
  677. }
  678. break;
  679. }
  680. }
  681. }
  682. void CGameState::initTowns()
  683. {
  684. logGlobal->debug("\tTowns");
  685. if (campaign)
  686. campaign->initTowns();
  687. CGTownInstance::universitySkills.clear();
  688. for ( int i=0; i<4; i++)
  689. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  690. for (auto & elem : map->towns)
  691. {
  692. CGTownInstance * vti =(elem);
  693. assert(vti->town);
  694. if(vti->getNameTranslated().empty())
  695. {
  696. size_t nameID = getRandomGenerator().nextInt(vti->getTown()->getRandomNamesCount() - 1);
  697. vti->setNameTextId(vti->getTown()->getRandomNameTextID(nameID));
  698. }
  699. 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 };
  700. 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 };
  701. 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 };
  702. //init buildings
  703. if(vstd::contains(vti->builtBuildings, BuildingID::DEFAULT)) //give standard set of buildings
  704. {
  705. vti->builtBuildings.erase(BuildingID::DEFAULT);
  706. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  707. if(vti->tempOwner != PlayerColor::NEUTRAL)
  708. vti->builtBuildings.insert(BuildingID::TAVERN);
  709. auto definesBuildingsChances = VLC->settings()->getVector(EGameSettings::TOWNS_STARTING_DWELLING_CHANCES);
  710. for(int i = 0; i < definesBuildingsChances.size(); i++)
  711. {
  712. if((getRandomGenerator().nextInt(1,100) <= definesBuildingsChances[i]))
  713. {
  714. vti->builtBuildings.insert(basicDwellings[i]);
  715. }
  716. }
  717. }
  718. // village hall must always exist
  719. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  720. //init hordes
  721. for (int i = 0; i < GameConstants::CREATURES_PER_TOWN; i++)
  722. {
  723. if (vstd::contains(vti->builtBuildings, hordes[i])) //if we have horde for this level
  724. {
  725. vti->builtBuildings.erase(hordes[i]);//remove old ID
  726. if (vti->getTown()->hordeLvl.at(0) == i)//if town first horde is this one
  727. {
  728. vti->builtBuildings.insert(BuildingID::HORDE_1);//add it
  729. //if we have upgraded dwelling as well
  730. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  731. vti->builtBuildings.insert(BuildingID::HORDE_1_UPGR);//add it as well
  732. }
  733. if (vti->getTown()->hordeLvl.at(1) == i)//if town second horde is this one
  734. {
  735. vti->builtBuildings.insert(BuildingID::HORDE_2);
  736. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  737. vti->builtBuildings.insert(BuildingID::HORDE_2_UPGR);
  738. }
  739. }
  740. }
  741. //#1444 - remove entries that don't have buildings defined (like some unused extra town hall buildings)
  742. //But DO NOT remove horde placeholders before they are replaced
  743. vstd::erase_if(vti->builtBuildings, [vti](const BuildingID & bid)
  744. {
  745. return !vti->getTown()->buildings.count(bid) || !vti->getTown()->buildings.at(bid);
  746. });
  747. if (vstd::contains(vti->builtBuildings, BuildingID::SHIPYARD) && vti->shipyardStatus()==IBoatGenerator::TILE_BLOCKED)
  748. vti->builtBuildings.erase(BuildingID::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  749. //Early check for #1444-like problems
  750. for([[maybe_unused]] const auto & building : vti->builtBuildings)
  751. {
  752. assert(vti->getTown()->buildings.at(building) != nullptr);
  753. }
  754. //town events
  755. for(CCastleEvent &ev : vti->events)
  756. {
  757. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  758. if (vstd::contains(ev.buildings,hordes[i])) //if we have horde for this level
  759. {
  760. ev.buildings.erase(hordes[i]);
  761. if (vti->getTown()->hordeLvl.at(0) == i)
  762. ev.buildings.insert(BuildingID::HORDE_1);
  763. if (vti->getTown()->hordeLvl.at(1) == i)
  764. ev.buildings.insert(BuildingID::HORDE_2);
  765. }
  766. }
  767. //init spells
  768. vti->spells.resize(GameConstants::SPELL_LEVELS);
  769. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  770. {
  771. const auto * s = vti->obligatorySpells[z].toSpell();
  772. vti->spells[s->getLevel()-1].push_back(s->id);
  773. vti->possibleSpells -= s->id;
  774. }
  775. while(!vti->possibleSpells.empty())
  776. {
  777. ui32 total=0;
  778. int sel = -1;
  779. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  780. total += vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  781. if (total == 0) // remaining spells have 0 probability
  782. break;
  783. auto r = getRandomGenerator().nextInt(total - 1);
  784. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  785. {
  786. r -= vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  787. if(r<0)
  788. {
  789. sel = ps;
  790. break;
  791. }
  792. }
  793. if(sel<0)
  794. sel=0;
  795. const auto * s = vti->possibleSpells[sel].toSpell();
  796. vti->spells[s->getLevel()-1].push_back(s->id);
  797. vti->possibleSpells -= s->id;
  798. }
  799. vti->possibleSpells.clear();
  800. if(vti->getOwner() != PlayerColor::NEUTRAL)
  801. getPlayerState(vti->getOwner())->towns.emplace_back(vti);
  802. }
  803. }
  804. void CGameState::initMapObjects()
  805. {
  806. logGlobal->debug("\tObject initialization");
  807. // objCaller->preInit();
  808. for(CGObjectInstance *obj : map->objects)
  809. {
  810. if(obj)
  811. {
  812. logGlobal->trace("Calling Init for object %d, %s, %s", obj->id.getNum(), obj->typeName, obj->subTypeName);
  813. obj->initObj(getRandomGenerator());
  814. }
  815. }
  816. for(CGObjectInstance *obj : map->objects)
  817. {
  818. if(!obj)
  819. continue;
  820. switch (obj->ID)
  821. {
  822. case Obj::QUEST_GUARD:
  823. case Obj::SEER_HUT:
  824. {
  825. auto * q = dynamic_cast<CGSeerHut *>(obj);
  826. assert (q);
  827. q->setObjToKill();
  828. }
  829. }
  830. }
  831. CGSubterraneanGate::postInit(); //pairing subterranean gates
  832. map->calculateGuardingGreaturePositions(); //calculate once again when all the guards are placed and initialized
  833. }
  834. void CGameState::placeHeroesInTowns()
  835. {
  836. for(auto & player : players)
  837. {
  838. if(player.first == PlayerColor::NEUTRAL)
  839. continue;
  840. for(CGHeroInstance * h : player.second.heroes)
  841. {
  842. for(CGTownInstance * t : player.second.towns)
  843. {
  844. if(h->visitablePos().z != t->visitablePos().z)
  845. continue;
  846. bool heroOnTownBlockableTile = t->blockingAt(h->visitablePos().x, h->visitablePos().y);
  847. // current hero position is at one of blocking tiles of current town
  848. // assume that this hero should be visiting the town (H3M format quirk) and move hero to correct position
  849. if (heroOnTownBlockableTile)
  850. {
  851. int3 correctedPos = h->convertFromVisitablePos(t->visitablePos());
  852. map->removeBlockVisTiles(h);
  853. h->pos = correctedPos;
  854. map->addBlockVisTiles(h);
  855. assert(t->visitableAt(h->visitablePos().x, h->visitablePos().y));
  856. }
  857. }
  858. }
  859. }
  860. }
  861. void CGameState::initVisitingAndGarrisonedHeroes()
  862. {
  863. for(auto & player : players)
  864. {
  865. if(player.first == PlayerColor::NEUTRAL)
  866. continue;
  867. //init visiting and garrisoned heroes
  868. for(CGHeroInstance * h : player.second.heroes)
  869. {
  870. for(CGTownInstance * t : player.second.towns)
  871. {
  872. if(h->visitablePos().z != t->visitablePos().z)
  873. continue;
  874. if (t->visitableAt(h->visitablePos().x, h->visitablePos().y))
  875. {
  876. assert(t->visitingHero == nullptr);
  877. t->setVisitingHero(h);
  878. }
  879. }
  880. }
  881. }
  882. for (auto hero : map->heroesOnMap)
  883. {
  884. if (hero->visitedTown)
  885. {
  886. assert (hero->visitedTown->visitingHero == hero);
  887. }
  888. }
  889. }
  890. const BattleInfo * CGameState::getBattle(const PlayerColor & player) const
  891. {
  892. if (!player.isValidPlayer())
  893. return nullptr;
  894. for (const auto & battlePtr : currentBattles)
  895. if (battlePtr->sides[0].color == player || battlePtr->sides[1].color == player)
  896. return battlePtr.get();
  897. return nullptr;
  898. }
  899. const BattleInfo * CGameState::getBattle(const BattleID & battle) const
  900. {
  901. for (const auto & battlePtr : currentBattles)
  902. if (battlePtr->battleID == battle)
  903. return battlePtr.get();
  904. return nullptr;
  905. }
  906. BattleInfo * CGameState::getBattle(const BattleID & battle)
  907. {
  908. for (const auto & battlePtr : currentBattles)
  909. if (battlePtr->battleID == battle)
  910. return battlePtr.get();
  911. return nullptr;
  912. }
  913. BattleField CGameState::battleGetBattlefieldType(int3 tile, CRandomGenerator & rand)
  914. {
  915. assert(tile.valid());
  916. if(!tile.valid())
  917. return BattleField::NONE;
  918. const TerrainTile &t = map->getTile(tile);
  919. auto * topObject = t.visitableObjects.front();
  920. if(topObject && topObject->getBattlefield() != BattleField::NONE)
  921. {
  922. return topObject->getBattlefield();
  923. }
  924. for(auto &obj : map->objects)
  925. {
  926. //look only for objects covering given tile
  927. if( !obj || obj->pos.z != tile.z || !obj->coveringAt(tile.x, tile.y))
  928. continue;
  929. auto customBattlefield = obj->getBattlefield();
  930. if(customBattlefield != BattleField::NONE)
  931. return customBattlefield;
  932. }
  933. if(map->isCoastalTile(tile)) //coastal tile is always ground
  934. return BattleField(*VLC->identifiers()->getIdentifier("core", "battlefield.sand_shore"));
  935. return BattleField(*RandomGeneratorUtil::nextItem(t.terType->battleFields, rand));
  936. }
  937. void CGameState::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  938. {
  939. assert(obj);
  940. assert(obj->hasStackAtSlot(stackPos));
  941. out = fillUpgradeInfo(obj->getStack(stackPos));
  942. }
  943. UpgradeInfo CGameState::fillUpgradeInfo(const CStackInstance &stack) const
  944. {
  945. UpgradeInfo ret;
  946. const CCreature *base = stack.type;
  947. if (stack.armyObj->ID == Obj::HERO)
  948. {
  949. auto hero = dynamic_cast<const CGHeroInstance *>(stack.armyObj);
  950. hero->fillUpgradeInfo(ret, stack);
  951. if (hero->visitedTown)
  952. {
  953. hero->visitedTown->fillUpgradeInfo(ret, stack);
  954. }
  955. else
  956. {
  957. auto object = vstd::frontOrNull(getVisitableObjs(hero->visitablePos()));
  958. auto upgradeSource = dynamic_cast<const ICreatureUpgrader*>(object);
  959. if (object != hero && upgradeSource != nullptr)
  960. upgradeSource->fillUpgradeInfo(ret, stack);
  961. }
  962. }
  963. if (stack.armyObj->ID == Obj::TOWN)
  964. {
  965. auto town = dynamic_cast<const CGTownInstance *>(stack.armyObj);
  966. town->fillUpgradeInfo(ret, stack);
  967. }
  968. if(!ret.newID.empty())
  969. ret.oldID = base->getId();
  970. for (ResourceSet &cost : ret.cost)
  971. cost.positive(); //upgrade cost can't be negative, ignore missing resources
  972. return ret;
  973. }
  974. PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  975. {
  976. if ( color1 == color2 )
  977. return PlayerRelations::SAME_PLAYER;
  978. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  979. return PlayerRelations::ENEMIES;
  980. const TeamState * ts = getPlayerTeam(color1);
  981. if (ts && vstd::contains(ts->players, color2))
  982. return PlayerRelations::ALLIES;
  983. return PlayerRelations::ENEMIES;
  984. }
  985. void CGameState::apply(CPack *pack)
  986. {
  987. ui16 typ = typeList.getTypeID(pack);
  988. applier->getApplier(typ)->applyOnGS(this, pack);
  989. }
  990. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out)
  991. {
  992. calculatePaths(std::make_shared<SingleHeroPathfinderConfig>(out, this, hero));
  993. }
  994. void CGameState::calculatePaths(const std::shared_ptr<PathfinderConfig> & config)
  995. {
  996. //FIXME: creating pathfinder is costly, maybe reset / clear is enough?
  997. CPathfinder pathfinder(this, config);
  998. pathfinder.calculatePaths();
  999. }
  1000. /**
  1001. * Tells if the tile is guarded by a monster as well as the position
  1002. * of the monster that will attack on it.
  1003. *
  1004. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1005. * the monster guarding the tile.
  1006. */
  1007. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1008. {
  1009. std::vector<CGObjectInstance*> guards;
  1010. const int3 originalPos = pos;
  1011. if (!map->isInTheMap(pos))
  1012. return guards;
  1013. const TerrainTile &posTile = map->getTile(pos);
  1014. if (posTile.visitable)
  1015. {
  1016. for (CGObjectInstance* obj : posTile.visitableObjects)
  1017. {
  1018. if(obj->isBlockedVisitable())
  1019. {
  1020. if (obj->ID == Obj::MONSTER) // Monster
  1021. guards.push_back(obj);
  1022. }
  1023. }
  1024. }
  1025. pos -= int3(1, 1, 0); // Start with top left.
  1026. for (int dx = 0; dx < 3; dx++)
  1027. {
  1028. for (int dy = 0; dy < 3; dy++)
  1029. {
  1030. if (map->isInTheMap(pos))
  1031. {
  1032. const auto & tile = map->getTile(pos);
  1033. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1034. {
  1035. for (CGObjectInstance* obj : tile.visitableObjects)
  1036. {
  1037. if (obj->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1038. {
  1039. guards.push_back(obj);
  1040. }
  1041. }
  1042. }
  1043. }
  1044. pos.y++;
  1045. }
  1046. pos.y -= 3;
  1047. pos.x++;
  1048. }
  1049. return guards;
  1050. }
  1051. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1052. {
  1053. return gs->map->guardingCreaturePositions[pos.z][pos.x][pos.y];
  1054. }
  1055. void CGameState::updateRumor()
  1056. {
  1057. static std::vector<RumorState::ERumorType> rumorTypes = {RumorState::TYPE_MAP, RumorState::TYPE_SPECIAL, RumorState::TYPE_RAND, RumorState::TYPE_RAND};
  1058. std::vector<RumorState::ERumorTypeSpecial> sRumorTypes = {
  1059. RumorState::RUMOR_OBELISKS, RumorState::RUMOR_ARTIFACTS, RumorState::RUMOR_ARMY, RumorState::RUMOR_INCOME};
  1060. if(map->grailPos.valid()) // Grail should always be on map, but I had related crash I didn't manage to reproduce
  1061. sRumorTypes.push_back(RumorState::RUMOR_GRAIL);
  1062. int rumorId = -1;
  1063. int rumorExtra = -1;
  1064. auto & rand = getRandomGenerator();
  1065. rumor.type = *RandomGeneratorUtil::nextItem(rumorTypes, rand);
  1066. do
  1067. {
  1068. switch(rumor.type)
  1069. {
  1070. case RumorState::TYPE_SPECIAL:
  1071. {
  1072. SThievesGuildInfo tgi;
  1073. obtainPlayersStats(tgi, 20);
  1074. rumorId = *RandomGeneratorUtil::nextItem(sRumorTypes, rand);
  1075. if(rumorId == RumorState::RUMOR_GRAIL)
  1076. {
  1077. rumorExtra = getTile(map->grailPos)->terType->getIndex();
  1078. break;
  1079. }
  1080. std::vector<PlayerColor> players = {};
  1081. switch(rumorId)
  1082. {
  1083. case RumorState::RUMOR_OBELISKS:
  1084. players = tgi.obelisks[0];
  1085. break;
  1086. case RumorState::RUMOR_ARTIFACTS:
  1087. players = tgi.artifacts[0];
  1088. break;
  1089. case RumorState::RUMOR_ARMY:
  1090. players = tgi.army[0];
  1091. break;
  1092. case RumorState::RUMOR_INCOME:
  1093. players = tgi.income[0];
  1094. break;
  1095. }
  1096. rumorExtra = RandomGeneratorUtil::nextItem(players, rand)->getNum();
  1097. break;
  1098. }
  1099. case RumorState::TYPE_MAP:
  1100. // Makes sure that map rumors only used if there enough rumors too choose from
  1101. if(!map->rumors.empty() && (map->rumors.size() > 1 || !rumor.last.count(RumorState::TYPE_MAP)))
  1102. {
  1103. rumorId = rand.nextInt((int)map->rumors.size() - 1);
  1104. break;
  1105. }
  1106. else
  1107. rumor.type = RumorState::TYPE_RAND;
  1108. [[fallthrough]];
  1109. case RumorState::TYPE_RAND:
  1110. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randtvrn");
  1111. rumorId = rand.nextInt((int)vector.size() - 1);
  1112. break;
  1113. }
  1114. }
  1115. while(!rumor.update(rumorId, rumorExtra));
  1116. }
  1117. bool CGameState::isVisible(int3 pos, const std::optional<PlayerColor> & player) const
  1118. {
  1119. if (!map->isInTheMap(pos))
  1120. return false;
  1121. if (!player)
  1122. return true;
  1123. if(player == PlayerColor::NEUTRAL)
  1124. return false;
  1125. if(player->isSpectator())
  1126. return true;
  1127. return (*getPlayerTeam(*player)->fogOfWarMap)[pos.z][pos.x][pos.y];
  1128. }
  1129. bool CGameState::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const
  1130. {
  1131. if(!player)
  1132. return true;
  1133. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  1134. if (player == obj->tempOwner)
  1135. return true;
  1136. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1137. return false;
  1138. //object is visible when at least one blocked tile is visible
  1139. for(int fy=0; fy < obj->getHeight(); ++fy)
  1140. {
  1141. for(int fx=0; fx < obj->getWidth(); ++fx)
  1142. {
  1143. int3 pos = obj->pos + int3(-fx, -fy, 0);
  1144. if ( map->isInTheMap(pos) &&
  1145. obj->coveringAt(pos.x, pos.y) &&
  1146. isVisible(pos, *player))
  1147. return true;
  1148. }
  1149. }
  1150. return false;
  1151. }
  1152. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1153. {
  1154. const TerrainTile * pom = &map->getTile(dst);
  1155. return map->checkForVisitableDir(src, pom, dst);
  1156. }
  1157. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(const PlayerColor & player) const
  1158. {
  1159. const MetaString messageWonSelf = MetaString::createFromTextID("core.genrltxt.659");
  1160. const MetaString messageWonOther = MetaString::createFromTextID("core.genrltxt.5");
  1161. const MetaString messageLostSelf = MetaString::createFromTextID("core.genrltxt.7");
  1162. const MetaString messageLostOther = MetaString::createFromTextID("core.genrltxt.8");
  1163. auto evaluateEvent = [=](const EventCondition & condition)
  1164. {
  1165. return this->checkForVictory(player, condition);
  1166. };
  1167. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1168. //cheater or tester, but has entered the code...
  1169. if (p->enteredWinningCheatCode)
  1170. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  1171. if (p->enteredLosingCheatCode)
  1172. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1173. for (const TriggeredEvent & event : map->triggeredEvents)
  1174. {
  1175. if (event.trigger.test(evaluateEvent))
  1176. {
  1177. if (event.effect.type == EventEffect::VICTORY)
  1178. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  1179. if (event.effect.type == EventEffect::DEFEAT)
  1180. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  1181. }
  1182. }
  1183. if (checkForStandardLoss(player))
  1184. {
  1185. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1186. }
  1187. return EVictoryLossCheckResult();
  1188. }
  1189. bool CGameState::checkForVictory(const PlayerColor & player, const EventCondition & condition) const
  1190. {
  1191. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  1192. switch (condition.condition)
  1193. {
  1194. case EventCondition::STANDARD_WIN:
  1195. {
  1196. return player == checkForStandardWin();
  1197. }
  1198. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  1199. {
  1200. for(const auto & elem : p->heroes)
  1201. if(elem->hasArt(ArtifactID(condition.objectType)))
  1202. return true;
  1203. return false;
  1204. }
  1205. case EventCondition::HAVE_CREATURES:
  1206. {
  1207. //check if in players armies there is enough creatures
  1208. int total = 0; //creature counter
  1209. for(auto object : map->objects)
  1210. {
  1211. const CArmedInstance *ai = nullptr;
  1212. if(object
  1213. && object->tempOwner == player //object controlled by player
  1214. && (ai = dynamic_cast<const CArmedInstance *>(object.get()))) //contains army
  1215. {
  1216. for(const auto & elem : ai->Slots()) //iterate through army
  1217. if(elem.second->type->getIndex() == condition.objectType) //it's searched creature
  1218. total += elem.second->count;
  1219. }
  1220. }
  1221. return total >= condition.value;
  1222. }
  1223. case EventCondition::HAVE_RESOURCES:
  1224. {
  1225. return p->resources[condition.objectType] >= condition.value;
  1226. }
  1227. case EventCondition::HAVE_BUILDING:
  1228. {
  1229. if (condition.object) // specific town
  1230. {
  1231. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  1232. return (t->tempOwner == player && t->hasBuilt(BuildingID(condition.objectType)));
  1233. }
  1234. else // any town
  1235. {
  1236. for (const CGTownInstance * t : p->towns)
  1237. {
  1238. if (t->hasBuilt(BuildingID(condition.objectType)))
  1239. return true;
  1240. }
  1241. return false;
  1242. }
  1243. }
  1244. case EventCondition::DESTROY:
  1245. {
  1246. if (condition.object) // mode A - destroy specific object of this type
  1247. {
  1248. if(const auto * hero = dynamic_cast<const CGHeroInstance *>(condition.object))
  1249. return boost::range::find(gs->map->heroesOnMap, hero) == gs->map->heroesOnMap.end();
  1250. else
  1251. return getObj(condition.object->id) == nullptr;
  1252. }
  1253. else
  1254. {
  1255. for(const auto & elem : map->objects) // mode B - destroy all objects of this type
  1256. {
  1257. if(elem && elem->ID.getNum() == condition.objectType)
  1258. return false;
  1259. }
  1260. return true;
  1261. }
  1262. }
  1263. case EventCondition::CONTROL:
  1264. {
  1265. // list of players that need to control object to fulfull condition
  1266. // NOTE: cgameinfocallback specified explicitly in order to get const version
  1267. const auto & team = CGameInfoCallback::getPlayerTeam(player)->players;
  1268. if (condition.object) // mode A - flag one specific object, like town
  1269. {
  1270. return team.count(condition.object->tempOwner) != 0;
  1271. }
  1272. else
  1273. {
  1274. for(const auto & elem : map->objects) // mode B - flag all objects of this type
  1275. {
  1276. //check not flagged objs
  1277. if ( elem && elem->ID.getNum() == condition.objectType && team.count(elem->tempOwner) == 0 )
  1278. return false;
  1279. }
  1280. return true;
  1281. }
  1282. }
  1283. case EventCondition::TRANSPORT:
  1284. {
  1285. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  1286. return (t->visitingHero && t->visitingHero->hasArt(ArtifactID(condition.objectType))) ||
  1287. (t->garrisonHero && t->garrisonHero->hasArt(ArtifactID(condition.objectType)));
  1288. }
  1289. case EventCondition::DAYS_PASSED:
  1290. {
  1291. return (si32)gs->day > condition.value;
  1292. }
  1293. case EventCondition::IS_HUMAN:
  1294. {
  1295. return p->human ? condition.value == 1 : condition.value == 0;
  1296. }
  1297. case EventCondition::DAYS_WITHOUT_TOWN:
  1298. {
  1299. if (p->daysWithoutCastle)
  1300. return p->daysWithoutCastle >= condition.value;
  1301. else
  1302. return false;
  1303. }
  1304. case EventCondition::CONST_VALUE:
  1305. {
  1306. return condition.value; // just convert to bool
  1307. }
  1308. case EventCondition::HAVE_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::HAVE_BUILDING_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. case EventCondition::DESTROY_0:
  1321. {
  1322. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  1323. //TODO: support new condition format
  1324. return false;
  1325. }
  1326. default:
  1327. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  1328. return false;
  1329. }
  1330. }
  1331. PlayerColor CGameState::checkForStandardWin() const
  1332. {
  1333. //std victory condition is:
  1334. //all enemies lost
  1335. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  1336. TeamID winnerTeam = TeamID::NO_TEAM;
  1337. for(const auto & elem : players)
  1338. {
  1339. if(elem.second.status == EPlayerStatus::INGAME && elem.first.isValidPlayer())
  1340. {
  1341. if(supposedWinner == PlayerColor::NEUTRAL)
  1342. {
  1343. //first player remaining ingame - candidate for victory
  1344. supposedWinner = elem.second.color;
  1345. winnerTeam = elem.second.team;
  1346. }
  1347. else if(winnerTeam != elem.second.team)
  1348. {
  1349. //current candidate has enemy remaining in game -> no vicotry
  1350. return PlayerColor::NEUTRAL;
  1351. }
  1352. }
  1353. }
  1354. return supposedWinner;
  1355. }
  1356. bool CGameState::checkForStandardLoss(const PlayerColor & player) const
  1357. {
  1358. //std loss condition is: player lost all towns and heroes
  1359. const PlayerState & pState = *CGameInfoCallback::getPlayerState(player);
  1360. return pState.checkVanquished();
  1361. }
  1362. struct statsHLP
  1363. {
  1364. using TStat = std::pair<PlayerColor, si64>;
  1365. //converts [<player's color, value>] to vec[place] -> platers
  1366. static std::vector< std::vector< PlayerColor > > getRank( std::vector<TStat> stats )
  1367. {
  1368. std::sort(stats.begin(), stats.end(), statsHLP());
  1369. //put first element
  1370. std::vector< std::vector<PlayerColor> > ret;
  1371. std::vector<PlayerColor> tmp;
  1372. tmp.push_back( stats[0].first );
  1373. ret.push_back( tmp );
  1374. //the rest of elements
  1375. for(int g=1; g<stats.size(); ++g)
  1376. {
  1377. if(stats[g].second == stats[g-1].second)
  1378. {
  1379. (ret.end()-1)->push_back( stats[g].first );
  1380. }
  1381. else
  1382. {
  1383. //create next occupied rank
  1384. std::vector<PlayerColor> tmp;
  1385. tmp.push_back(stats[g].first);
  1386. ret.push_back(tmp);
  1387. }
  1388. }
  1389. return ret;
  1390. }
  1391. bool operator()(const TStat & a, const TStat & b) const
  1392. {
  1393. return a.second > b.second;
  1394. }
  1395. static const CGHeroInstance * findBestHero(CGameState * gs, const PlayerColor & color)
  1396. {
  1397. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  1398. if(h.empty())
  1399. return nullptr;
  1400. //best hero will be that with highest exp
  1401. int best = 0;
  1402. for(int b=1; b<h.size(); ++b)
  1403. {
  1404. if(h[b]->exp > h[best]->exp)
  1405. {
  1406. best = b;
  1407. }
  1408. }
  1409. return h[best];
  1410. }
  1411. //calculates total number of artifacts that belong to given player
  1412. static int getNumberOfArts(const PlayerState * ps)
  1413. {
  1414. int ret = 0;
  1415. for(auto h : ps->heroes)
  1416. {
  1417. ret += (int)h->artifactsInBackpack.size() + (int)h->artifactsWorn.size();
  1418. }
  1419. return ret;
  1420. }
  1421. // get total strength of player army
  1422. static si64 getArmyStrength(const PlayerState * ps)
  1423. {
  1424. si64 str = 0;
  1425. for(auto h : ps->heroes)
  1426. {
  1427. if(!h->inTownGarrison) //original h3 behavior
  1428. str += h->getArmyStrength();
  1429. }
  1430. return str;
  1431. }
  1432. // get total gold income
  1433. static int getIncome(const PlayerState * ps)
  1434. {
  1435. int totalIncome = 0;
  1436. const CGObjectInstance * heroOrTown = nullptr;
  1437. //Heroes can produce gold as well - skill, specialty or arts
  1438. for(const auto & h : ps->heroes)
  1439. {
  1440. totalIncome += h->valOfBonuses(Selector::typeSubtype(BonusType::GENERATE_RESOURCE, BonusSubtypeID(GameResID(GameResID::GOLD))));
  1441. if(!heroOrTown)
  1442. heroOrTown = h;
  1443. }
  1444. //Add town income of all towns
  1445. for(const auto & t : ps->towns)
  1446. {
  1447. totalIncome += t->dailyIncome()[EGameResID::GOLD];
  1448. if(!heroOrTown)
  1449. heroOrTown = t;
  1450. }
  1451. /// FIXME: Dirty dirty hack
  1452. /// Stats helper need some access to gamestate.
  1453. std::vector<const CGObjectInstance *> ownedObjects;
  1454. for(const CGObjectInstance * obj : heroOrTown->cb->gameState()->map->objects)
  1455. {
  1456. if(obj && obj->tempOwner == ps->color)
  1457. ownedObjects.push_back(obj);
  1458. }
  1459. /// This is code from CPlayerSpecificInfoCallback::getMyObjects
  1460. /// I'm really need to find out about callback interface design...
  1461. for(const auto * object : ownedObjects)
  1462. {
  1463. //Mines
  1464. if ( object->ID == Obj::MINE )
  1465. {
  1466. const auto * mine = dynamic_cast<const CGMine *>(object);
  1467. assert(mine);
  1468. if (mine->producedResource == EGameResID::GOLD)
  1469. totalIncome += mine->producedQuantity;
  1470. }
  1471. }
  1472. return totalIncome;
  1473. }
  1474. };
  1475. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  1476. {
  1477. auto playerInactive = [&](const PlayerColor & color)
  1478. {
  1479. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  1480. };
  1481. #define FILL_FIELD(FIELD, VAL_GETTER) \
  1482. { \
  1483. std::vector< std::pair< PlayerColor, si64 > > stats; \
  1484. for(auto g = players.begin(); g != players.end(); ++g) \
  1485. { \
  1486. if(playerInactive(g->second.color)) \
  1487. continue; \
  1488. std::pair< PlayerColor, si64 > stat; \
  1489. stat.first = g->second.color; \
  1490. stat.second = VAL_GETTER; \
  1491. stats.push_back(stat); \
  1492. } \
  1493. tgi.FIELD = statsHLP::getRank(stats); \
  1494. }
  1495. for(auto & elem : players)
  1496. {
  1497. if(!playerInactive(elem.second.color))
  1498. tgi.playerColors.push_back(elem.second.color);
  1499. }
  1500. if(level >= 0) //num of towns & num of heroes
  1501. {
  1502. //num of towns
  1503. FILL_FIELD(numOfTowns, g->second.towns.size())
  1504. //num of heroes
  1505. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  1506. }
  1507. if(level >= 1) //best hero's portrait
  1508. {
  1509. for(const auto & player : players)
  1510. {
  1511. if(playerInactive(player.second.color))
  1512. continue;
  1513. const CGHeroInstance * best = statsHLP::findBestHero(this, player.second.color);
  1514. InfoAboutHero iah;
  1515. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  1516. iah.army.clear();
  1517. tgi.colorToBestHero[player.second.color] = iah;
  1518. }
  1519. }
  1520. if(level >= 2) //gold
  1521. {
  1522. FILL_FIELD(gold, g->second.resources[EGameResID::GOLD])
  1523. }
  1524. if(level >= 2) //wood & ore
  1525. {
  1526. FILL_FIELD(woodOre, g->second.resources[EGameResID::WOOD] + g->second.resources[EGameResID::ORE])
  1527. }
  1528. if(level >= 3) //mercury, sulfur, crystal, gems
  1529. {
  1530. FILL_FIELD(mercSulfCrystGems, g->second.resources[EGameResID::MERCURY] + g->second.resources[EGameResID::SULFUR] + g->second.resources[EGameResID::CRYSTAL] + g->second.resources[EGameResID::GEMS])
  1531. }
  1532. if(level >= 3) //obelisks found
  1533. {
  1534. auto getObeliskVisited = [](const TeamID & t)
  1535. {
  1536. if(CGObelisk::visited.count(t))
  1537. return CGObelisk::visited[t];
  1538. else
  1539. return ui8(0);
  1540. };
  1541. FILL_FIELD(obelisks, getObeliskVisited(gs->getPlayerTeam(g->second.color)->id))
  1542. }
  1543. if(level >= 4) //artifacts
  1544. {
  1545. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  1546. }
  1547. if(level >= 4) //army strength
  1548. {
  1549. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  1550. }
  1551. if(level >= 5) //income
  1552. {
  1553. FILL_FIELD(income, statsHLP::getIncome(&g->second))
  1554. }
  1555. if(level >= 2) //best hero's stats
  1556. {
  1557. //already set in lvl 1 handling
  1558. }
  1559. if(level >= 3) //personality
  1560. {
  1561. for(const auto & player : players)
  1562. {
  1563. if(playerInactive(player.second.color)) //do nothing for neutral player
  1564. continue;
  1565. if(player.second.human)
  1566. {
  1567. tgi.personality[player.second.color] = EAiTactic::NONE;
  1568. }
  1569. else //AI
  1570. {
  1571. tgi.personality[player.second.color] = map->players[player.second.color.getNum()].aiTactic;
  1572. }
  1573. }
  1574. }
  1575. if(level >= 4) //best creature
  1576. {
  1577. //best creatures belonging to player (highest AI value)
  1578. for(const auto & player : players)
  1579. {
  1580. if(playerInactive(player.second.color)) //do nothing for neutral player
  1581. continue;
  1582. int bestCre = -1; //best creature's ID
  1583. for(const auto & elem : player.second.heroes)
  1584. {
  1585. for(const auto & it : elem->Slots())
  1586. {
  1587. int toCmp = it.second->type->getId(); //ID of creature we should compare with the best one
  1588. if(bestCre == -1 || VLC->creh->objects[bestCre]->getAIValue() < VLC->creh->objects[toCmp]->getAIValue())
  1589. {
  1590. bestCre = toCmp;
  1591. }
  1592. }
  1593. }
  1594. tgi.bestCreature[player.second.color] = bestCre;
  1595. }
  1596. }
  1597. #undef FILL_FIELD
  1598. }
  1599. void CGameState::buildBonusSystemTree()
  1600. {
  1601. buildGlobalTeamPlayerTree();
  1602. attachArmedObjects();
  1603. // for(CGTownInstance *t : map->towns)
  1604. // {
  1605. // t->deserializationFix();
  1606. // }
  1607. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  1608. // are provided on initializing / deserializing
  1609. // NOTE: calling deserializationFix() might be more correct option, but might lead to side effects
  1610. for (auto hero : map->heroesOnMap)
  1611. hero->boatDeserializationFix();
  1612. }
  1613. void CGameState::deserializationFix()
  1614. {
  1615. buildGlobalTeamPlayerTree();
  1616. attachArmedObjects();
  1617. }
  1618. void CGameState::buildGlobalTeamPlayerTree()
  1619. {
  1620. for(auto & team : teams)
  1621. {
  1622. TeamState * t = &team.second;
  1623. t->attachTo(globalEffects);
  1624. for(const PlayerColor & teamMember : team.second.players)
  1625. {
  1626. PlayerState *p = getPlayerState(teamMember);
  1627. assert(p);
  1628. p->attachTo(*t);
  1629. }
  1630. }
  1631. }
  1632. void CGameState::attachArmedObjects()
  1633. {
  1634. for(CGObjectInstance *obj : map->objects)
  1635. {
  1636. if(auto * armed = dynamic_cast<CArmedInstance *>(obj))
  1637. {
  1638. armed->whatShouldBeAttached().attachTo(armed->whereShouldBeAttached(this));
  1639. }
  1640. }
  1641. }
  1642. bool CGameState::giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid)
  1643. {
  1644. CArtifact * const artifact = VLC->arth->objects[aid]; //pointer to constant object
  1645. CArtifactInstance * ai = ArtifactUtils::createNewArtifactInstance(artifact);
  1646. map->addNewArtifactInstance(ai);
  1647. auto slot = ArtifactUtils::getArtAnyPosition(h, aid);
  1648. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  1649. {
  1650. ai->putAt(*h, slot);
  1651. return true;
  1652. }
  1653. else
  1654. {
  1655. return false;
  1656. }
  1657. }
  1658. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  1659. {
  1660. std::set<HeroTypeID> ret;
  1661. for(int i = 0; i < map->allowedHeroes.size(); i++)
  1662. if(map->allowedHeroes[i] || alsoIncludeNotAllowed)
  1663. ret.insert(HeroTypeID(i));
  1664. for(const auto & playerSettingPair : scenarioOps->playerInfos) //remove uninitialized yet heroes picked for start by other players
  1665. {
  1666. if(playerSettingPair.second.hero != HeroTypeID::RANDOM)
  1667. ret -= HeroTypeID(playerSettingPair.second.hero);
  1668. }
  1669. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1670. {
  1671. if(hero->type)
  1672. ret -= hero->type->getId();
  1673. else
  1674. ret -= hero->getHeroType();
  1675. }
  1676. for(auto obj : map->objects) //prisons
  1677. {
  1678. auto * hero = dynamic_cast<const CGHeroInstance *>(obj.get());
  1679. if(hero && hero->ID == Obj::PRISON)
  1680. ret -= hero->getHeroType();
  1681. }
  1682. return ret;
  1683. }
  1684. bool CGameState::isUsedHero(const HeroTypeID & hid) const
  1685. {
  1686. return getUsedHero(hid);
  1687. }
  1688. CGHeroInstance * CGameState::getUsedHero(const HeroTypeID & hid) const
  1689. {
  1690. for(auto obj : map->objects) //prisons
  1691. {
  1692. if (!obj)
  1693. continue;
  1694. if ( obj->ID !=Obj::PRISON && obj->ID != Obj::HERO)
  1695. continue;
  1696. auto * hero = dynamic_cast<CGHeroInstance *>(obj.get());
  1697. assert(hero);
  1698. if (hero->getHeroType() == hid)
  1699. return hero;
  1700. }
  1701. return nullptr;
  1702. }
  1703. bool RumorState::update(int id, int extra)
  1704. {
  1705. if(vstd::contains(last, type))
  1706. {
  1707. if(last[type].first != id)
  1708. {
  1709. last[type].first = id;
  1710. last[type].second = extra;
  1711. }
  1712. else
  1713. return false;
  1714. }
  1715. else
  1716. last[type] = std::make_pair(id, extra);
  1717. return true;
  1718. }
  1719. TeamState::TeamState()
  1720. {
  1721. setNodeType(TEAM);
  1722. fogOfWarMap = std::make_shared<boost::multi_array<ui8, 3>>();
  1723. }
  1724. TeamState::TeamState(TeamState && other) noexcept:
  1725. CBonusSystemNode(std::move(other)),
  1726. id(other.id)
  1727. {
  1728. std::swap(players, other.players);
  1729. std::swap(fogOfWarMap, other.fogOfWarMap);
  1730. }
  1731. CRandomGenerator & CGameState::getRandomGenerator()
  1732. {
  1733. return rand;
  1734. }
  1735. VCMI_LIB_NAMESPACE_END