CGameState.cpp 50 KB

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