CGameState.cpp 55 KB

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