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 "GameSettings.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->scenarioOps->getIthPlayersSettings(color);
  51. }
  52. bool CGameInfoCallback::isAllowed(SpellID id) const
  53. {
  54. return gs->map->allowedSpells.count(id) != 0;
  55. }
  56. bool CGameInfoCallback::isAllowed(ArtifactID id) const
  57. {
  58. return gs->map->allowedArtifact.count(id) != 0;
  59. }
  60. bool CGameInfoCallback::isAllowed(SecondarySkill id) const
  61. {
  62. return gs->map->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->map->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->map->objects[oid];
  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. //boost::shared_lock<boost::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(bool beforeRandomization) const
  171. {
  172. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  173. if(beforeRandomization)
  174. return gs->initialOpts;
  175. else
  176. return gs->scenarioOps;
  177. }
  178. int32_t CGameInfoCallback::getSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  179. {
  180. //boost::shared_lock<boost::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. //boost::shared_lock<boost::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. //boost::shared_lock<boost::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. int3 CGameInfoCallback::guardingCreaturePosition (int3 pos) const //FIXME: redundant?
  240. {
  241. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", int3(-1,-1,-1));
  242. return gs->guardingCreaturePosition(pos);
  243. }
  244. std::vector<const CGObjectInstance*> CGameInfoCallback::getGuardingCreatures (int3 pos) const
  245. {
  246. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", std::vector<const CGObjectInstance*>());
  247. std::vector<const CGObjectInstance*> ret;
  248. for(auto * cr : gs->guardingCreatures(pos))
  249. {
  250. ret.push_back(cr);
  251. }
  252. return ret;
  253. }
  254. bool CGameInfoCallback::isTileGuardedUnchecked(int3 tile) const
  255. {
  256. return !gs->guardingCreatures(tile).empty();
  257. }
  258. bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero & dest, const CGObjectInstance * selectedObject) const
  259. {
  260. const auto * h = dynamic_cast<const CGHeroInstance *>(hero);
  261. ERROR_RET_VAL_IF(!h, "That's not a hero!", false);
  262. InfoAboutHero::EInfoLevel infoLevel = InfoAboutHero::EInfoLevel::BASIC;
  263. if(hasAccess(h->tempOwner))
  264. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  265. if (infoLevel == InfoAboutHero::EInfoLevel::BASIC)
  266. {
  267. auto ourBattle = gs->getBattle(*getPlayerID());
  268. if(ourBattle && ourBattle->playerHasAccessToHeroInfo(*getPlayerID(), h)) //if it's battle we can get enemy hero full data
  269. infoLevel = InfoAboutHero::EInfoLevel::INBATTLE;
  270. else
  271. ERROR_RET_VAL_IF(!isVisible(h->visitablePos()), "That hero is not visible!", false);
  272. }
  273. if( (infoLevel == InfoAboutHero::EInfoLevel::BASIC) && nullptr != selectedObject)
  274. {
  275. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  276. if(nullptr != selectedHero)
  277. if(selectedHero->hasVisions(hero, BonusCustomSubtype::visionsHeroes))
  278. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  279. }
  280. dest.initFromHero(h, infoLevel);
  281. //DISGUISED bonus implementation
  282. if(getPlayerRelations(*getPlayerID(), hero->tempOwner) == PlayerRelations::ENEMIES)
  283. {
  284. //todo: bonus cashing
  285. int disguiseLevel = h->valOfBonuses(BonusType::DISGUISED);
  286. auto doBasicDisguise = [](InfoAboutHero & info)
  287. {
  288. int maxAIValue = 0;
  289. const CCreature * mostStrong = nullptr;
  290. for(auto & elem : info.army)
  291. {
  292. if(static_cast<int>(elem.second.type->getAIValue()) > maxAIValue)
  293. {
  294. maxAIValue = elem.second.type->getAIValue();
  295. mostStrong = elem.second.type;
  296. }
  297. }
  298. if(nullptr == mostStrong)//just in case
  299. logGlobal->error("CGameInfoCallback::getHeroInfo: Unable to select most strong stack");
  300. else
  301. for(auto & elem : info.army)
  302. {
  303. elem.second.type = mostStrong;
  304. }
  305. };
  306. auto doAdvancedDisguise = [&doBasicDisguise](InfoAboutHero & info)
  307. {
  308. doBasicDisguise(info);
  309. for(auto & elem : info.army)
  310. elem.second.count = 0;
  311. };
  312. auto doExpertDisguise = [this,h](InfoAboutHero & info)
  313. {
  314. for(auto & elem : info.army)
  315. elem.second.count = 0;
  316. const auto factionIndex = getStartInfo(false)->playerInfos.at(h->tempOwner).castle;
  317. int maxAIValue = 0;
  318. const CCreature * mostStrong = nullptr;
  319. for(const auto & creature : VLC->creh->objects)
  320. {
  321. if(creature->getFaction() == factionIndex && static_cast<int>(creature->getAIValue()) > maxAIValue)
  322. {
  323. maxAIValue = creature->getAIValue();
  324. mostStrong = creature.get();
  325. }
  326. }
  327. if(nullptr != mostStrong) //possible, faction may have no creatures at all
  328. for(auto & elem : info.army)
  329. elem.second.type = mostStrong;
  330. };
  331. switch (disguiseLevel)
  332. {
  333. case 0:
  334. //no bonus at all - do nothing
  335. break;
  336. case 1:
  337. doBasicDisguise(dest);
  338. break;
  339. case 2:
  340. doAdvancedDisguise(dest);
  341. break;
  342. case 3:
  343. doExpertDisguise(dest);
  344. break;
  345. default:
  346. //invalid value
  347. logGlobal->error("CGameInfoCallback::getHeroInfo: Invalid DISGUISED bonus value %d", disguiseLevel);
  348. break;
  349. }
  350. }
  351. return true;
  352. }
  353. int CGameInfoCallback::getDate(Date mode) const
  354. {
  355. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  356. return gs->getDate(mode);
  357. }
  358. bool CGameInfoCallback::isVisible(int3 pos, const std::optional<PlayerColor> & Player) const
  359. {
  360. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  361. return gs->isVisible(pos, Player);
  362. }
  363. bool CGameInfoCallback::isVisible(int3 pos) const
  364. {
  365. return isVisible(pos, getPlayerID());
  366. }
  367. bool CGameInfoCallback::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & Player) const
  368. {
  369. return gs->isVisible(obj, Player);
  370. }
  371. bool CGameInfoCallback::isVisible(const CGObjectInstance *obj) const
  372. {
  373. return isVisible(obj, getPlayerID());
  374. }
  375. // const CCreatureSet* CInfoCallback::getGarrison(const CGObjectInstance *obj) const
  376. // {
  377. // //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  378. // if()
  379. // const CArmedInstance *armi = dynamic_cast<const CArmedInstance*>(obj);
  380. // if(!armi)
  381. // return nullptr;
  382. // else
  383. // return armi;
  384. // }
  385. std::vector <const CGObjectInstance *> CGameInfoCallback::getBlockingObjs( int3 pos ) const
  386. {
  387. std::vector<const CGObjectInstance *> ret;
  388. const TerrainTile *t = getTile(pos);
  389. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  390. for(const CGObjectInstance * obj : t->blockingObjects)
  391. ret.push_back(obj);
  392. return ret;
  393. }
  394. std::vector <const CGObjectInstance *> CGameInfoCallback::getVisitableObjs(int3 pos, bool verbose) const
  395. {
  396. std::vector<const CGObjectInstance *> ret;
  397. const TerrainTile *t = getTile(pos, verbose);
  398. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!t, verbose, pos.toString() + " is not visible!", ret);
  399. for(const CGObjectInstance * obj : t->visitableObjects)
  400. {
  401. if(getPlayerID() || obj->ID != Obj::EVENT) //hide events from players
  402. ret.push_back(obj);
  403. }
  404. return ret;
  405. }
  406. const CGObjectInstance * CGameInfoCallback::getTopObj (int3 pos) const
  407. {
  408. return vstd::backOrNull(getVisitableObjs(pos));
  409. }
  410. std::vector <const CGObjectInstance *> CGameInfoCallback::getFlaggableObjects(int3 pos) const
  411. {
  412. std::vector<const CGObjectInstance *> ret;
  413. const TerrainTile *t = getTile(pos);
  414. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  415. for(const CGObjectInstance *obj : t->blockingObjects)
  416. if(obj->tempOwner != PlayerColor::UNFLAGGABLE)
  417. ret.push_back(obj);
  418. return ret;
  419. }
  420. int3 CGameInfoCallback::getMapSize() const
  421. {
  422. return int3(gs->map->width, gs->map->height, gs->map->twoLevel ? 2 : 1);
  423. }
  424. std::vector<const CGHeroInstance *> CGameInfoCallback::getAvailableHeroes(const CGObjectInstance * townOrTavern) const
  425. {
  426. ASSERT_IF_CALLED_WITH_PLAYER
  427. std::vector<const CGHeroInstance *> ret;
  428. //ERROR_RET_VAL_IF(!isOwnedOrVisited(townOrTavern), "Town or tavern must be owned or visited!", ret);
  429. //TODO: town needs to be owned, advmap tavern needs to be visited; to be reimplemented when visit tracking is done
  430. const CGTownInstance * town = getTown(townOrTavern->id);
  431. if(townOrTavern->ID == Obj::TAVERN || (town && town->hasBuilt(BuildingID::TAVERN)))
  432. return gs->heroesPool->getHeroesFor(*getPlayerID());
  433. return ret;
  434. }
  435. const TerrainTile * CGameInfoCallback::getTile(int3 tile, bool verbose) const
  436. {
  437. if(isVisible(tile))
  438. return &gs->map->getTile(tile);
  439. if(verbose)
  440. logGlobal->error("\r\n%s: %s\r\n", BOOST_CURRENT_FUNCTION, tile.toString() + " is not visible!");
  441. return nullptr;
  442. }
  443. const TerrainTile * CGameInfoCallback::getTileUnchecked(int3 tile) const
  444. {
  445. if (isInTheMap(tile))
  446. return &gs->map->getTile(tile);
  447. return nullptr;
  448. }
  449. EDiggingStatus CGameInfoCallback::getTileDigStatus(int3 tile, bool verbose) const
  450. {
  451. if(!isVisible(tile))
  452. return EDiggingStatus::UNKNOWN;
  453. for(const auto & object : gs->map->objects)
  454. {
  455. if(object && object->ID == Obj::HOLE && object->pos == tile)
  456. return EDiggingStatus::TILE_OCCUPIED;
  457. }
  458. return getTile(tile)->getDiggingStatus();
  459. }
  460. //TODO: typedef?
  461. std::shared_ptr<const boost::multi_array<TerrainTile*, 3>> CGameInfoCallback::getAllVisibleTiles() const
  462. {
  463. assert(getPlayerID().has_value());
  464. const auto * team = getPlayerTeam(getPlayerID().value());
  465. size_t width = gs->map->width;
  466. size_t height = gs->map->height;
  467. size_t levels = gs->map->levels();
  468. auto * ptr = new boost::multi_array<TerrainTile *, 3>(boost::extents[levels][width][height]);
  469. int3 tile;
  470. for(tile.z = 0; tile.z < levels; tile.z++)
  471. for(tile.x = 0; tile.x < width; tile.x++)
  472. for(tile.y = 0; tile.y < height; tile.y++)
  473. {
  474. if (team->fogOfWarMap[tile.z][tile.x][tile.y])
  475. (*ptr)[tile.z][tile.x][tile.y] = &gs->map->getTile(tile);
  476. else
  477. (*ptr)[tile.z][tile.x][tile.y] = nullptr;
  478. }
  479. return std::shared_ptr<const boost::multi_array<TerrainTile*, 3>>(ptr);
  480. }
  481. EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID )
  482. {
  483. ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", EBuildingState::TOWN_NOT_OWNED);
  484. if(!t->town->buildings.count(ID))
  485. return EBuildingState::BUILDING_ERROR;
  486. const CBuilding * building = t->town->buildings.at(ID);
  487. if(t->hasBuilt(ID)) //already built
  488. return EBuildingState::ALREADY_PRESENT;
  489. //can we build it?
  490. if(vstd::contains(t->forbiddenBuildings, ID))
  491. return EBuildingState::FORBIDDEN; //forbidden
  492. auto possiblyNotBuiltTest = [&](const BuildingID & id) -> bool
  493. {
  494. return ((id == BuildingID::CAPITOL) ? true : !t->hasBuilt(id));
  495. };
  496. std::function<bool(BuildingID id)> allowedTest = [&](const BuildingID & id) -> bool
  497. {
  498. return !vstd::contains(t->forbiddenBuildings, id);
  499. };
  500. if (!t->genBuildingRequirements(ID, true).satisfiable(allowedTest, possiblyNotBuiltTest))
  501. return EBuildingState::FORBIDDEN;
  502. if(ID == BuildingID::CAPITOL)
  503. {
  504. const PlayerState *ps = getPlayerState(t->tempOwner, false);
  505. if(ps)
  506. {
  507. for(const CGTownInstance *town : ps->getTowns())
  508. {
  509. if(town->hasBuilt(BuildingID::CAPITOL))
  510. {
  511. return EBuildingState::HAVE_CAPITAL; //no more than one capitol
  512. }
  513. }
  514. }
  515. }
  516. else if(ID == BuildingID::SHIPYARD)
  517. {
  518. const TerrainTile *tile = getTile(t->bestLocation(), false);
  519. if(!tile || !tile->terType->isWater())
  520. return EBuildingState::NO_WATER; //lack of water
  521. }
  522. auto buildTest = [&](const BuildingID & id) -> bool
  523. {
  524. return t->hasBuilt(id);
  525. };
  526. if (!t->genBuildingRequirements(ID).test(buildTest))
  527. return EBuildingState::PREREQUIRES;
  528. if(t->built >= VLC->settings()->getInteger(EGameSettings::TOWNS_BUILDINGS_PER_TURN_CAP))
  529. return EBuildingState::CANT_BUILD_TODAY; //building limit
  530. //checking resources
  531. if(!building->resources.canBeAfforded(getPlayerState(t->tempOwner)->resources))
  532. return EBuildingState::NO_RESOURCES; //lack of res
  533. return EBuildingState::ALLOWED;
  534. }
  535. const CMapHeader * CGameInfoCallback::getMapHeader() const
  536. {
  537. return gs->map;
  538. }
  539. bool CGameInfoCallback::hasAccess(std::optional<PlayerColor> playerId) const
  540. {
  541. return !getPlayerID() || getPlayerID()->isSpectator() || gs->getPlayerRelations(*playerId, *getPlayerID()) != PlayerRelations::ENEMIES;
  542. }
  543. EPlayerStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const
  544. {
  545. const PlayerState *ps = gs->getPlayerState(player, verbose);
  546. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!ps, verbose, "No such player!", EPlayerStatus::WRONG);
  547. return ps->status;
  548. }
  549. std::string CGameInfoCallback::getTavernRumor(const CGObjectInstance * townOrTavern) const
  550. {
  551. MetaString text;
  552. text.appendLocalString(EMetaText::GENERAL_TXT, 216);
  553. std::string extraText;
  554. if(gs->currentRumor.type == RumorState::TYPE_NONE)
  555. return text.toString();
  556. auto rumor = gs->currentRumor.last[gs->currentRumor.type];
  557. switch(gs->currentRumor.type)
  558. {
  559. case RumorState::TYPE_SPECIAL:
  560. text.replaceLocalString(EMetaText::GENERAL_TXT, rumor.first);
  561. if(rumor.first == RumorState::RUMOR_GRAIL)
  562. text.replaceTextID(TextIdentifier("core", "arraytxt", 158 + rumor.second).get());
  563. else
  564. text.replaceTextID(TextIdentifier("core", "plcolors", rumor.second).get());
  565. break;
  566. case RumorState::TYPE_MAP:
  567. text.replaceRawString(gs->map->rumors[rumor.first].text.toString());
  568. break;
  569. case RumorState::TYPE_RAND:
  570. text.replaceTextID(TextIdentifier("core", "randtvrn", rumor.first).get());
  571. break;
  572. }
  573. return text.toString();
  574. }
  575. PlayerRelations CGameInfoCallback::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  576. {
  577. return gs->getPlayerRelations(color1, color2);
  578. }
  579. bool CGameInfoCallback::canGetFullInfo(const CGObjectInstance *obj) const
  580. {
  581. return !obj || hasAccess(obj->tempOwner);
  582. }
  583. int CGameInfoCallback::getHeroCount( PlayerColor player, bool includeGarrisoned ) const
  584. {
  585. int ret = 0;
  586. const PlayerState *p = gs->getPlayerState(player);
  587. ERROR_RET_VAL_IF(!p, "No such player!", -1);
  588. if(includeGarrisoned)
  589. return static_cast<int>(p->getHeroes().size());
  590. else
  591. for(const auto & elem : p->getHeroes())
  592. if(!elem->inTownGarrison)
  593. ret++;
  594. return ret;
  595. }
  596. bool CGameInfoCallback::isOwnedOrVisited(const CGObjectInstance *obj) const
  597. {
  598. if(canGetFullInfo(obj))
  599. return true;
  600. const TerrainTile *t = getTile(obj->visitablePos()); //get entrance tile
  601. const CGObjectInstance *visitor = t->visitableObjects.back(); //visitong hero if present or the object itself at last
  602. return visitor->ID == Obj::HERO && canGetFullInfo(visitor); //owned or allied hero is a visitor
  603. }
  604. bool CGameInfoCallback::isPlayerMakingTurn(PlayerColor player) const
  605. {
  606. return gs->actingPlayers.count(player);
  607. }
  608. CGameInfoCallback::CGameInfoCallback():
  609. gs(nullptr)
  610. {
  611. }
  612. CGameInfoCallback::CGameInfoCallback(CGameState * GS):
  613. gs(GS)
  614. {
  615. }
  616. int CPlayerSpecificInfoCallback::howManyTowns() const
  617. {
  618. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  619. ERROR_RET_VAL_IF(!getPlayerID(), "Applicable only for player callbacks", -1);
  620. return CGameInfoCallback::howManyTowns(*getPlayerID());
  621. }
  622. std::vector < const CGTownInstance *> CPlayerSpecificInfoCallback::getTownsInfo(bool onlyOur) const
  623. {
  624. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  625. auto ret = std::vector < const CGTownInstance *>();
  626. for(const auto & i : gs->players)
  627. {
  628. for(const auto & town : i.second.getTowns())
  629. {
  630. if(i.first == getPlayerID() || (!onlyOur && isVisible(town, getPlayerID())))
  631. {
  632. ret.push_back(town);
  633. }
  634. }
  635. } // for ( std::map<int, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  636. return ret;
  637. }
  638. std::vector < const CGHeroInstance *> CPlayerSpecificInfoCallback::getHeroesInfo(bool onlyOur) const
  639. {
  640. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  641. std::vector < const CGHeroInstance *> ret;
  642. for(auto hero : gs->map->heroesOnMap)
  643. {
  644. // !player || // - why would we even get access to hero not owned by any player?
  645. if((hero->tempOwner == *getPlayerID()) ||
  646. (isVisible(hero->visitablePos(), getPlayerID()) && !onlyOur) )
  647. {
  648. ret.push_back(hero);
  649. }
  650. }
  651. return ret;
  652. }
  653. int CPlayerSpecificInfoCallback::getHeroSerial(const CGHeroInstance * hero, bool includeGarrisoned) const
  654. {
  655. if (hero->inTownGarrison && !includeGarrisoned)
  656. return -1;
  657. size_t index = 0;
  658. const auto & heroes = gs->players[*getPlayerID()].getHeroes();
  659. for (auto & possibleHero : heroes)
  660. {
  661. if (includeGarrisoned || !(possibleHero)->inTownGarrison)
  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->map->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->map->obelisksVisited.count(t))
  679. visited = static_cast<double>(gs->map->obelisksVisited[t]);
  680. *outKnownRatio = visited / gs->map->obeliskCount;
  681. }
  682. return gs->map->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. //boost::shared_lock<boost::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]->inTownGarrison)
  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. //boost::shared_lock<boost::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. //boost::shared_lock<boost::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. const CGHeroInstance * CGameInfoCallback::getHeroWithSubid( int subid ) const
  771. {
  772. if(subid<0)
  773. return nullptr;
  774. if(subid>= gs->map->allHeroes.size())
  775. return nullptr;
  776. return gs->map->allHeroes.at(subid).get();
  777. }
  778. bool CGameInfoCallback::isInTheMap(const int3 &pos) const
  779. {
  780. return gs->map->isInTheMap(pos);
  781. }
  782. void CGameInfoCallback::getVisibleTilesInRange(std::unordered_set<int3> &tiles, int3 pos, int radious, int3::EDistanceFormula distanceFormula) const
  783. {
  784. gs->getTilesInRange(tiles, pos, radious, ETileVisibility::REVEALED, *getPlayerID(), distanceFormula);
  785. }
  786. void CGameInfoCallback::calculatePaths(const std::shared_ptr<PathfinderConfig> & config)
  787. {
  788. gs->calculatePaths(config);
  789. }
  790. void CGameInfoCallback::calculatePaths( const CGHeroInstance *hero, CPathsInfo &out)
  791. {
  792. gs->calculatePaths(hero, out);
  793. }
  794. const CArtifactInstance * CGameInfoCallback::getArtInstance( ArtifactInstanceID aid ) const
  795. {
  796. return gs->map->artInstances[aid.num];
  797. }
  798. const CGObjectInstance * CGameInfoCallback::getObjInstance( ObjectInstanceID oid ) const
  799. {
  800. return gs->map->objects[oid.num];
  801. }
  802. const CArtifactSet * CGameInfoCallback::getArtSet(const ArtifactLocation & loc) const
  803. {
  804. return gs->getArtSet(loc);
  805. }
  806. std::vector<ObjectInstanceID> CGameInfoCallback::getVisibleTeleportObjects(std::vector<ObjectInstanceID> ids, PlayerColor player) const
  807. {
  808. vstd::erase_if(ids, [&](const ObjectInstanceID & id) -> bool
  809. {
  810. const auto * obj = getObj(id, false);
  811. return player != PlayerColor::UNFLAGGABLE && (!obj || !isVisible(obj->pos, player));
  812. });
  813. return ids;
  814. }
  815. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelEntrances(TeleportChannelID id, PlayerColor player) const
  816. {
  817. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->entrances, player);
  818. }
  819. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelExits(TeleportChannelID id, PlayerColor player) const
  820. {
  821. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->exits, player);
  822. }
  823. ETeleportChannelType CGameInfoCallback::getTeleportChannelType(TeleportChannelID id, PlayerColor player) const
  824. {
  825. std::vector<ObjectInstanceID> entrances = getTeleportChannelEntrances(id, player);
  826. std::vector<ObjectInstanceID> exits = getTeleportChannelExits(id, player);
  827. if((entrances.empty() || exits.empty()) // impassable if exits or entrances list are empty
  828. || (entrances.size() == 1 && entrances == exits)) // impassable if only entrance and only exit is same object. e.g bidirectional monolith
  829. {
  830. return ETeleportChannelType::IMPASSABLE;
  831. }
  832. auto intersection = vstd::intersection(entrances, exits);
  833. if(intersection.size() == entrances.size() && intersection.size() == exits.size())
  834. return ETeleportChannelType::BIDIRECTIONAL;
  835. else if(intersection.empty())
  836. return ETeleportChannelType::UNIDIRECTIONAL;
  837. else
  838. return ETeleportChannelType::MIXED;
  839. }
  840. bool CGameInfoCallback::isTeleportChannelImpassable(TeleportChannelID id, PlayerColor player) const
  841. {
  842. return ETeleportChannelType::IMPASSABLE == getTeleportChannelType(id, player);
  843. }
  844. bool CGameInfoCallback::isTeleportChannelBidirectional(TeleportChannelID id, PlayerColor player) const
  845. {
  846. return ETeleportChannelType::BIDIRECTIONAL == getTeleportChannelType(id, player);
  847. }
  848. bool CGameInfoCallback::isTeleportChannelUnidirectional(TeleportChannelID id, PlayerColor player) const
  849. {
  850. return ETeleportChannelType::UNIDIRECTIONAL == getTeleportChannelType(id, player);
  851. }
  852. bool CGameInfoCallback::isTeleportEntrancePassable(const CGTeleport * obj, PlayerColor player) const
  853. {
  854. return obj && obj->isEntrance() && !isTeleportChannelImpassable(obj->channel, player);
  855. }
  856. VCMI_LIB_NAMESPACE_END