CGameState.cpp 55 KB

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