CGameInfoCallback.cpp 30 KB

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