CGameState.cpp 49 KB

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