CGameState.cpp 56 KB

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