CGameInfoCallback.cpp 29 KB

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