CGameState.cpp 55 KB

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