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(SpellID id) const
  50. {
  51. return gs->map->allowedSpells.count(id) != 0;
  52. }
  53. bool CGameInfoCallback::isAllowed(ArtifactID id) const
  54. {
  55. return gs->map->allowedArtifact.count(id) != 0;
  56. }
  57. bool CGameInfoCallback::isAllowed(SecondarySkill id) const
  58. {
  59. return gs->map->allowedAbilities.count(id) != 0;
  60. }
  61. std::optional<PlayerColor> CGameInfoCallback::getPlayerID() const
  62. {
  63. return std::nullopt;
  64. }
  65. const Player * CGameInfoCallback::getPlayer(PlayerColor color) const
  66. {
  67. return getPlayerState(color, false);
  68. }
  69. const PlayerState * CGameInfoCallback::getPlayerState(PlayerColor color, bool verbose) const
  70. {
  71. //funtion written from scratch since it's accessed A LOT by AI
  72. if(!color.isValidPlayer())
  73. {
  74. return nullptr;
  75. }
  76. auto player = gs->players.find(color);
  77. if (player != gs->players.end())
  78. {
  79. if (hasAccess(color))
  80. return &player->second;
  81. else
  82. {
  83. if (verbose)
  84. logGlobal->error("Cannot access player %d info!", color);
  85. return nullptr;
  86. }
  87. }
  88. else
  89. {
  90. if (verbose)
  91. logGlobal->error("Cannot find player %d info!", color);
  92. return nullptr;
  93. }
  94. }
  95. TurnTimerInfo CGameInfoCallback::getPlayerTurnTime(PlayerColor color) const
  96. {
  97. if(!color.isValidPlayer())
  98. {
  99. return TurnTimerInfo{};
  100. }
  101. auto player = gs->players.find(color);
  102. if(player != gs->players.end())
  103. {
  104. return player->second.turnTimer;
  105. }
  106. return TurnTimerInfo{};
  107. }
  108. const CGObjectInstance * CGameInfoCallback::getObjByQuestIdentifier(ObjectInstanceID identifier) const
  109. {
  110. if(gs->map->questIdentifierToId.empty())
  111. {
  112. //assume that it is VCMI map and quest identifier equals instance identifier
  113. return getObj(identifier, true);
  114. }
  115. else
  116. {
  117. ERROR_RET_VAL_IF(!vstd::contains(gs->map->questIdentifierToId, identifier.getNum()), "There is no object with such quest identifier!", nullptr);
  118. return getObj(gs->map->questIdentifierToId[identifier.getNum()]);
  119. }
  120. }
  121. /************************************************************************/
  122. /* */
  123. /************************************************************************/
  124. const CGObjectInstance* CGameInfoCallback::getObj(ObjectInstanceID objid, bool verbose) const
  125. {
  126. si32 oid = objid.num;
  127. if(oid < 0 || oid >= gs->map->objects.size())
  128. {
  129. if(verbose)
  130. logGlobal->error("Cannot get object with id %d", oid);
  131. return nullptr;
  132. }
  133. const CGObjectInstance *ret = gs->map->objects[oid];
  134. if(!ret)
  135. {
  136. if(verbose)
  137. logGlobal->error("Cannot get object with id %d. Object was removed", oid);
  138. return nullptr;
  139. }
  140. if(!isVisible(ret, getPlayerID()) && ret->tempOwner != getPlayerID())
  141. {
  142. if(verbose)
  143. logGlobal->error("Cannot get object with id %d. Object is not visible.", oid);
  144. return nullptr;
  145. }
  146. return ret;
  147. }
  148. const CGHeroInstance* CGameInfoCallback::getHero(ObjectInstanceID objid) const
  149. {
  150. const CGObjectInstance *obj = getObj(objid, false);
  151. if(obj)
  152. return dynamic_cast<const CGHeroInstance*>(obj);
  153. else
  154. return nullptr;
  155. }
  156. const CGTownInstance* CGameInfoCallback::getTown(ObjectInstanceID objid) const
  157. {
  158. const CGObjectInstance *obj = getObj(objid, false);
  159. if(obj)
  160. return dynamic_cast<const CGTownInstance*>(obj);
  161. else
  162. return nullptr;
  163. }
  164. void CGameInfoCallback::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  165. {
  166. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  167. ERROR_RET_IF(!canGetFullInfo(obj), "Cannot get info about not owned object!");
  168. ERROR_RET_IF(!obj->hasStackAtSlot(stackPos), "There is no such stack!");
  169. gs->fillUpgradeInfo(obj, stackPos, out);
  170. //return gs->fillUpgradeInfo(obj->getStack(stackPos));
  171. }
  172. const StartInfo * CGameInfoCallback::getStartInfo(bool beforeRandomization) const
  173. {
  174. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  175. if(beforeRandomization)
  176. return gs->initialOpts;
  177. else
  178. return gs->scenarioOps;
  179. }
  180. int32_t CGameInfoCallback::getSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  181. {
  182. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  183. ERROR_RET_VAL_IF(!canGetFullInfo(caster), "Cannot get info about caster!", -1);
  184. //if there is a battle
  185. auto casterBattle = gs->getBattle(caster->getOwner());
  186. if(casterBattle)
  187. return casterBattle->battleGetSpellCost(sp, caster);
  188. //if there is no battle
  189. return caster->getSpellCost(sp);
  190. }
  191. int64_t CGameInfoCallback::estimateSpellDamage(const CSpell * sp, const CGHeroInstance * hero) const
  192. {
  193. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  194. ERROR_RET_VAL_IF(hero && !canGetFullInfo(hero), "Cannot get info about caster!", -1);
  195. if(hero) //we see hero's spellbook
  196. return sp->calculateDamage(hero);
  197. else
  198. return 0; //mage guild
  199. }
  200. void CGameInfoCallback::getThievesGuildInfo(SThievesGuildInfo & thi, const CGObjectInstance * obj)
  201. {
  202. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  203. ERROR_RET_IF(!obj, "No guild object!");
  204. ERROR_RET_IF(obj->ID == Obj::TOWN && !canGetFullInfo(obj), "Cannot get info about town guild object!");
  205. //TODO: advmap object -> check if they're visited by our hero
  206. if(obj->ID == Obj::TOWN || obj->ID == Obj::TAVERN)
  207. {
  208. int taverns = 0;
  209. for(auto town : gs->players[*getPlayerID()].towns)
  210. {
  211. if(town->hasBuilt(BuildingID::TAVERN))
  212. taverns++;
  213. }
  214. gs->obtainPlayersStats(thi, taverns);
  215. }
  216. else if(obj->ID == Obj::DEN_OF_THIEVES)
  217. {
  218. gs->obtainPlayersStats(thi, 20);
  219. }
  220. }
  221. int CGameInfoCallback::howManyTowns(PlayerColor Player) const
  222. {
  223. ERROR_RET_VAL_IF(!hasAccess(Player), "Access forbidden!", -1);
  224. return static_cast<int>(gs->players[Player].towns.size());
  225. }
  226. bool CGameInfoCallback::getTownInfo(const CGObjectInstance * town, InfoAboutTown & dest, const CGObjectInstance * selectedObject) const
  227. {
  228. ERROR_RET_VAL_IF(!isVisible(town, getPlayerID()), "Town is not visible!", false); //it's not a town or it's not visible for layer
  229. bool detailed = hasAccess(town->tempOwner);
  230. if(town->ID == Obj::TOWN)
  231. {
  232. if(!detailed && nullptr != selectedObject)
  233. {
  234. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  235. if(nullptr != selectedHero)
  236. detailed = selectedHero->hasVisions(town, BonusCustomSubtype::visionsTowns);
  237. }
  238. dest.initFromTown(dynamic_cast<const CGTownInstance *>(town), detailed);
  239. }
  240. else if(town->ID == Obj::GARRISON || town->ID == Obj::GARRISON2)
  241. dest.initFromArmy(dynamic_cast<const CArmedInstance *>(town), detailed);
  242. else
  243. return false;
  244. return true;
  245. }
  246. int3 CGameInfoCallback::guardingCreaturePosition (int3 pos) const //FIXME: redundant?
  247. {
  248. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", int3(-1,-1,-1));
  249. return gs->guardingCreaturePosition(pos);
  250. }
  251. std::vector<const CGObjectInstance*> CGameInfoCallback::getGuardingCreatures (int3 pos) const
  252. {
  253. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", std::vector<const CGObjectInstance*>());
  254. std::vector<const CGObjectInstance*> ret;
  255. for(auto * cr : gs->guardingCreatures(pos))
  256. {
  257. ret.push_back(cr);
  258. }
  259. return ret;
  260. }
  261. bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero & dest, const CGObjectInstance * selectedObject) const
  262. {
  263. const auto * h = dynamic_cast<const CGHeroInstance *>(hero);
  264. ERROR_RET_VAL_IF(!h, "That's not a hero!", false);
  265. InfoAboutHero::EInfoLevel infoLevel = InfoAboutHero::EInfoLevel::BASIC;
  266. if(hasAccess(h->tempOwner))
  267. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  268. if (infoLevel == InfoAboutHero::EInfoLevel::BASIC)
  269. {
  270. auto ourBattle = gs->getBattle(*getPlayerID());
  271. if(ourBattle && ourBattle->playerHasAccessToHeroInfo(*getPlayerID(), h)) //if it's battle we can get enemy hero full data
  272. infoLevel = InfoAboutHero::EInfoLevel::INBATTLE;
  273. else
  274. ERROR_RET_VAL_IF(!isVisible(h->visitablePos()), "That hero is not visible!", false);
  275. }
  276. if( (infoLevel == InfoAboutHero::EInfoLevel::BASIC) && nullptr != selectedObject)
  277. {
  278. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  279. if(nullptr != selectedHero)
  280. if(selectedHero->hasVisions(hero, BonusCustomSubtype::visionsHeroes))
  281. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  282. }
  283. dest.initFromHero(h, infoLevel);
  284. //DISGUISED bonus implementation
  285. if(getPlayerRelations(*getPlayerID(), hero->tempOwner) == PlayerRelations::ENEMIES)
  286. {
  287. //todo: bonus cashing
  288. int disguiseLevel = h->valOfBonuses(BonusType::DISGUISED);
  289. auto doBasicDisguise = [](InfoAboutHero & info)
  290. {
  291. int maxAIValue = 0;
  292. const CCreature * mostStrong = nullptr;
  293. for(auto & elem : info.army)
  294. {
  295. if(static_cast<int>(elem.second.type->getAIValue()) > maxAIValue)
  296. {
  297. maxAIValue = elem.second.type->getAIValue();
  298. mostStrong = elem.second.type;
  299. }
  300. }
  301. if(nullptr == mostStrong)//just in case
  302. logGlobal->error("CGameInfoCallback::getHeroInfo: Unable to select most strong stack");
  303. else
  304. for(auto & elem : info.army)
  305. {
  306. elem.second.type = mostStrong;
  307. }
  308. };
  309. auto doAdvancedDisguise = [&doBasicDisguise](InfoAboutHero & info)
  310. {
  311. doBasicDisguise(info);
  312. for(auto & elem : info.army)
  313. elem.second.count = 0;
  314. };
  315. auto doExpertDisguise = [this,h](InfoAboutHero & info)
  316. {
  317. for(auto & elem : info.army)
  318. elem.second.count = 0;
  319. const auto factionIndex = getStartInfo(false)->playerInfos.at(h->tempOwner).castle;
  320. int maxAIValue = 0;
  321. const CCreature * mostStrong = nullptr;
  322. for(auto creature : VLC->creh->objects)
  323. {
  324. if(creature->getFaction() == factionIndex && static_cast<int>(creature->getAIValue()) > maxAIValue)
  325. {
  326. maxAIValue = creature->getAIValue();
  327. mostStrong = creature;
  328. }
  329. }
  330. if(nullptr != mostStrong) //possible, faction may have no creatures at all
  331. for(auto & elem : info.army)
  332. elem.second.type = mostStrong;
  333. };
  334. switch (disguiseLevel)
  335. {
  336. case 0:
  337. //no bonus at all - do nothing
  338. break;
  339. case 1:
  340. doBasicDisguise(dest);
  341. break;
  342. case 2:
  343. doAdvancedDisguise(dest);
  344. break;
  345. case 3:
  346. doExpertDisguise(dest);
  347. break;
  348. default:
  349. //invalid value
  350. logGlobal->error("CGameInfoCallback::getHeroInfo: Invalid DISGUISED bonus value %d", disguiseLevel);
  351. break;
  352. }
  353. }
  354. return true;
  355. }
  356. int CGameInfoCallback::getDate(Date mode) const
  357. {
  358. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  359. return gs->getDate(mode);
  360. }
  361. bool CGameInfoCallback::isVisible(int3 pos, const std::optional<PlayerColor> & Player) const
  362. {
  363. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  364. return gs->isVisible(pos, Player);
  365. }
  366. bool CGameInfoCallback::isVisible(int3 pos) const
  367. {
  368. return isVisible(pos, getPlayerID());
  369. }
  370. bool CGameInfoCallback::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & Player) const
  371. {
  372. return gs->isVisible(obj, Player);
  373. }
  374. bool CGameInfoCallback::isVisible(const CGObjectInstance *obj) const
  375. {
  376. return isVisible(obj, getPlayerID());
  377. }
  378. // const CCreatureSet* CInfoCallback::getGarrison(const CGObjectInstance *obj) const
  379. // {
  380. // //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  381. // if()
  382. // const CArmedInstance *armi = dynamic_cast<const CArmedInstance*>(obj);
  383. // if(!armi)
  384. // return nullptr;
  385. // else
  386. // return armi;
  387. // }
  388. std::vector < const CGObjectInstance * > CGameInfoCallback::getBlockingObjs( int3 pos ) const
  389. {
  390. std::vector<const CGObjectInstance *> ret;
  391. const TerrainTile *t = getTile(pos);
  392. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  393. for(const CGObjectInstance * obj : t->blockingObjects)
  394. ret.push_back(obj);
  395. return ret;
  396. }
  397. std::vector <const CGObjectInstance * > CGameInfoCallback::getVisitableObjs(int3 pos, bool verbose) const
  398. {
  399. std::vector<const CGObjectInstance *> ret;
  400. const TerrainTile *t = getTile(pos, verbose);
  401. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!t, verbose, pos.toString() + " is not visible!", ret);
  402. for(const CGObjectInstance * obj : t->visitableObjects)
  403. {
  404. if(getPlayerID() || obj->ID != Obj::EVENT) //hide events from players
  405. ret.push_back(obj);
  406. }
  407. return ret;
  408. }
  409. const CGObjectInstance * CGameInfoCallback::getTopObj (int3 pos) const
  410. {
  411. return vstd::backOrNull(getVisitableObjs(pos));
  412. }
  413. std::vector < const CGObjectInstance * > CGameInfoCallback::getFlaggableObjects(int3 pos) const
  414. {
  415. std::vector<const CGObjectInstance *> ret;
  416. const TerrainTile *t = getTile(pos);
  417. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  418. for(const CGObjectInstance *obj : t->blockingObjects)
  419. if(obj->tempOwner != PlayerColor::UNFLAGGABLE)
  420. ret.push_back(obj);
  421. return ret;
  422. }
  423. int3 CGameInfoCallback::getMapSize() const
  424. {
  425. return int3(gs->map->width, gs->map->height, gs->map->twoLevel ? 2 : 1);
  426. }
  427. std::vector<const CGHeroInstance *> CGameInfoCallback::getAvailableHeroes(const CGObjectInstance * townOrTavern) const
  428. {
  429. ASSERT_IF_CALLED_WITH_PLAYER
  430. std::vector<const CGHeroInstance *> ret;
  431. //ERROR_RET_VAL_IF(!isOwnedOrVisited(townOrTavern), "Town or tavern must be owned or visited!", ret);
  432. //TODO: town needs to be owned, advmap tavern needs to be visited; to be reimplemented when visit tracking is done
  433. const CGTownInstance * town = getTown(townOrTavern->id);
  434. if(townOrTavern->ID == Obj::TAVERN || (town && town->hasBuilt(BuildingID::TAVERN)))
  435. return gs->heroesPool->getHeroesFor(*getPlayerID());
  436. return ret;
  437. }
  438. const TerrainTile * CGameInfoCallback::getTile( int3 tile, bool verbose) const
  439. {
  440. if(isVisible(tile))
  441. return &gs->map->getTile(tile);
  442. if(verbose)
  443. logGlobal->error("\r\n%s: %s\r\n", BOOST_CURRENT_FUNCTION, tile.toString() + " is not visible!");
  444. return nullptr;
  445. }
  446. EDiggingStatus CGameInfoCallback::getTileDigStatus(int3 tile, bool verbose) const
  447. {
  448. if(!isVisible(tile))
  449. return EDiggingStatus::UNKNOWN;
  450. for(const auto & object : gs->map->objects)
  451. {
  452. if(object && object->ID == Obj::HOLE && object->pos == tile)
  453. return EDiggingStatus::TILE_OCCUPIED;
  454. }
  455. return getTile(tile)->getDiggingStatus();
  456. }
  457. //TODO: typedef?
  458. std::shared_ptr<const boost::multi_array<TerrainTile*, 3>> CGameInfoCallback::getAllVisibleTiles() const
  459. {
  460. assert(getPlayerID().has_value());
  461. const auto * team = getPlayerTeam(getPlayerID().value());
  462. size_t width = gs->map->width;
  463. size_t height = gs->map->height;
  464. size_t levels = gs->map->levels();
  465. auto * ptr = new boost::multi_array<TerrainTile *, 3>(boost::extents[levels][width][height]);
  466. int3 tile;
  467. for(tile.z = 0; tile.z < levels; tile.z++)
  468. for(tile.x = 0; tile.x < width; tile.x++)
  469. for(tile.y = 0; tile.y < height; tile.y++)
  470. {
  471. if ((*team->fogOfWarMap)[tile.z][tile.x][tile.y])
  472. (*ptr)[tile.z][tile.x][tile.y] = &gs->map->getTile(tile);
  473. else
  474. (*ptr)[tile.z][tile.x][tile.y] = nullptr;
  475. }
  476. return std::shared_ptr<const boost::multi_array<TerrainTile*, 3>>(ptr);
  477. }
  478. EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID )
  479. {
  480. ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", EBuildingState::TOWN_NOT_OWNED);
  481. if(!t->town->buildings.count(ID))
  482. return EBuildingState::BUILDING_ERROR;
  483. const CBuilding * building = t->town->buildings.at(ID);
  484. if(t->hasBuilt(ID)) //already built
  485. return EBuildingState::ALREADY_PRESENT;
  486. //can we build it?
  487. if(vstd::contains(t->forbiddenBuildings, ID))
  488. return EBuildingState::FORBIDDEN; //forbidden
  489. auto possiblyNotBuiltTest = [&](const BuildingID & id) -> bool
  490. {
  491. return ((id == BuildingID::CAPITOL) ? true : !t->hasBuilt(id));
  492. };
  493. std::function<bool(BuildingID id)> allowedTest = [&](const BuildingID & id) -> bool
  494. {
  495. return !vstd::contains(t->forbiddenBuildings, id);
  496. };
  497. if (!t->genBuildingRequirements(ID, true).satisfiable(allowedTest, possiblyNotBuiltTest))
  498. return EBuildingState::FORBIDDEN;
  499. if(ID == BuildingID::CAPITOL)
  500. {
  501. const PlayerState *ps = getPlayerState(t->tempOwner, false);
  502. if(ps)
  503. {
  504. for(const CGTownInstance *town : ps->towns)
  505. {
  506. if(town->hasBuilt(BuildingID::CAPITOL))
  507. {
  508. return EBuildingState::HAVE_CAPITAL; //no more than one capitol
  509. }
  510. }
  511. }
  512. }
  513. else if(ID == BuildingID::SHIPYARD)
  514. {
  515. const TerrainTile *tile = getTile(t->bestLocation(), false);
  516. if(!tile || !tile->terType->isWater())
  517. return EBuildingState::NO_WATER; //lack of water
  518. }
  519. auto buildTest = [&](const BuildingID & id) -> bool
  520. {
  521. return t->hasBuilt(id);
  522. };
  523. if (!t->genBuildingRequirements(ID).test(buildTest))
  524. return EBuildingState::PREREQUIRES;
  525. if(t->builded >= VLC->settings()->getInteger(EGameSettings::TOWNS_BUILDINGS_PER_TURN_CAP))
  526. return EBuildingState::CANT_BUILD_TODAY; //building limit
  527. //checking resources
  528. if(!building->resources.canBeAfforded(getPlayerState(t->tempOwner)->resources))
  529. return EBuildingState::NO_RESOURCES; //lack of res
  530. return EBuildingState::ALLOWED;
  531. }
  532. const CMapHeader * CGameInfoCallback::getMapHeader() const
  533. {
  534. return gs->map;
  535. }
  536. bool CGameInfoCallback::hasAccess(std::optional<PlayerColor> playerId) const
  537. {
  538. return !getPlayerID() || getPlayerID()->isSpectator() || gs->getPlayerRelations(*playerId, *getPlayerID()) != PlayerRelations::ENEMIES;
  539. }
  540. EPlayerStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const
  541. {
  542. const PlayerState *ps = gs->getPlayerState(player, verbose);
  543. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!ps, verbose, "No such player!", EPlayerStatus::WRONG);
  544. return ps->status;
  545. }
  546. std::string CGameInfoCallback::getTavernRumor(const CGObjectInstance * townOrTavern) const
  547. {
  548. MetaString text;
  549. text.appendLocalString(EMetaText::GENERAL_TXT, 216);
  550. std::string extraText;
  551. if(gs->rumor.type == RumorState::TYPE_NONE)
  552. return text.toString();
  553. auto rumor = gs->rumor.last[gs->rumor.type];
  554. switch(gs->rumor.type)
  555. {
  556. case RumorState::TYPE_SPECIAL:
  557. text.replaceLocalString(EMetaText::GENERAL_TXT, rumor.first);
  558. if(rumor.first == RumorState::RUMOR_GRAIL)
  559. text.replaceTextID(TextIdentifier("core", "arraytxt", 158 + rumor.second).get());
  560. else
  561. text.replaceTextID(TextIdentifier("core", "plcolors", rumor.second).get());
  562. break;
  563. case RumorState::TYPE_MAP:
  564. text.replaceRawString(gs->map->rumors[rumor.first].text.toString());
  565. break;
  566. case RumorState::TYPE_RAND:
  567. text.replaceTextID(TextIdentifier("core", "randtvrn", rumor.first).get());
  568. break;
  569. }
  570. return text.toString();
  571. }
  572. PlayerRelations CGameInfoCallback::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  573. {
  574. return gs->getPlayerRelations(color1, color2);
  575. }
  576. bool CGameInfoCallback::canGetFullInfo(const CGObjectInstance *obj) const
  577. {
  578. return !obj || hasAccess(obj->tempOwner);
  579. }
  580. int CGameInfoCallback::getHeroCount( PlayerColor player, bool includeGarrisoned ) const
  581. {
  582. int ret = 0;
  583. const PlayerState *p = gs->getPlayerState(player);
  584. ERROR_RET_VAL_IF(!p, "No such player!", -1);
  585. if(includeGarrisoned)
  586. return static_cast<int>(p->heroes.size());
  587. else
  588. for(const auto & elem : p->heroes)
  589. if(!elem->inTownGarrison)
  590. ret++;
  591. return ret;
  592. }
  593. bool CGameInfoCallback::isOwnedOrVisited(const CGObjectInstance *obj) const
  594. {
  595. if(canGetFullInfo(obj))
  596. return true;
  597. const TerrainTile *t = getTile(obj->visitablePos()); //get entrance tile
  598. const CGObjectInstance *visitor = t->visitableObjects.back(); //visitong hero if present or the obejct itself at last
  599. return visitor->ID == Obj::HERO && canGetFullInfo(visitor); //owned or allied hero is a visitor
  600. }
  601. bool CGameInfoCallback::isPlayerMakingTurn(PlayerColor player) const
  602. {
  603. return gs->actingPlayers.count(player);
  604. }
  605. CGameInfoCallback::CGameInfoCallback(CGameState * GS):
  606. gs(GS)
  607. {
  608. }
  609. std::shared_ptr<const boost::multi_array<ui8, 3>> CPlayerSpecificInfoCallback::getVisibilityMap() const
  610. {
  611. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  612. return gs->getPlayerTeam(*getPlayerID())->fogOfWarMap;
  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. std::vector < const CGTownInstance *> 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 & heroe : heroes)
  658. {
  659. if (includeGarrisoned || !(heroe)->inTownGarrison)
  660. index++;
  661. if (heroe == hero)
  662. return static_cast<int>(index);
  663. }
  664. return -1;
  665. }
  666. int3 CPlayerSpecificInfoCallback::getGrailPos( double *outKnownRatio )
  667. {
  668. if (!getPlayerID() || CGObelisk::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(CGObelisk::visited.count(t))
  677. visited = static_cast<double>(CGObelisk::visited[t]);
  678. *outKnownRatio = visited / CGObelisk::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. CArtifactSet * CGameInfoCallback::getArtSet(const ArtifactLocation & loc) const
  822. {
  823. auto hero = const_cast<CGHeroInstance*>(getHero(loc.artHolder));
  824. if(loc.creature.has_value())
  825. {
  826. if(loc.creature.value() == SlotID::COMMANDER_SLOT_PLACEHOLDER)
  827. return hero->commander;
  828. else
  829. return hero->getStackPtr(loc.creature.value());
  830. }
  831. else
  832. {
  833. return hero;
  834. }
  835. }
  836. std::vector<ObjectInstanceID> CGameInfoCallback::getVisibleTeleportObjects(std::vector<ObjectInstanceID> ids, PlayerColor player) const
  837. {
  838. vstd::erase_if(ids, [&](const ObjectInstanceID & id) -> bool
  839. {
  840. const auto * obj = getObj(id, false);
  841. return player != PlayerColor::UNFLAGGABLE && (!obj || !isVisible(obj->pos, player));
  842. });
  843. return ids;
  844. }
  845. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelEntraces(TeleportChannelID id, PlayerColor player) const
  846. {
  847. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->entrances, player);
  848. }
  849. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelExits(TeleportChannelID id, PlayerColor player) const
  850. {
  851. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->exits, player);
  852. }
  853. ETeleportChannelType CGameInfoCallback::getTeleportChannelType(TeleportChannelID id, PlayerColor player) const
  854. {
  855. std::vector<ObjectInstanceID> entrances = getTeleportChannelEntraces(id, player);
  856. std::vector<ObjectInstanceID> exits = getTeleportChannelExits(id, player);
  857. if((entrances.empty() || exits.empty()) // impassable if exits or entrances list are empty
  858. || (entrances.size() == 1 && entrances == exits)) // impassable if only entrance and only exit is same object. e.g bidirectional monolith
  859. {
  860. return ETeleportChannelType::IMPASSABLE;
  861. }
  862. auto intersection = vstd::intersection(entrances, exits);
  863. if(intersection.size() == entrances.size() && intersection.size() == exits.size())
  864. return ETeleportChannelType::BIDIRECTIONAL;
  865. else if(intersection.empty())
  866. return ETeleportChannelType::UNIDIRECTIONAL;
  867. else
  868. return ETeleportChannelType::MIXED;
  869. }
  870. bool CGameInfoCallback::isTeleportChannelImpassable(TeleportChannelID id, PlayerColor player) const
  871. {
  872. return ETeleportChannelType::IMPASSABLE == getTeleportChannelType(id, player);
  873. }
  874. bool CGameInfoCallback::isTeleportChannelBidirectional(TeleportChannelID id, PlayerColor player) const
  875. {
  876. return ETeleportChannelType::BIDIRECTIONAL == getTeleportChannelType(id, player);
  877. }
  878. bool CGameInfoCallback::isTeleportChannelUnidirectional(TeleportChannelID id, PlayerColor player) const
  879. {
  880. return ETeleportChannelType::UNIDIRECTIONAL == getTeleportChannelType(id, player);
  881. }
  882. bool CGameInfoCallback::isTeleportEntrancePassable(const CGTeleport * obj, PlayerColor player) const
  883. {
  884. return obj && obj->isEntrance() && !isTeleportChannelImpassable(obj->channel, player);
  885. }
  886. VCMI_LIB_NAMESPACE_END