CGameInfoCallback.cpp 30 KB

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