CGameInfoCallback.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. /*
  2. * CGameInfoCallback.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CGameInfoCallback.h"
  12. #include "entities/building/CBuilding.h"
  13. #include "gameState/CGameState.h"
  14. #include "gameState/InfoAboutArmy.h"
  15. #include "gameState/SThievesGuildInfo.h"
  16. #include "gameState/TavernHeroesPool.h"
  17. #include "gameState/QuestInfo.h"
  18. #include "mapObjects/CGHeroInstance.h"
  19. #include "mapObjects/CGTownInstance.h"
  20. #include "mapObjects/MiscObjects.h"
  21. #include "networkPacks/ArtifactLocation.h"
  22. #include "texts/CGeneralTextHandler.h"
  23. #include "StartInfo.h" // for StartInfo
  24. #include "battle/BattleInfo.h" // for BattleInfo
  25. #include "IGameSettings.h"
  26. #include "TerrainHandler.h"
  27. #include "spells/CSpellHandler.h"
  28. #include "mapping/CMap.h"
  29. #include "CPlayerState.h"
  30. VCMI_LIB_NAMESPACE_BEGIN
  31. //TODO make clean
  32. #define ERROR_VERBOSE_OR_NOT_RET_VAL_IF(cond, verbose, txt, retVal) do {if(cond){if(verbose)logGlobal->error("%s: %s",BOOST_CURRENT_FUNCTION, txt); return retVal;}} while(0)
  33. #define ERROR_RET_IF(cond, txt) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return;}} while(0)
  34. #define ERROR_RET_VAL_IF(cond, txt, retVal) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return retVal;}} while(0)
  35. PlayerColor CGameInfoCallback::getOwner(ObjectInstanceID heroID) const
  36. {
  37. const CGObjectInstance *obj = getObj(heroID);
  38. ERROR_RET_VAL_IF(!obj, "No such object!", PlayerColor::CANNOT_DETERMINE);
  39. return obj->tempOwner;
  40. }
  41. int CGameInfoCallback::getResource(PlayerColor Player, GameResID which) const
  42. {
  43. const PlayerState *p = getPlayerState(Player);
  44. ERROR_RET_VAL_IF(!p, "No player info!", -1);
  45. ERROR_RET_VAL_IF(p->resources.size() <= which.getNum() || which.getNum() < 0, "No such resource!", -1);
  46. return p->resources[which];
  47. }
  48. const PlayerSettings * CGameInfoCallback::getPlayerSettings(PlayerColor color) const
  49. {
  50. return &gs->getStartInfo()->getIthPlayersSettings(color);
  51. }
  52. bool CGameInfoCallback::isAllowed(SpellID id) const
  53. {
  54. return gs->getMap().allowedSpells.count(id) != 0;
  55. }
  56. bool CGameInfoCallback::isAllowed(ArtifactID id) const
  57. {
  58. return gs->getMap().allowedArtifact.count(id) != 0;
  59. }
  60. bool CGameInfoCallback::isAllowed(SecondarySkill id) const
  61. {
  62. return gs->getMap().allowedAbilities.count(id) != 0;
  63. }
  64. std::optional<PlayerColor> CGameInfoCallback::getPlayerID() const
  65. {
  66. return std::nullopt;
  67. }
  68. const Player * CGameInfoCallback::getPlayer(PlayerColor color) const
  69. {
  70. return getPlayerState(color, false);
  71. }
  72. const PlayerState * CGameInfoCallback::getPlayerState(PlayerColor color, bool verbose) const
  73. {
  74. //function written from scratch since it's accessed A LOT by AI
  75. if(!color.isValidPlayer())
  76. {
  77. return nullptr;
  78. }
  79. auto player = gs->players.find(color);
  80. if (player != gs->players.end())
  81. {
  82. if (hasAccess(color))
  83. return &player->second;
  84. else
  85. {
  86. if (verbose)
  87. logGlobal->error("Cannot access player %d info!", color);
  88. return nullptr;
  89. }
  90. }
  91. else
  92. {
  93. if (verbose)
  94. logGlobal->error("Cannot find player %d info!", color);
  95. return nullptr;
  96. }
  97. }
  98. TurnTimerInfo CGameInfoCallback::getPlayerTurnTime(PlayerColor color) const
  99. {
  100. if(!color.isValidPlayer())
  101. {
  102. return TurnTimerInfo{};
  103. }
  104. auto player = gs->players.find(color);
  105. if(player != gs->players.end())
  106. {
  107. return player->second.turnTimer;
  108. }
  109. return TurnTimerInfo{};
  110. }
  111. /************************************************************************/
  112. /* */
  113. /************************************************************************/
  114. const CGObjectInstance* CGameInfoCallback::getObj(ObjectInstanceID objid, bool verbose) const
  115. {
  116. const CGObjectInstance *ret = gs->getMap().getObject(objid);
  117. if(!ret)
  118. {
  119. if(verbose)
  120. logGlobal->error("Cannot get object with id %d. Object was removed", objid.getNum());
  121. return nullptr;
  122. }
  123. if(!isVisible(ret, getPlayerID()) && ret->tempOwner != getPlayerID())
  124. {
  125. if(verbose)
  126. logGlobal->error("Cannot get object with id %d. Object is not visible.", objid.getNum());
  127. return nullptr;
  128. }
  129. return ret;
  130. }
  131. const CGHeroInstance* CGameInfoCallback::getHero(ObjectInstanceID objid) const
  132. {
  133. const CGObjectInstance *obj = getObj(objid, false);
  134. if(obj)
  135. return dynamic_cast<const CGHeroInstance*>(obj);
  136. else
  137. return nullptr;
  138. }
  139. const CGTownInstance* CGameInfoCallback::getTown(ObjectInstanceID objid) const
  140. {
  141. const CGObjectInstance *obj = getObj(objid, false);
  142. if(obj)
  143. return dynamic_cast<const CGTownInstance*>(obj);
  144. else
  145. return nullptr;
  146. }
  147. const IMarket * CGameInfoCallback::getMarket(ObjectInstanceID objid) const
  148. {
  149. const CGObjectInstance * obj = getObj(objid, false);
  150. if(obj)
  151. return dynamic_cast<const IMarket*>(obj);
  152. else
  153. return nullptr;
  154. }
  155. void CGameInfoCallback::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo & out) const
  156. {
  157. //std::shared_lock<std::shared_mutex> lock(*gs->mx);
  158. ERROR_RET_IF(!canGetFullInfo(obj), "Cannot get info about not owned object!");
  159. ERROR_RET_IF(!obj->hasStackAtSlot(stackPos), "There is no such stack!");
  160. gs->fillUpgradeInfo(obj, stackPos, out);
  161. //return gs->fillUpgradeInfo(obj->getStack(stackPos));
  162. }
  163. const StartInfo * CGameInfoCallback::getStartInfo() const
  164. {
  165. return gs->getStartInfo();
  166. }
  167. const StartInfo * CGameInfoCallback::getInitialStartInfo() const
  168. {
  169. return gs->getInitialStartInfo();
  170. }
  171. int32_t CGameInfoCallback::getSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  172. {
  173. //std::shared_lock<std::shared_mutex> lock(*gs->mx);
  174. ERROR_RET_VAL_IF(!canGetFullInfo(caster), "Cannot get info about caster!", -1);
  175. //if there is a battle
  176. auto casterBattle = gs->getBattle(caster->getOwner());
  177. if(casterBattle)
  178. return casterBattle->battleGetSpellCost(sp, caster);
  179. //if there is no battle
  180. return caster->getSpellCost(sp);
  181. }
  182. int64_t CGameInfoCallback::estimateSpellDamage(const CSpell * sp, const CGHeroInstance * hero) const
  183. {
  184. //std::shared_lock<std::shared_mutex> lock(*gs->mx);
  185. ERROR_RET_VAL_IF(hero && !canGetFullInfo(hero), "Cannot get info about caster!", -1);
  186. if(hero) //we see hero's spellbook
  187. return sp->calculateDamage(hero);
  188. else
  189. return 0; //mage guild
  190. }
  191. void CGameInfoCallback::getThievesGuildInfo(SThievesGuildInfo & thi, const CGObjectInstance * obj)
  192. {
  193. //std::shared_lock<std::shared_mutex> lock(*gs->mx);
  194. ERROR_RET_IF(!obj, "No guild object!");
  195. ERROR_RET_IF(obj->ID == Obj::TOWN && !canGetFullInfo(obj), "Cannot get info about town guild object!");
  196. //TODO: advmap object -> check if they're visited by our hero
  197. if(obj->ID == Obj::TOWN || obj->ID == Obj::TAVERN)
  198. {
  199. int taverns = gs->players[*getPlayerID()].valOfBonuses(BonusType::THIEVES_GUILD_ACCESS);
  200. gs->obtainPlayersStats(thi, taverns);
  201. }
  202. else if(obj->ID == Obj::DEN_OF_THIEVES)
  203. {
  204. gs->obtainPlayersStats(thi, 20);
  205. }
  206. }
  207. int CGameInfoCallback::howManyTowns(PlayerColor Player) const
  208. {
  209. ERROR_RET_VAL_IF(!hasAccess(Player), "Access forbidden!", -1);
  210. return static_cast<int>(gs->players[Player].getTowns().size());
  211. }
  212. bool CGameInfoCallback::getTownInfo(const CGObjectInstance * town, InfoAboutTown & dest, const CGObjectInstance * selectedObject) const
  213. {
  214. ERROR_RET_VAL_IF(!isVisible(town, getPlayerID()), "Town is not visible!", false); //it's not a town or it's not visible for layer
  215. bool detailed = hasAccess(town->tempOwner);
  216. if(town->ID == Obj::TOWN)
  217. {
  218. if(!detailed && nullptr != selectedObject)
  219. {
  220. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  221. if(nullptr != selectedHero)
  222. detailed = selectedHero->hasVisions(town, BonusCustomSubtype::visionsTowns);
  223. }
  224. dest.initFromTown(dynamic_cast<const CGTownInstance *>(town), detailed);
  225. }
  226. else if(town->ID == Obj::GARRISON || town->ID == Obj::GARRISON2)
  227. dest.initFromArmy(dynamic_cast<const CArmedInstance *>(town), detailed);
  228. else
  229. return false;
  230. return true;
  231. }
  232. const IGameSettings & CGameInfoCallback::getSettings() const
  233. {
  234. return gs->getSettings();
  235. }
  236. int3 CGameInfoCallback::guardingCreaturePosition (int3 pos) const //FIXME: redundant?
  237. {
  238. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", int3(-1,-1,-1));
  239. return gs->guardingCreaturePosition(pos);
  240. }
  241. std::vector<const CGObjectInstance*> CGameInfoCallback::getGuardingCreatures (int3 pos) const
  242. {
  243. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", std::vector<const CGObjectInstance*>());
  244. std::vector<const CGObjectInstance*> ret;
  245. for(auto * cr : gs->guardingCreatures(pos))
  246. {
  247. ret.push_back(cr);
  248. }
  249. return ret;
  250. }
  251. bool CGameInfoCallback::isTileGuardedUnchecked(int3 tile) const
  252. {
  253. return !gs->guardingCreatures(tile).empty();
  254. }
  255. bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero & dest, const CGObjectInstance * selectedObject) const
  256. {
  257. const auto * h = dynamic_cast<const CGHeroInstance *>(hero);
  258. ERROR_RET_VAL_IF(!h, "That's not a hero!", false);
  259. InfoAboutHero::EInfoLevel infoLevel = InfoAboutHero::EInfoLevel::BASIC;
  260. if(hasAccess(h->tempOwner))
  261. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  262. if (infoLevel == InfoAboutHero::EInfoLevel::BASIC)
  263. {
  264. auto ourBattle = gs->getBattle(*getPlayerID());
  265. if(ourBattle && ourBattle->playerHasAccessToHeroInfo(*getPlayerID(), h)) //if it's battle we can get enemy hero full data
  266. infoLevel = InfoAboutHero::EInfoLevel::INBATTLE;
  267. else
  268. ERROR_RET_VAL_IF(!isVisible(h->visitablePos()), "That hero is not visible!", false);
  269. }
  270. if( (infoLevel == InfoAboutHero::EInfoLevel::BASIC) && nullptr != selectedObject)
  271. {
  272. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  273. if(nullptr != selectedHero)
  274. if(selectedHero->hasVisions(hero, BonusCustomSubtype::visionsHeroes))
  275. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  276. }
  277. dest.initFromHero(h, infoLevel);
  278. //DISGUISED bonus implementation
  279. if(getPlayerRelations(*getPlayerID(), hero->tempOwner) == PlayerRelations::ENEMIES)
  280. {
  281. //todo: bonus cashing
  282. int disguiseLevel = h->valOfBonuses(BonusType::DISGUISED);
  283. auto doBasicDisguise = [](InfoAboutHero & info)
  284. {
  285. int maxAIValue = 0;
  286. const CCreature * mostStrong = nullptr;
  287. for(auto & elem : info.army)
  288. {
  289. if(static_cast<int>(elem.second.getCreature()->getAIValue()) > maxAIValue)
  290. {
  291. maxAIValue = elem.second.getCreature()->getAIValue();
  292. mostStrong = elem.second.getCreature();
  293. }
  294. }
  295. if(nullptr == mostStrong)//just in case
  296. logGlobal->error("CGameInfoCallback::getHeroInfo: Unable to select most strong stack");
  297. else
  298. for(auto & elem : info.army)
  299. {
  300. elem.second.setType(mostStrong);
  301. }
  302. };
  303. auto doAdvancedDisguise = [&doBasicDisguise](InfoAboutHero & info)
  304. {
  305. doBasicDisguise(info);
  306. for(auto & elem : info.army)
  307. elem.second.count = 0;
  308. };
  309. auto doExpertDisguise = [this,h](InfoAboutHero & info)
  310. {
  311. for(auto & elem : info.army)
  312. elem.second.count = 0;
  313. const auto factionIndex = getStartInfo()->playerInfos.at(h->tempOwner).castle;
  314. int maxAIValue = 0;
  315. const CCreature * mostStrong = nullptr;
  316. for(const auto & creature : LIBRARY->creh->objects)
  317. {
  318. if(creature->getFactionID() == factionIndex && static_cast<int>(creature->getAIValue()) > maxAIValue)
  319. {
  320. maxAIValue = creature->getAIValue();
  321. mostStrong = creature.get();
  322. }
  323. }
  324. if(nullptr != mostStrong) //possible, faction may have no creatures at all
  325. for(auto & elem : info.army)
  326. elem.second.setType(mostStrong);
  327. };
  328. switch (disguiseLevel)
  329. {
  330. case 0:
  331. //no bonus at all - do nothing
  332. break;
  333. case 1:
  334. doBasicDisguise(dest);
  335. break;
  336. case 2:
  337. doAdvancedDisguise(dest);
  338. break;
  339. case 3:
  340. doExpertDisguise(dest);
  341. break;
  342. default:
  343. //invalid value
  344. logGlobal->error("CGameInfoCallback::getHeroInfo: Invalid DISGUISED bonus value %d", disguiseLevel);
  345. break;
  346. }
  347. }
  348. return true;
  349. }
  350. int CGameInfoCallback::getDate(Date mode) const
  351. {
  352. //std::shared_lock<std::shared_mutex> lock(*gs->mx);
  353. return gs->getDate(mode);
  354. }
  355. bool CGameInfoCallback::isVisible(int3 pos, const std::optional<PlayerColor> & Player) const
  356. {
  357. //std::shared_lock<std::shared_mutex> lock(*gs->mx);
  358. return gs->isVisible(pos, Player);
  359. }
  360. bool CGameInfoCallback::isVisible(int3 pos) const
  361. {
  362. return isVisible(pos, getPlayerID());
  363. }
  364. bool CGameInfoCallback::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & Player) const
  365. {
  366. return gs->isVisible(obj, Player);
  367. }
  368. bool CGameInfoCallback::isVisible(const CGObjectInstance *obj) const
  369. {
  370. return isVisible(obj, getPlayerID());
  371. }
  372. // const CCreatureSet* CInfoCallback::getGarrison(const CGObjectInstance *obj) const
  373. // {
  374. // //std::shared_lock<std::shared_mutex> lock(*gs->mx);
  375. // if()
  376. // const CArmedInstance *armi = dynamic_cast<const CArmedInstance*>(obj);
  377. // if(!armi)
  378. // return nullptr;
  379. // else
  380. // return armi;
  381. // }
  382. std::vector <const CGObjectInstance *> CGameInfoCallback::getBlockingObjs( int3 pos ) const
  383. {
  384. std::vector<const CGObjectInstance *> ret;
  385. const TerrainTile *t = getTile(pos);
  386. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  387. for(const auto & objID : t->blockingObjects)
  388. ret.push_back(getObj(objID));
  389. return ret;
  390. }
  391. std::vector <const CGObjectInstance *> CGameInfoCallback::getVisitableObjs(int3 pos, bool verbose) const
  392. {
  393. std::vector<const CGObjectInstance *> ret;
  394. const TerrainTile *t = getTile(pos, verbose);
  395. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!t, verbose, pos.toString() + " is not visible!", ret);
  396. for(const auto & objID : t->visitableObjects)
  397. {
  398. const auto & object = getObj(objID);
  399. if(!getPlayerID().has_value() || object->ID != Obj::EVENT) //hide events from players
  400. ret.push_back(object);
  401. }
  402. return ret;
  403. }
  404. std::vector<const CGObjectInstance *> CGameInfoCallback::getAllVisitableObjs() const
  405. {
  406. std::vector<const CGObjectInstance *> ret;
  407. for(auto & obj : gs->getMap().getObjects())
  408. if(obj->isVisitable() && obj->ID != Obj::EVENT && isVisible(obj))
  409. ret.push_back(obj);
  410. return ret;
  411. }
  412. const CGObjectInstance * CGameInfoCallback::getTopObj (int3 pos) const
  413. {
  414. return vstd::backOrNull(getVisitableObjs(pos));
  415. }
  416. std::vector <const CGObjectInstance *> CGameInfoCallback::getFlaggableObjects(int3 pos) const
  417. {
  418. std::vector<const CGObjectInstance *> ret;
  419. const TerrainTile *t = getTile(pos);
  420. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  421. for(const auto & objectID : t->blockingObjects)
  422. {
  423. const auto * obj = getObj(objectID);
  424. if(obj->tempOwner != PlayerColor::UNFLAGGABLE)
  425. ret.push_back(obj);
  426. }
  427. return ret;
  428. }
  429. int3 CGameInfoCallback::getMapSize() const
  430. {
  431. return int3(gs->getMap().width, gs->getMap().height, gs->getMap().twoLevel ? 2 : 1);
  432. }
  433. std::vector<const CGHeroInstance *> CGameInfoCallback::getAvailableHeroes(const CGObjectInstance * townOrTavern) const
  434. {
  435. ASSERT_IF_CALLED_WITH_PLAYER
  436. std::vector<const CGHeroInstance *> ret;
  437. //ERROR_RET_VAL_IF(!isOwnedOrVisited(townOrTavern), "Town or tavern must be owned or visited!", ret);
  438. //TODO: town needs to be owned, advmap tavern needs to be visited; to be reimplemented when visit tracking is done
  439. const CGTownInstance * town = getTown(townOrTavern->id);
  440. if(townOrTavern->ID == Obj::TAVERN || (town && town->hasBuilt(BuildingID::TAVERN)))
  441. return gs->heroesPool->getHeroesFor(*getPlayerID());
  442. return ret;
  443. }
  444. const TerrainTile * CGameInfoCallback::getTile(int3 tile, bool verbose) const
  445. {
  446. if(isVisible(tile))
  447. return &gs->getMap().getTile(tile);
  448. if(verbose)
  449. logGlobal->error("\r\n%s: %s\r\n", BOOST_CURRENT_FUNCTION, tile.toString() + " is not visible!");
  450. return nullptr;
  451. }
  452. const TerrainTile * CGameInfoCallback::getTileUnchecked(int3 tile) const
  453. {
  454. if (isInTheMap(tile))
  455. return &gs->getMap().getTile(tile);
  456. return nullptr;
  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->getMap().getObjects())
  463. {
  464. if(object->ID == Obj::HOLE && object->anchorPos() == 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->getMap().width;
  475. size_t height = gs->getMap().height;
  476. size_t levels = gs->getMap().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->getMap().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->getTown()->buildings.count(ID))
  494. return EBuildingState::BUILDING_ERROR;
  495. const auto & building = t->getTown()->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->getTowns())
  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->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->built >= getSettings().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->getMap();
  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->currentRumor.type == RumorState::TYPE_NONE)
  564. return text.toString();
  565. auto rumor = gs->currentRumor.last[gs->currentRumor.type];
  566. switch(gs->currentRumor.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->getMap().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->getHeroes().size());
  599. else
  600. for(const auto & elem : p->getHeroes())
  601. if(!elem->isGarrisoned())
  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 ObjectInstanceID visitorID = t->visitableObjects.back(); //visitong hero if present or the object itself at last
  611. const CGObjectInstance * visitor = getObj(visitorID);
  612. return visitor->ID == Obj::HERO && canGetFullInfo(visitor); //owned or allied hero is a visitor
  613. }
  614. bool CGameInfoCallback::isPlayerMakingTurn(PlayerColor player) const
  615. {
  616. return gs->actingPlayers.count(player);
  617. }
  618. CGameInfoCallback::CGameInfoCallback():
  619. gs(nullptr)
  620. {
  621. }
  622. CGameInfoCallback::CGameInfoCallback(CGameState * GS):
  623. gs(GS)
  624. {
  625. }
  626. int CPlayerSpecificInfoCallback::howManyTowns() const
  627. {
  628. //std::shared_lock<std::shared_mutex> lock(*gs->mx);
  629. ERROR_RET_VAL_IF(!getPlayerID(), "Applicable only for player callbacks", -1);
  630. return CGameInfoCallback::howManyTowns(*getPlayerID());
  631. }
  632. std::vector < const CGTownInstance *> CPlayerSpecificInfoCallback::getTownsInfo(bool onlyOur) const
  633. {
  634. //std::shared_lock<std::shared_mutex> lock(*gs->mx);
  635. auto ret = std::vector < const CGTownInstance *>();
  636. for(const auto & i : gs->players)
  637. {
  638. for(const auto & town : i.second.getTowns())
  639. {
  640. if(i.first == getPlayerID() || (!onlyOur && isVisible(town, getPlayerID())))
  641. {
  642. ret.push_back(town);
  643. }
  644. }
  645. } // for ( std::map<int, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  646. return ret;
  647. }
  648. std::vector < const CGHeroInstance *> CPlayerSpecificInfoCallback::getHeroesInfo() const
  649. {
  650. const auto * playerState = gs->getPlayerState(*getPlayerID());
  651. return playerState->getHeroes();
  652. }
  653. int CPlayerSpecificInfoCallback::getHeroSerial(const CGHeroInstance * hero, bool includeGarrisoned) const
  654. {
  655. if (hero->isGarrisoned() && !includeGarrisoned)
  656. return -1;
  657. size_t index = 0;
  658. const auto & heroes = gs->players[*getPlayerID()].getHeroes();
  659. for (auto & possibleHero : heroes)
  660. {
  661. if (includeGarrisoned || !(possibleHero)->isGarrisoned())
  662. index++;
  663. if (possibleHero == hero)
  664. return static_cast<int>(index);
  665. }
  666. return -1;
  667. }
  668. int3 CPlayerSpecificInfoCallback::getGrailPos( double *outKnownRatio )
  669. {
  670. if (!getPlayerID() || gs->getMap().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(gs->getMap().obelisksVisited.count(t))
  679. visited = static_cast<double>(gs->getMap().obelisksVisited[t]);
  680. *outKnownRatio = visited / gs->getMap().obeliskCount;
  681. }
  682. return gs->getMap().grailPos;
  683. }
  684. std::vector < const CGObjectInstance * > CPlayerSpecificInfoCallback::getMyObjects() const
  685. {
  686. return gs->getPlayerState(*getPlayerID())->getOwnedObjects();
  687. }
  688. std::vector <QuestInfo> CPlayerSpecificInfoCallback::getMyQuests() const
  689. {
  690. return gs->getPlayerState(*getPlayerID())->quests;
  691. }
  692. int CPlayerSpecificInfoCallback::howManyHeroes(bool includeGarrisoned) const
  693. {
  694. //std::shared_lock<std::shared_mutex> lock(*gs->mx);
  695. ERROR_RET_VAL_IF(!getPlayerID(), "Applicable only for player callbacks", -1);
  696. return getHeroCount(*getPlayerID(), includeGarrisoned);
  697. }
  698. const CGHeroInstance* CPlayerSpecificInfoCallback::getHeroBySerial(int serialId, bool includeGarrisoned) const
  699. {
  700. ASSERT_IF_CALLED_WITH_PLAYER
  701. const PlayerState *p = getPlayerState(*getPlayerID());
  702. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  703. if (!includeGarrisoned)
  704. {
  705. for(ui32 i = 0; i < p->getHeroes().size() && static_cast<int>(i) <= serialId; i++)
  706. if(p->getHeroes()[i]->isGarrisoned())
  707. serialId++;
  708. }
  709. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->getHeroes().size(), "No player info", nullptr);
  710. return p->getHeroes()[serialId];
  711. }
  712. const CGTownInstance* CPlayerSpecificInfoCallback::getTownBySerial(int serialId) const
  713. {
  714. ASSERT_IF_CALLED_WITH_PLAYER
  715. const PlayerState *p = getPlayerState(*getPlayerID());
  716. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  717. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->getTowns().size(), "No player info", nullptr);
  718. return p->getTowns()[serialId];
  719. }
  720. int CPlayerSpecificInfoCallback::getResourceAmount(GameResID type) const
  721. {
  722. //std::shared_lock<std::shared_mutex> lock(*gs->mx);
  723. ERROR_RET_VAL_IF(!getPlayerID(), "Applicable only for player callbacks", -1);
  724. return getResource(*getPlayerID(), type);
  725. }
  726. TResources CPlayerSpecificInfoCallback::getResourceAmount() const
  727. {
  728. //std::shared_lock<std::shared_mutex> lock(*gs->mx);
  729. ERROR_RET_VAL_IF(!getPlayerID(), "Applicable only for player callbacks", TResources());
  730. return gs->players[*getPlayerID()].resources;
  731. }
  732. const TeamState * CGameInfoCallback::getTeam( TeamID teamID ) const
  733. {
  734. //rewritten by hand, AI calls this function a lot
  735. auto team = gs->teams.find(teamID);
  736. if (team != gs->teams.end())
  737. {
  738. const TeamState *ret = &team->second;
  739. if(!getPlayerID().has_value()) //neutral (or invalid) player
  740. return ret;
  741. else
  742. {
  743. if (vstd::contains(ret->players, *getPlayerID())) //specific player
  744. return ret;
  745. else
  746. {
  747. logGlobal->error("Illegal attempt to access team data!");
  748. return nullptr;
  749. }
  750. }
  751. }
  752. else
  753. {
  754. logGlobal->error("Cannot find info for team %d", teamID);
  755. return nullptr;
  756. }
  757. }
  758. const TeamState * CGameInfoCallback::getPlayerTeam( PlayerColor color ) const
  759. {
  760. auto player = gs->players.find(color);
  761. if (player != gs->players.end())
  762. {
  763. return getTeam (player->second.team);
  764. }
  765. else
  766. {
  767. return nullptr;
  768. }
  769. }
  770. bool CGameInfoCallback::isInTheMap(const int3 &pos) const
  771. {
  772. return gs->getMap().isInTheMap(pos);
  773. }
  774. void CGameInfoCallback::getVisibleTilesInRange(std::unordered_set<int3> &tiles, int3 pos, int radious, int3::EDistanceFormula distanceFormula) const
  775. {
  776. gs->getTilesInRange(tiles, pos, radious, ETileVisibility::REVEALED, *getPlayerID(), distanceFormula);
  777. }
  778. void CGameInfoCallback::calculatePaths(const std::shared_ptr<PathfinderConfig> & config) const
  779. {
  780. gs->calculatePaths(config);
  781. }
  782. const CArtifactInstance * CGameInfoCallback::getArtInstance( ArtifactInstanceID aid ) const
  783. {
  784. return gs->getMap().getArtifactInstance(aid);
  785. }
  786. const CGObjectInstance * CGameInfoCallback::getObjInstance( ObjectInstanceID oid ) const
  787. {
  788. return gs->getMap().getObject((oid));
  789. }
  790. const CArtifactSet * CGameInfoCallback::getArtSet(const ArtifactLocation & loc) const
  791. {
  792. return gs->getArtSet(loc);
  793. }
  794. std::vector<ObjectInstanceID> CGameInfoCallback::getVisibleTeleportObjects(std::vector<ObjectInstanceID> ids, PlayerColor player) const
  795. {
  796. vstd::erase_if(ids, [&](const ObjectInstanceID & id) -> bool
  797. {
  798. const auto * obj = getObj(id, false);
  799. return player != PlayerColor::UNFLAGGABLE && (!obj || !isVisible(obj->visitablePos(), player));
  800. });
  801. return ids;
  802. }
  803. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelEntrances(TeleportChannelID id, PlayerColor player) const
  804. {
  805. return getVisibleTeleportObjects(gs->getMap().teleportChannels[id]->entrances, player);
  806. }
  807. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelExits(TeleportChannelID id, PlayerColor player) const
  808. {
  809. return getVisibleTeleportObjects(gs->getMap().teleportChannels[id]->exits, player);
  810. }
  811. ETeleportChannelType CGameInfoCallback::getTeleportChannelType(TeleportChannelID id, PlayerColor player) const
  812. {
  813. std::vector<ObjectInstanceID> entrances = getTeleportChannelEntrances(id, player);
  814. std::vector<ObjectInstanceID> exits = getTeleportChannelExits(id, player);
  815. if((entrances.empty() || exits.empty()) // impassable if exits or entrances list are empty
  816. || (entrances.size() == 1 && entrances == exits)) // impassable if only entrance and only exit is same object. e.g bidirectional monolith
  817. {
  818. return ETeleportChannelType::IMPASSABLE;
  819. }
  820. auto intersection = vstd::intersection(entrances, exits);
  821. if(intersection.size() == entrances.size() && intersection.size() == exits.size())
  822. return ETeleportChannelType::BIDIRECTIONAL;
  823. else if(intersection.empty())
  824. return ETeleportChannelType::UNIDIRECTIONAL;
  825. else
  826. return ETeleportChannelType::MIXED;
  827. }
  828. bool CGameInfoCallback::isTeleportChannelImpassable(TeleportChannelID id, PlayerColor player) const
  829. {
  830. return ETeleportChannelType::IMPASSABLE == getTeleportChannelType(id, player);
  831. }
  832. bool CGameInfoCallback::isTeleportChannelBidirectional(TeleportChannelID id, PlayerColor player) const
  833. {
  834. return ETeleportChannelType::BIDIRECTIONAL == getTeleportChannelType(id, player);
  835. }
  836. bool CGameInfoCallback::isTeleportChannelUnidirectional(TeleportChannelID id, PlayerColor player) const
  837. {
  838. return ETeleportChannelType::UNIDIRECTIONAL == getTeleportChannelType(id, player);
  839. }
  840. bool CGameInfoCallback::isTeleportEntrancePassable(const CGTeleport * obj, PlayerColor player) const
  841. {
  842. return obj && obj->isEntrance() && !isTeleportChannelImpassable(obj->channel, player);
  843. }
  844. VCMI_LIB_NAMESPACE_END