CGameInfoCallback.cpp 28 KB

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