CGameState.cpp 49 KB

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