CGameInfoCallback.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. /*
  2. * CGameInfoCallback.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 "CGameInfoCallback.h"
  12. #include "gameState/CGameState.h"
  13. #include "gameState/InfoAboutArmy.h"
  14. #include "gameState/SThievesGuildInfo.h"
  15. #include "gameState/TavernHeroesPool.h"
  16. #include "gameState/QuestInfo.h"
  17. #include "mapObjects/CGHeroInstance.h"
  18. #include "mapObjects/CGTownInstance.h"
  19. #include "mapObjects/MiscObjects.h"
  20. #include "networkPacks/ArtifactLocation.h"
  21. #include "CGeneralTextHandler.h"
  22. #include "StartInfo.h" // for StartInfo
  23. #include "battle/BattleInfo.h" // for BattleInfo
  24. #include "GameSettings.h"
  25. #include "TerrainHandler.h"
  26. #include "spells/CSpellHandler.h"
  27. #include "mapping/CMap.h"
  28. #include "CPlayerState.h"
  29. VCMI_LIB_NAMESPACE_BEGIN
  30. //TODO make clean
  31. #define ERROR_VERBOSE_OR_NOT_RET_VAL_IF(cond, verbose, txt, retVal) do {if(cond){if(verbose)logGlobal->error("%s: %s",BOOST_CURRENT_FUNCTION, txt); return retVal;}} while(0)
  32. #define ERROR_RET_IF(cond, txt) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return;}} while(0)
  33. #define ERROR_RET_VAL_IF(cond, txt, retVal) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return retVal;}} while(0)
  34. PlayerColor CGameInfoCallback::getOwner(ObjectInstanceID heroID) const
  35. {
  36. const CGObjectInstance *obj = getObj(heroID);
  37. ERROR_RET_VAL_IF(!obj, "No such object!", PlayerColor::CANNOT_DETERMINE);
  38. return obj->tempOwner;
  39. }
  40. int CGameInfoCallback::getResource(PlayerColor Player, GameResID which) const
  41. {
  42. const PlayerState *p = getPlayerState(Player);
  43. ERROR_RET_VAL_IF(!p, "No player info!", -1);
  44. ERROR_RET_VAL_IF(p->resources.size() <= which.getNum() || which.getNum() < 0, "No such resource!", -1);
  45. return p->resources[which];
  46. }
  47. const PlayerSettings * CGameInfoCallback::getPlayerSettings(PlayerColor color) const
  48. {
  49. return &gs->scenarioOps->getIthPlayersSettings(color);
  50. }
  51. bool CGameInfoCallback::isAllowed(SpellID id) const
  52. {
  53. return gs->map->allowedSpells.count(id) != 0;
  54. }
  55. bool CGameInfoCallback::isAllowed(ArtifactID id) const
  56. {
  57. return gs->map->allowedArtifact.count(id) != 0;
  58. }
  59. bool CGameInfoCallback::isAllowed(SecondarySkill id) const
  60. {
  61. return gs->map->allowedAbilities.count(id) != 0;
  62. }
  63. std::optional<PlayerColor> CGameInfoCallback::getPlayerID() const
  64. {
  65. return std::nullopt;
  66. }
  67. const Player * CGameInfoCallback::getPlayer(PlayerColor color) const
  68. {
  69. return getPlayerState(color, false);
  70. }
  71. const PlayerState * CGameInfoCallback::getPlayerState(PlayerColor color, bool verbose) const
  72. {
  73. //function written from scratch since it's accessed A LOT by AI
  74. if(!color.isValidPlayer())
  75. {
  76. return nullptr;
  77. }
  78. auto player = gs->players.find(color);
  79. if (player != gs->players.end())
  80. {
  81. if (hasAccess(color))
  82. return &player->second;
  83. else
  84. {
  85. if (verbose)
  86. logGlobal->error("Cannot access player %d info!", color);
  87. return nullptr;
  88. }
  89. }
  90. else
  91. {
  92. if (verbose)
  93. logGlobal->error("Cannot find player %d info!", color);
  94. return nullptr;
  95. }
  96. }
  97. TurnTimerInfo CGameInfoCallback::getPlayerTurnTime(PlayerColor color) const
  98. {
  99. if(!color.isValidPlayer())
  100. {
  101. return TurnTimerInfo{};
  102. }
  103. auto player = gs->players.find(color);
  104. if(player != gs->players.end())
  105. {
  106. return player->second.turnTimer;
  107. }
  108. return TurnTimerInfo{};
  109. }
  110. /************************************************************************/
  111. /* */
  112. /************************************************************************/
  113. const CGObjectInstance* CGameInfoCallback::getObj(ObjectInstanceID objid, bool verbose) const
  114. {
  115. si32 oid = objid.num;
  116. if(oid < 0 || oid >= gs->map->objects.size())
  117. {
  118. if(verbose)
  119. logGlobal->error("Cannot get object with id %d", oid);
  120. return nullptr;
  121. }
  122. const CGObjectInstance *ret = gs->map->objects[oid];
  123. if(!ret)
  124. {
  125. if(verbose)
  126. logGlobal->error("Cannot get object with id %d. Object was removed", oid);
  127. return nullptr;
  128. }
  129. if(!isVisible(ret, getPlayerID()) && ret->tempOwner != getPlayerID())
  130. {
  131. if(verbose)
  132. logGlobal->error("Cannot get object with id %d. Object is not visible.", oid);
  133. return nullptr;
  134. }
  135. return ret;
  136. }
  137. const CGHeroInstance* CGameInfoCallback::getHero(ObjectInstanceID objid) const
  138. {
  139. const CGObjectInstance *obj = getObj(objid, false);
  140. if(obj)
  141. return dynamic_cast<const CGHeroInstance*>(obj);
  142. else
  143. return nullptr;
  144. }
  145. const CGTownInstance* CGameInfoCallback::getTown(ObjectInstanceID objid) const
  146. {
  147. const CGObjectInstance *obj = getObj(objid, false);
  148. if(obj)
  149. return dynamic_cast<const CGTownInstance*>(obj);
  150. else
  151. return nullptr;
  152. }
  153. void CGameInfoCallback::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  154. {
  155. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  156. ERROR_RET_IF(!canGetFullInfo(obj), "Cannot get info about not owned object!");
  157. ERROR_RET_IF(!obj->hasStackAtSlot(stackPos), "There is no such stack!");
  158. gs->fillUpgradeInfo(obj, stackPos, out);
  159. //return gs->fillUpgradeInfo(obj->getStack(stackPos));
  160. }
  161. const StartInfo * CGameInfoCallback::getStartInfo(bool beforeRandomization) const
  162. {
  163. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  164. if(beforeRandomization)
  165. return gs->initialOpts;
  166. else
  167. return gs->scenarioOps;
  168. }
  169. int32_t CGameInfoCallback::getSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  170. {
  171. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  172. ERROR_RET_VAL_IF(!canGetFullInfo(caster), "Cannot get info about caster!", -1);
  173. //if there is a battle
  174. auto casterBattle = gs->getBattle(caster->getOwner());
  175. if(casterBattle)
  176. return casterBattle->battleGetSpellCost(sp, caster);
  177. //if there is no battle
  178. return caster->getSpellCost(sp);
  179. }
  180. int64_t CGameInfoCallback::estimateSpellDamage(const CSpell * sp, const CGHeroInstance * hero) const
  181. {
  182. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  183. ERROR_RET_VAL_IF(hero && !canGetFullInfo(hero), "Cannot get info about caster!", -1);
  184. if(hero) //we see hero's spellbook
  185. return sp->calculateDamage(hero);
  186. else
  187. return 0; //mage guild
  188. }
  189. void CGameInfoCallback::getThievesGuildInfo(SThievesGuildInfo & thi, const CGObjectInstance * obj)
  190. {
  191. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  192. ERROR_RET_IF(!obj, "No guild object!");
  193. ERROR_RET_IF(obj->ID == Obj::TOWN && !canGetFullInfo(obj), "Cannot get info about town guild object!");
  194. //TODO: advmap object -> check if they're visited by our hero
  195. if(obj->ID == Obj::TOWN || obj->ID == Obj::TAVERN)
  196. {
  197. int taverns = 0;
  198. for(auto town : gs->players[*getPlayerID()].towns)
  199. {
  200. if(town->hasBuilt(BuildingID::TAVERN))
  201. taverns++;
  202. if(town->hasBuilt(BuildingSubID::THIEVES_GUILD))
  203. taverns += 2;
  204. }
  205. gs->obtainPlayersStats(thi, taverns);
  206. }
  207. else if(obj->ID == Obj::DEN_OF_THIEVES)
  208. {
  209. gs->obtainPlayersStats(thi, 20);
  210. }
  211. }
  212. int CGameInfoCallback::howManyTowns(PlayerColor Player) const
  213. {
  214. ERROR_RET_VAL_IF(!hasAccess(Player), "Access forbidden!", -1);
  215. return static_cast<int>(gs->players[Player].towns.size());
  216. }
  217. bool CGameInfoCallback::getTownInfo(const CGObjectInstance * town, InfoAboutTown & dest, const CGObjectInstance * selectedObject) const
  218. {
  219. ERROR_RET_VAL_IF(!isVisible(town, getPlayerID()), "Town is not visible!", false); //it's not a town or it's not visible for layer
  220. bool detailed = hasAccess(town->tempOwner);
  221. if(town->ID == Obj::TOWN)
  222. {
  223. if(!detailed && nullptr != selectedObject)
  224. {
  225. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  226. if(nullptr != selectedHero)
  227. detailed = selectedHero->hasVisions(town, BonusCustomSubtype::visionsTowns);
  228. }
  229. dest.initFromTown(dynamic_cast<const CGTownInstance *>(town), detailed);
  230. }
  231. else if(town->ID == Obj::GARRISON || town->ID == Obj::GARRISON2)
  232. dest.initFromArmy(dynamic_cast<const CArmedInstance *>(town), detailed);
  233. else
  234. return false;
  235. return true;
  236. }
  237. int3 CGameInfoCallback::guardingCreaturePosition (int3 pos) const //FIXME: redundant?
  238. {
  239. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", int3(-1,-1,-1));
  240. return gs->guardingCreaturePosition(pos);
  241. }
  242. std::vector<const CGObjectInstance*> CGameInfoCallback::getGuardingCreatures (int3 pos) const
  243. {
  244. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", std::vector<const CGObjectInstance*>());
  245. std::vector<const CGObjectInstance*> ret;
  246. for(auto * cr : gs->guardingCreatures(pos))
  247. {
  248. ret.push_back(cr);
  249. }
  250. return ret;
  251. }
  252. bool CGameInfoCallback::isTileGuardedUnchecked(int3 tile) const
  253. {
  254. return !gs->guardingCreatures(tile).empty();
  255. }
  256. bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero & dest, const CGObjectInstance * selectedObject) const
  257. {
  258. const auto * h = dynamic_cast<const CGHeroInstance *>(hero);
  259. ERROR_RET_VAL_IF(!h, "That's not a hero!", false);
  260. InfoAboutHero::EInfoLevel infoLevel = InfoAboutHero::EInfoLevel::BASIC;
  261. if(hasAccess(h->tempOwner))
  262. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  263. if (infoLevel == InfoAboutHero::EInfoLevel::BASIC)
  264. {
  265. auto ourBattle = gs->getBattle(*getPlayerID());
  266. if(ourBattle && ourBattle->playerHasAccessToHeroInfo(*getPlayerID(), h)) //if it's battle we can get enemy hero full data
  267. infoLevel = InfoAboutHero::EInfoLevel::INBATTLE;
  268. else
  269. ERROR_RET_VAL_IF(!isVisible(h->visitablePos()), "That hero is not visible!", false);
  270. }
  271. if( (infoLevel == InfoAboutHero::EInfoLevel::BASIC) && nullptr != selectedObject)
  272. {
  273. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  274. if(nullptr != selectedHero)
  275. if(selectedHero->hasVisions(hero, BonusCustomSubtype::visionsHeroes))
  276. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  277. }
  278. dest.initFromHero(h, infoLevel);
  279. //DISGUISED bonus implementation
  280. if(getPlayerRelations(*getPlayerID(), hero->tempOwner) == PlayerRelations::ENEMIES)
  281. {
  282. //todo: bonus cashing
  283. int disguiseLevel = h->valOfBonuses(BonusType::DISGUISED);
  284. auto doBasicDisguise = [](InfoAboutHero & info)
  285. {
  286. int maxAIValue = 0;
  287. const CCreature * mostStrong = nullptr;
  288. for(auto & elem : info.army)
  289. {
  290. if(static_cast<int>(elem.second.type->getAIValue()) > maxAIValue)
  291. {
  292. maxAIValue = elem.second.type->getAIValue();
  293. mostStrong = elem.second.type;
  294. }
  295. }
  296. if(nullptr == mostStrong)//just in case
  297. logGlobal->error("CGameInfoCallback::getHeroInfo: Unable to select most strong stack");
  298. else
  299. for(auto & elem : info.army)
  300. {
  301. elem.second.type = mostStrong;
  302. }
  303. };
  304. auto doAdvancedDisguise = [&doBasicDisguise](InfoAboutHero & info)
  305. {
  306. doBasicDisguise(info);
  307. for(auto & elem : info.army)
  308. elem.second.count = 0;
  309. };
  310. auto doExpertDisguise = [this,h](InfoAboutHero & info)
  311. {
  312. for(auto & elem : info.army)
  313. elem.second.count = 0;
  314. const auto factionIndex = getStartInfo(false)->playerInfos.at(h->tempOwner).castle;
  315. int maxAIValue = 0;
  316. const CCreature * mostStrong = nullptr;
  317. for(const auto & creature : VLC->creh->objects)
  318. {
  319. if(creature->getFaction() == factionIndex && static_cast<int>(creature->getAIValue()) > maxAIValue)
  320. {
  321. maxAIValue = creature->getAIValue();
  322. mostStrong = creature.get();
  323. }
  324. }
  325. if(nullptr != mostStrong) //possible, faction may have no creatures at all
  326. for(auto & elem : info.army)
  327. elem.second.type = mostStrong;
  328. };
  329. switch (disguiseLevel)
  330. {
  331. case 0:
  332. //no bonus at all - do nothing
  333. break;
  334. case 1:
  335. doBasicDisguise(dest);
  336. break;
  337. case 2:
  338. doAdvancedDisguise(dest);
  339. break;
  340. case 3:
  341. doExpertDisguise(dest);
  342. break;
  343. default:
  344. //invalid value
  345. logGlobal->error("CGameInfoCallback::getHeroInfo: Invalid DISGUISED bonus value %d", disguiseLevel);
  346. break;
  347. }
  348. }
  349. return true;
  350. }
  351. int CGameInfoCallback::getDate(Date mode) const
  352. {
  353. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  354. return gs->getDate(mode);
  355. }
  356. bool CGameInfoCallback::isVisible(int3 pos, const std::optional<PlayerColor> & Player) const
  357. {
  358. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  359. return gs->isVisible(pos, Player);
  360. }
  361. bool CGameInfoCallback::isVisible(int3 pos) const
  362. {
  363. return isVisible(pos, getPlayerID());
  364. }
  365. bool CGameInfoCallback::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & Player) const
  366. {
  367. return gs->isVisible(obj, Player);
  368. }
  369. bool CGameInfoCallback::isVisible(const CGObjectInstance *obj) const
  370. {
  371. return isVisible(obj, getPlayerID());
  372. }
  373. // const CCreatureSet* CInfoCallback::getGarrison(const CGObjectInstance *obj) const
  374. // {
  375. // //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  376. // if()
  377. // const CArmedInstance *armi = dynamic_cast<const CArmedInstance*>(obj);
  378. // if(!armi)
  379. // return nullptr;
  380. // else
  381. // return armi;
  382. // }
  383. std::vector <const CGObjectInstance *> CGameInfoCallback::getBlockingObjs( int3 pos ) const
  384. {
  385. std::vector<const CGObjectInstance *> ret;
  386. const TerrainTile *t = getTile(pos);
  387. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  388. for(const CGObjectInstance * obj : t->blockingObjects)
  389. ret.push_back(obj);
  390. return ret;
  391. }
  392. std::vector <const CGObjectInstance *> CGameInfoCallback::getVisitableObjs(int3 pos, bool verbose) const
  393. {
  394. std::vector<const CGObjectInstance *> ret;
  395. const TerrainTile *t = getTile(pos, verbose);
  396. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!t, verbose, pos.toString() + " is not visible!", ret);
  397. for(const CGObjectInstance * obj : t->visitableObjects)
  398. {
  399. if(getPlayerID() || obj->ID != Obj::EVENT) //hide events from players
  400. ret.push_back(obj);
  401. }
  402. return ret;
  403. }
  404. const CGObjectInstance * CGameInfoCallback::getTopObj (int3 pos) const
  405. {
  406. return vstd::backOrNull(getVisitableObjs(pos));
  407. }
  408. std::vector <const CGObjectInstance *> CGameInfoCallback::getFlaggableObjects(int3 pos) const
  409. {
  410. std::vector<const CGObjectInstance *> ret;
  411. const TerrainTile *t = getTile(pos);
  412. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  413. for(const CGObjectInstance *obj : t->blockingObjects)
  414. if(obj->tempOwner != PlayerColor::UNFLAGGABLE)
  415. ret.push_back(obj);
  416. return ret;
  417. }
  418. int3 CGameInfoCallback::getMapSize() const
  419. {
  420. return int3(gs->map->width, gs->map->height, gs->map->twoLevel ? 2 : 1);
  421. }
  422. std::vector<const CGHeroInstance *> CGameInfoCallback::getAvailableHeroes(const CGObjectInstance * townOrTavern) const
  423. {
  424. ASSERT_IF_CALLED_WITH_PLAYER
  425. std::vector<const CGHeroInstance *> ret;
  426. //ERROR_RET_VAL_IF(!isOwnedOrVisited(townOrTavern), "Town or tavern must be owned or visited!", ret);
  427. //TODO: town needs to be owned, advmap tavern needs to be visited; to be reimplemented when visit tracking is done
  428. const CGTownInstance * town = getTown(townOrTavern->id);
  429. if(townOrTavern->ID == Obj::TAVERN || (town && town->hasBuilt(BuildingID::TAVERN)))
  430. return gs->heroesPool->getHeroesFor(*getPlayerID());
  431. return ret;
  432. }
  433. const TerrainTile * CGameInfoCallback::getTile(int3 tile, bool verbose) const
  434. {
  435. if(isVisible(tile))
  436. return &gs->map->getTile(tile);
  437. if(verbose)
  438. logGlobal->error("\r\n%s: %s\r\n", BOOST_CURRENT_FUNCTION, tile.toString() + " is not visible!");
  439. return nullptr;
  440. }
  441. const TerrainTile * CGameInfoCallback::getTileUnchecked(int3 tile) const
  442. {
  443. if (isInTheMap(tile))
  444. return &gs->map->getTile(tile);
  445. return nullptr;
  446. }
  447. EDiggingStatus CGameInfoCallback::getTileDigStatus(int3 tile, bool verbose) const
  448. {
  449. if(!isVisible(tile))
  450. return EDiggingStatus::UNKNOWN;
  451. for(const auto & object : gs->map->objects)
  452. {
  453. if(object && object->ID == Obj::HOLE && object->pos == tile)
  454. return EDiggingStatus::TILE_OCCUPIED;
  455. }
  456. return getTile(tile)->getDiggingStatus();
  457. }
  458. //TODO: typedef?
  459. std::shared_ptr<const boost::multi_array<TerrainTile*, 3>> CGameInfoCallback::getAllVisibleTiles() const
  460. {
  461. assert(getPlayerID().has_value());
  462. const auto * team = getPlayerTeam(getPlayerID().value());
  463. size_t width = gs->map->width;
  464. size_t height = gs->map->height;
  465. size_t levels = gs->map->levels();
  466. auto * ptr = new boost::multi_array<TerrainTile *, 3>(boost::extents[levels][width][height]);
  467. int3 tile;
  468. for(tile.z = 0; tile.z < levels; tile.z++)
  469. for(tile.x = 0; tile.x < width; tile.x++)
  470. for(tile.y = 0; tile.y < height; tile.y++)
  471. {
  472. if (team->fogOfWarMap[tile.z][tile.x][tile.y])
  473. (*ptr)[tile.z][tile.x][tile.y] = &gs->map->getTile(tile);
  474. else
  475. (*ptr)[tile.z][tile.x][tile.y] = nullptr;
  476. }
  477. return std::shared_ptr<const boost::multi_array<TerrainTile*, 3>>(ptr);
  478. }
  479. EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID )
  480. {
  481. ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", EBuildingState::TOWN_NOT_OWNED);
  482. if(!t->town->buildings.count(ID))
  483. return EBuildingState::BUILDING_ERROR;
  484. const CBuilding * building = t->town->buildings.at(ID);
  485. if(t->hasBuilt(ID)) //already built
  486. return EBuildingState::ALREADY_PRESENT;
  487. //can we build it?
  488. if(vstd::contains(t->forbiddenBuildings, ID))
  489. return EBuildingState::FORBIDDEN; //forbidden
  490. auto possiblyNotBuiltTest = [&](const BuildingID & id) -> bool
  491. {
  492. return ((id == BuildingID::CAPITOL) ? true : !t->hasBuilt(id));
  493. };
  494. std::function<bool(BuildingID id)> allowedTest = [&](const BuildingID & id) -> bool
  495. {
  496. return !vstd::contains(t->forbiddenBuildings, id);
  497. };
  498. if (!t->genBuildingRequirements(ID, true).satisfiable(allowedTest, possiblyNotBuiltTest))
  499. return EBuildingState::FORBIDDEN;
  500. if(ID == BuildingID::CAPITOL)
  501. {
  502. const PlayerState *ps = getPlayerState(t->tempOwner, false);
  503. if(ps)
  504. {
  505. for(const CGTownInstance *town : ps->towns)
  506. {
  507. if(town->hasBuilt(BuildingID::CAPITOL))
  508. {
  509. return EBuildingState::HAVE_CAPITAL; //no more than one capitol
  510. }
  511. }
  512. }
  513. }
  514. else if(ID == BuildingID::SHIPYARD)
  515. {
  516. const TerrainTile *tile = getTile(t->bestLocation(), false);
  517. if(!tile || !tile->terType->isWater())
  518. return EBuildingState::NO_WATER; //lack of water
  519. }
  520. auto buildTest = [&](const BuildingID & id) -> bool
  521. {
  522. return t->hasBuilt(id);
  523. };
  524. if (!t->genBuildingRequirements(ID).test(buildTest))
  525. return EBuildingState::PREREQUIRES;
  526. if(t->built >= VLC->settings()->getInteger(EGameSettings::TOWNS_BUILDINGS_PER_TURN_CAP))
  527. return EBuildingState::CANT_BUILD_TODAY; //building limit
  528. //checking resources
  529. if(!building->resources.canBeAfforded(getPlayerState(t->tempOwner)->resources))
  530. return EBuildingState::NO_RESOURCES; //lack of res
  531. return EBuildingState::ALLOWED;
  532. }
  533. const CMapHeader * CGameInfoCallback::getMapHeader() const
  534. {
  535. return gs->map;
  536. }
  537. bool CGameInfoCallback::hasAccess(std::optional<PlayerColor> playerId) const
  538. {
  539. return !getPlayerID() || getPlayerID()->isSpectator() || gs->getPlayerRelations(*playerId, *getPlayerID()) != PlayerRelations::ENEMIES;
  540. }
  541. EPlayerStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const
  542. {
  543. const PlayerState *ps = gs->getPlayerState(player, verbose);
  544. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!ps, verbose, "No such player!", EPlayerStatus::WRONG);
  545. return ps->status;
  546. }
  547. std::string CGameInfoCallback::getTavernRumor(const CGObjectInstance * townOrTavern) const
  548. {
  549. MetaString text;
  550. text.appendLocalString(EMetaText::GENERAL_TXT, 216);
  551. std::string extraText;
  552. if(gs->rumor.type == RumorState::TYPE_NONE)
  553. return text.toString();
  554. auto rumor = gs->rumor.last[gs->rumor.type];
  555. switch(gs->rumor.type)
  556. {
  557. case RumorState::TYPE_SPECIAL:
  558. text.replaceLocalString(EMetaText::GENERAL_TXT, rumor.first);
  559. if(rumor.first == RumorState::RUMOR_GRAIL)
  560. text.replaceTextID(TextIdentifier("core", "arraytxt", 158 + rumor.second).get());
  561. else
  562. text.replaceTextID(TextIdentifier("core", "plcolors", rumor.second).get());
  563. break;
  564. case RumorState::TYPE_MAP:
  565. text.replaceRawString(gs->map->rumors[rumor.first].text.toString());
  566. break;
  567. case RumorState::TYPE_RAND:
  568. text.replaceTextID(TextIdentifier("core", "randtvrn", rumor.first).get());
  569. break;
  570. }
  571. return text.toString();
  572. }
  573. PlayerRelations CGameInfoCallback::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  574. {
  575. return gs->getPlayerRelations(color1, color2);
  576. }
  577. bool CGameInfoCallback::canGetFullInfo(const CGObjectInstance *obj) const
  578. {
  579. return !obj || hasAccess(obj->tempOwner);
  580. }
  581. int CGameInfoCallback::getHeroCount( PlayerColor player, bool includeGarrisoned ) const
  582. {
  583. int ret = 0;
  584. const PlayerState *p = gs->getPlayerState(player);
  585. ERROR_RET_VAL_IF(!p, "No such player!", -1);
  586. if(includeGarrisoned)
  587. return static_cast<int>(p->heroes.size());
  588. else
  589. for(const auto & elem : p->heroes)
  590. if(!elem->inTownGarrison)
  591. ret++;
  592. return ret;
  593. }
  594. bool CGameInfoCallback::isOwnedOrVisited(const CGObjectInstance *obj) const
  595. {
  596. if(canGetFullInfo(obj))
  597. return true;
  598. const TerrainTile *t = getTile(obj->visitablePos()); //get entrance tile
  599. const CGObjectInstance *visitor = t->visitableObjects.back(); //visitong hero if present or the object itself at last
  600. return visitor->ID == Obj::HERO && canGetFullInfo(visitor); //owned or allied hero is a visitor
  601. }
  602. bool CGameInfoCallback::isPlayerMakingTurn(PlayerColor player) const
  603. {
  604. return gs->actingPlayers.count(player);
  605. }
  606. CGameInfoCallback::CGameInfoCallback():
  607. gs(nullptr)
  608. {
  609. }
  610. CGameInfoCallback::CGameInfoCallback(CGameState * GS):
  611. gs(GS)
  612. {
  613. }
  614. int CPlayerSpecificInfoCallback::howManyTowns() const
  615. {
  616. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  617. ERROR_RET_VAL_IF(!getPlayerID(), "Applicable only for player callbacks", -1);
  618. return CGameInfoCallback::howManyTowns(*getPlayerID());
  619. }
  620. std::vector < const CGTownInstance *> CPlayerSpecificInfoCallback::getTownsInfo(bool onlyOur) const
  621. {
  622. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  623. auto ret = std::vector < const CGTownInstance *>();
  624. for(const auto & i : gs->players)
  625. {
  626. for(const auto & town : i.second.towns)
  627. {
  628. if(i.first == getPlayerID() || (!onlyOur && isVisible(town, getPlayerID())))
  629. {
  630. ret.push_back(town);
  631. }
  632. }
  633. } // for ( std::map<int, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  634. return ret;
  635. }
  636. std::vector < const CGHeroInstance *> CPlayerSpecificInfoCallback::getHeroesInfo(bool onlyOur) const
  637. {
  638. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  639. std::vector < const CGHeroInstance *> ret;
  640. for(auto hero : gs->map->heroesOnMap)
  641. {
  642. // !player || // - why would we even get access to hero not owned by any player?
  643. if((hero->tempOwner == *getPlayerID()) ||
  644. (isVisible(hero->visitablePos(), getPlayerID()) && !onlyOur) )
  645. {
  646. ret.push_back(hero);
  647. }
  648. }
  649. return ret;
  650. }
  651. int CPlayerSpecificInfoCallback::getHeroSerial(const CGHeroInstance * hero, bool includeGarrisoned) const
  652. {
  653. if (hero->inTownGarrison && !includeGarrisoned)
  654. return -1;
  655. size_t index = 0;
  656. auto & heroes = gs->players[*getPlayerID()].heroes;
  657. for (auto & possibleHero : heroes)
  658. {
  659. if (includeGarrisoned || !(possibleHero)->inTownGarrison)
  660. index++;
  661. if (possibleHero == hero)
  662. return static_cast<int>(index);
  663. }
  664. return -1;
  665. }
  666. int3 CPlayerSpecificInfoCallback::getGrailPos( double *outKnownRatio )
  667. {
  668. if (!getPlayerID() || gs->map->obeliskCount == 0)
  669. {
  670. *outKnownRatio = 0.0;
  671. }
  672. else
  673. {
  674. TeamID t = gs->getPlayerTeam(*getPlayerID())->id;
  675. double visited = 0.0;
  676. if(gs->map->obelisksVisited.count(t))
  677. visited = static_cast<double>(gs->map->obelisksVisited[t]);
  678. *outKnownRatio = visited / gs->map->obeliskCount;
  679. }
  680. return gs->map->grailPos;
  681. }
  682. std::vector < const CGObjectInstance * > CPlayerSpecificInfoCallback::getMyObjects() const
  683. {
  684. std::vector < const CGObjectInstance * > ret;
  685. for(const CGObjectInstance * obj : gs->map->objects)
  686. {
  687. if(obj && obj->tempOwner == getPlayerID())
  688. ret.push_back(obj);
  689. }
  690. return ret;
  691. }
  692. std::vector < const CGDwelling * > CPlayerSpecificInfoCallback::getMyDwellings() const
  693. {
  694. ASSERT_IF_CALLED_WITH_PLAYER
  695. std::vector < const CGDwelling * > ret;
  696. for(CGDwelling * dw : gs->getPlayerState(*getPlayerID())->dwellings)
  697. {
  698. ret.push_back(dw);
  699. }
  700. return ret;
  701. }
  702. std::vector <QuestInfo> CPlayerSpecificInfoCallback::getMyQuests() const
  703. {
  704. std::vector <QuestInfo> ret;
  705. for(const auto & quest : gs->getPlayerState(*getPlayerID())->quests)
  706. {
  707. ret.push_back (quest);
  708. }
  709. return ret;
  710. }
  711. int CPlayerSpecificInfoCallback::howManyHeroes(bool includeGarrisoned) const
  712. {
  713. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  714. ERROR_RET_VAL_IF(!getPlayerID(), "Applicable only for player callbacks", -1);
  715. return getHeroCount(*getPlayerID(), includeGarrisoned);
  716. }
  717. const CGHeroInstance* CPlayerSpecificInfoCallback::getHeroBySerial(int serialId, bool includeGarrisoned) const
  718. {
  719. ASSERT_IF_CALLED_WITH_PLAYER
  720. const PlayerState *p = getPlayerState(*getPlayerID());
  721. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  722. if (!includeGarrisoned)
  723. {
  724. for(ui32 i = 0; i < p->heroes.size() && static_cast<int>(i) <= serialId; i++)
  725. if(p->heroes[i]->inTownGarrison)
  726. serialId++;
  727. }
  728. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->heroes.size(), "No player info", nullptr);
  729. return p->heroes[serialId];
  730. }
  731. const CGTownInstance* CPlayerSpecificInfoCallback::getTownBySerial(int serialId) const
  732. {
  733. ASSERT_IF_CALLED_WITH_PLAYER
  734. const PlayerState *p = getPlayerState(*getPlayerID());
  735. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  736. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->towns.size(), "No player info", nullptr);
  737. return p->towns[serialId];
  738. }
  739. int CPlayerSpecificInfoCallback::getResourceAmount(GameResID type) const
  740. {
  741. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  742. ERROR_RET_VAL_IF(!getPlayerID(), "Applicable only for player callbacks", -1);
  743. return getResource(*getPlayerID(), type);
  744. }
  745. TResources CPlayerSpecificInfoCallback::getResourceAmount() const
  746. {
  747. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  748. ERROR_RET_VAL_IF(!getPlayerID(), "Applicable only for player callbacks", TResources());
  749. return gs->players[*getPlayerID()].resources;
  750. }
  751. const TeamState * CGameInfoCallback::getTeam( TeamID teamID ) const
  752. {
  753. //rewritten by hand, AI calls this function a lot
  754. auto team = gs->teams.find(teamID);
  755. if (team != gs->teams.end())
  756. {
  757. const TeamState *ret = &team->second;
  758. if(!getPlayerID().has_value()) //neutral (or invalid) player
  759. return ret;
  760. else
  761. {
  762. if (vstd::contains(ret->players, *getPlayerID())) //specific player
  763. return ret;
  764. else
  765. {
  766. logGlobal->error("Illegal attempt to access team data!");
  767. return nullptr;
  768. }
  769. }
  770. }
  771. else
  772. {
  773. logGlobal->error("Cannot find info for team %d", teamID);
  774. return nullptr;
  775. }
  776. }
  777. const TeamState * CGameInfoCallback::getPlayerTeam( PlayerColor color ) const
  778. {
  779. auto player = gs->players.find(color);
  780. if (player != gs->players.end())
  781. {
  782. return getTeam (player->second.team);
  783. }
  784. else
  785. {
  786. return nullptr;
  787. }
  788. }
  789. const CGHeroInstance * CGameInfoCallback::getHeroWithSubid( int subid ) const
  790. {
  791. if(subid<0)
  792. return nullptr;
  793. if(subid>= gs->map->allHeroes.size())
  794. return nullptr;
  795. return gs->map->allHeroes.at(subid).get();
  796. }
  797. bool CGameInfoCallback::isInTheMap(const int3 &pos) const
  798. {
  799. return gs->map->isInTheMap(pos);
  800. }
  801. void CGameInfoCallback::getVisibleTilesInRange(std::unordered_set<int3> &tiles, int3 pos, int radious, int3::EDistanceFormula distanceFormula) const
  802. {
  803. gs->getTilesInRange(tiles, pos, radious, ETileVisibility::REVEALED, *getPlayerID(), distanceFormula);
  804. }
  805. void CGameInfoCallback::calculatePaths(const std::shared_ptr<PathfinderConfig> & config)
  806. {
  807. gs->calculatePaths(config);
  808. }
  809. void CGameInfoCallback::calculatePaths( const CGHeroInstance *hero, CPathsInfo &out)
  810. {
  811. gs->calculatePaths(hero, out);
  812. }
  813. const CArtifactInstance * CGameInfoCallback::getArtInstance( ArtifactInstanceID aid ) const
  814. {
  815. return gs->map->artInstances[aid.num];
  816. }
  817. const CGObjectInstance * CGameInfoCallback::getObjInstance( ObjectInstanceID oid ) const
  818. {
  819. return gs->map->objects[oid.num];
  820. }
  821. const CArtifactSet * CGameInfoCallback::getArtSet(const ArtifactLocation & loc) const
  822. {
  823. return gs->getArtSet(loc);
  824. }
  825. std::vector<ObjectInstanceID> CGameInfoCallback::getVisibleTeleportObjects(std::vector<ObjectInstanceID> ids, PlayerColor player) const
  826. {
  827. vstd::erase_if(ids, [&](const ObjectInstanceID & id) -> bool
  828. {
  829. const auto * obj = getObj(id, false);
  830. return player != PlayerColor::UNFLAGGABLE && (!obj || !isVisible(obj->pos, player));
  831. });
  832. return ids;
  833. }
  834. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelEntrances(TeleportChannelID id, PlayerColor player) const
  835. {
  836. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->entrances, player);
  837. }
  838. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelExits(TeleportChannelID id, PlayerColor player) const
  839. {
  840. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->exits, player);
  841. }
  842. ETeleportChannelType CGameInfoCallback::getTeleportChannelType(TeleportChannelID id, PlayerColor player) const
  843. {
  844. std::vector<ObjectInstanceID> entrances = getTeleportChannelEntrances(id, player);
  845. std::vector<ObjectInstanceID> exits = getTeleportChannelExits(id, player);
  846. if((entrances.empty() || exits.empty()) // impassable if exits or entrances list are empty
  847. || (entrances.size() == 1 && entrances == exits)) // impassable if only entrance and only exit is same object. e.g bidirectional monolith
  848. {
  849. return ETeleportChannelType::IMPASSABLE;
  850. }
  851. auto intersection = vstd::intersection(entrances, exits);
  852. if(intersection.size() == entrances.size() && intersection.size() == exits.size())
  853. return ETeleportChannelType::BIDIRECTIONAL;
  854. else if(intersection.empty())
  855. return ETeleportChannelType::UNIDIRECTIONAL;
  856. else
  857. return ETeleportChannelType::MIXED;
  858. }
  859. bool CGameInfoCallback::isTeleportChannelImpassable(TeleportChannelID id, PlayerColor player) const
  860. {
  861. return ETeleportChannelType::IMPASSABLE == getTeleportChannelType(id, player);
  862. }
  863. bool CGameInfoCallback::isTeleportChannelBidirectional(TeleportChannelID id, PlayerColor player) const
  864. {
  865. return ETeleportChannelType::BIDIRECTIONAL == getTeleportChannelType(id, player);
  866. }
  867. bool CGameInfoCallback::isTeleportChannelUnidirectional(TeleportChannelID id, PlayerColor player) const
  868. {
  869. return ETeleportChannelType::UNIDIRECTIONAL == getTeleportChannelType(id, player);
  870. }
  871. bool CGameInfoCallback::isTeleportEntrancePassable(const CGTeleport * obj, PlayerColor player) const
  872. {
  873. return obj && obj->isEntrance() && !isTeleportChannelImpassable(obj->channel, player);
  874. }
  875. VCMI_LIB_NAMESPACE_END