CGameInfoCallback.cpp 30 KB

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