CGameInfoCallback.cpp 29 KB

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