CGameInfoCallback.cpp 29 KB

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