CGameInfoCallback.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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/UpgradeInfo.h"
  15. #include "../gameState/InfoAboutArmy.h"
  16. #include "../gameState/TavernHeroesPool.h"
  17. #include "../mapObjects/CGHeroInstance.h"
  18. #include "../mapObjects/CGTownInstance.h"
  19. #include "../mapObjects/MiscObjects.h"
  20. #include "../StartInfo.h"
  21. #include "../battle/BattleInfo.h"
  22. #include "../IGameSettings.h"
  23. #include "../spells/CSpellHandler.h"
  24. #include "../mapping/CMap.h"
  25. #include "../CPlayerState.h"
  26. #define ASSERT_IF_CALLED_WITH_PLAYER if(!getPlayerID()) {logGlobal->error(BOOST_CURRENT_FUNCTION); assert(0);}
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. //TODO make clean
  29. #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)
  30. #define ERROR_RET_IF(cond, txt) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return;}} while(0)
  31. #define ERROR_RET_VAL_IF(cond, txt, retVal) do {if(cond){logGlobal->error("%s: %s", BOOST_CURRENT_FUNCTION, txt); return retVal;}} while(0)
  32. const IMarket * CGameInfoCallback::getMarket(ObjectInstanceID objid) const
  33. {
  34. const CGObjectInstance * obj = getObj(objid, false);
  35. return dynamic_cast<const IMarket*>(obj);
  36. }
  37. int CGameInfoCallback::getResource(PlayerColor Player, GameResID which) const
  38. {
  39. const PlayerState *p = getPlayerState(Player);
  40. ERROR_RET_VAL_IF(!p, "No player info!", -1);
  41. ERROR_RET_VAL_IF(p->resources.size() <= which.getNum() || which.getNum() < 0, "No such resource!", -1);
  42. return p->resources[which];
  43. }
  44. const PlayerSettings * CGameInfoCallback::getPlayerSettings(PlayerColor color) const
  45. {
  46. return &gameState().getStartInfo()->getIthPlayersSettings(color);
  47. }
  48. std::optional<PlayerColor> CGameInfoCallback::getPlayerID() const
  49. {
  50. return std::nullopt;
  51. }
  52. const Player * CGameInfoCallback::getPlayer(PlayerColor color) const
  53. {
  54. return getPlayerState(color, false);
  55. }
  56. const PlayerState * CGameInfoCallback::getPlayerState(PlayerColor color, bool verbose) const
  57. {
  58. //function written from scratch since it's accessed A LOT by AI
  59. if(!color.isValidPlayer())
  60. {
  61. return nullptr;
  62. }
  63. auto player = gameState().players.find(color);
  64. if (player != gameState().players.end())
  65. {
  66. if (hasAccess(color))
  67. return &player->second;
  68. else
  69. {
  70. if (verbose)
  71. logGlobal->error("Cannot access player %d info!", color);
  72. return nullptr;
  73. }
  74. }
  75. else
  76. {
  77. if (verbose)
  78. logGlobal->error("Cannot find player %d info!", color);
  79. return nullptr;
  80. }
  81. }
  82. TurnTimerInfo CGameInfoCallback::getPlayerTurnTime(PlayerColor color) const
  83. {
  84. if(!color.isValidPlayer())
  85. {
  86. return TurnTimerInfo{};
  87. }
  88. auto player = gameState().players.find(color);
  89. if(player != gameState().players.end())
  90. {
  91. return player->second.turnTimer;
  92. }
  93. return TurnTimerInfo{};
  94. }
  95. /************************************************************************/
  96. /* */
  97. /************************************************************************/
  98. const CGObjectInstance* CGameInfoCallback::getObj(ObjectInstanceID objid, bool verbose) const
  99. {
  100. const CGObjectInstance * ret = MapInfoCallback::getObj(objid, verbose);
  101. if(!ret)
  102. return nullptr;
  103. if(getPlayerID().has_value() && !isVisibleFor(ret, *getPlayerID()) && ret->tempOwner != getPlayerID())
  104. {
  105. if(verbose)
  106. logGlobal->error("Cannot get object with id %d. Object is not visible.", objid.getNum());
  107. return nullptr;
  108. }
  109. return ret;
  110. }
  111. void CGameInfoCallback::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo & out) const
  112. {
  113. ERROR_RET_IF(!canGetFullInfo(obj), "Cannot get info about not owned object!");
  114. ERROR_RET_IF(!obj->hasStackAtSlot(stackPos), "There is no such stack!");
  115. const auto & stack = obj->getStack(stackPos);
  116. const CCreature *base = stack.getCreature();
  117. UpgradeInfo ret(base->getId());
  118. if (stack.getArmy()->ID == Obj::HERO)
  119. {
  120. auto hero = dynamic_cast<const CGHeroInstance *>(stack.getArmy());
  121. hero->fillUpgradeInfo(ret, stack);
  122. if (hero->getVisitedTown())
  123. {
  124. hero->getVisitedTown()->fillUpgradeInfo(ret, stack);
  125. }
  126. else
  127. {
  128. auto object = vstd::frontOrNull(getVisitableObjs(hero->visitablePos()));
  129. auto upgradeSource = dynamic_cast<const ICreatureUpgrader*>(object);
  130. if (object != hero && upgradeSource != nullptr)
  131. upgradeSource->fillUpgradeInfo(ret, stack);
  132. }
  133. }
  134. if (stack.getArmy()->ID == Obj::TOWN)
  135. {
  136. auto town = dynamic_cast<const CGTownInstance *>(stack.getArmy());
  137. town->fillUpgradeInfo(ret, stack);
  138. }
  139. out = ret;
  140. }
  141. const StartInfo * CGameInfoCallback::getStartInfo() const
  142. {
  143. return gameState().getStartInfo();
  144. }
  145. const StartInfo * CGameInfoCallback::getInitialStartInfo() const
  146. {
  147. return gameState().getInitialStartInfo();
  148. }
  149. int32_t CGameInfoCallback::getSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  150. {
  151. ERROR_RET_VAL_IF(!canGetFullInfo(caster), "Cannot get info about caster!", -1);
  152. //if there is a battle
  153. auto casterBattle = gameState().getBattle(caster->getOwner());
  154. if(casterBattle)
  155. return casterBattle->battleGetSpellCost(sp, caster);
  156. //if there is no battle
  157. return caster->getSpellCost(sp);
  158. }
  159. int64_t CGameInfoCallback::estimateSpellDamage(const CSpell * sp, const CGHeroInstance * hero) const
  160. {
  161. ERROR_RET_VAL_IF(hero && !canGetFullInfo(hero), "Cannot get info about caster!", -1);
  162. if(hero) //we see hero's spellbook
  163. return sp->calculateDamage(hero);
  164. else
  165. return 0; //mage guild
  166. }
  167. void CGameInfoCallback::getThievesGuildInfo(SThievesGuildInfo & thi, const CGObjectInstance * obj)
  168. {
  169. ERROR_RET_IF(!obj, "No guild object!");
  170. ERROR_RET_IF(obj->ID == Obj::TOWN && !canGetFullInfo(obj), "Cannot get info about town guild object!");
  171. //TODO: advmap object -> check if they're visited by our hero
  172. if(obj->ID == Obj::TOWN || obj->ID == Obj::TAVERN)
  173. {
  174. int taverns = gameState().players.at(*getPlayerID()).valOfBonuses(BonusType::THIEVES_GUILD_ACCESS);
  175. gameState().obtainPlayersStats(thi, taverns);
  176. }
  177. else if(obj->ID == Obj::DEN_OF_THIEVES)
  178. {
  179. gameState().obtainPlayersStats(thi, 20);
  180. }
  181. }
  182. int CGameInfoCallback::howManyTowns(PlayerColor Player) const
  183. {
  184. ERROR_RET_VAL_IF(!hasAccess(Player), "Access forbidden!", -1);
  185. return static_cast<int>(gameState().players.at(Player).getTowns().size());
  186. }
  187. bool CGameInfoCallback::getTownInfo(const CGObjectInstance * town, InfoAboutTown & dest, const CGObjectInstance * selectedObject) const
  188. {
  189. ERROR_RET_VAL_IF(getPlayerID().has_value() && !isVisibleFor(town, *getPlayerID()), "Town is not visible!", false); //it's not a town or it's not visible for layer
  190. bool detailed = hasAccess(town->tempOwner);
  191. if(town->ID == Obj::TOWN)
  192. {
  193. if(!detailed && nullptr != selectedObject)
  194. {
  195. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  196. if(nullptr != selectedHero)
  197. detailed = selectedHero->hasVisions(town, BonusCustomSubtype::visionsTowns);
  198. }
  199. dest.initFromTown(dynamic_cast<const CGTownInstance *>(town), detailed);
  200. }
  201. else if(town->ID == Obj::GARRISON || town->ID == Obj::GARRISON2)
  202. dest.initFromArmy(dynamic_cast<const CArmedInstance *>(town), detailed);
  203. else
  204. return false;
  205. return true;
  206. }
  207. int3 CGameInfoCallback::guardingCreaturePosition (int3 pos) const
  208. {
  209. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", int3(-1,-1,-1));
  210. return gameState().getMap().guardingCreaturePositions[pos.z][pos.x][pos.y];
  211. }
  212. std::vector<const CGObjectInstance*> CGameInfoCallback::getGuardingCreatures (int3 pos) const
  213. {
  214. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", std::vector<const CGObjectInstance*>());
  215. std::vector<const CGObjectInstance*> ret;
  216. for(auto * cr : gameState().guardingCreatures(pos))
  217. {
  218. ret.push_back(cr);
  219. }
  220. return ret;
  221. }
  222. bool CGameInfoCallback::isTileGuardedUnchecked(int3 tile) const
  223. {
  224. return !gameState().guardingCreatures(tile).empty();
  225. }
  226. bool CGameInfoCallback::getHeroInfo(const CGObjectInstance * hero, InfoAboutHero & dest, const CGObjectInstance * selectedObject) const
  227. {
  228. const auto * h = dynamic_cast<const CGHeroInstance *>(hero);
  229. ERROR_RET_VAL_IF(!h, "That's not a hero!", false);
  230. InfoAboutHero::EInfoLevel infoLevel = InfoAboutHero::EInfoLevel::BASIC;
  231. if(hasAccess(h->tempOwner))
  232. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  233. if (infoLevel == InfoAboutHero::EInfoLevel::BASIC)
  234. {
  235. auto ourBattle = gameState().getBattle(*getPlayerID());
  236. if(ourBattle && ourBattle->playerHasAccessToHeroInfo(*getPlayerID(), h)) //if it's battle we can get enemy hero full data
  237. infoLevel = InfoAboutHero::EInfoLevel::INBATTLE;
  238. else
  239. ERROR_RET_VAL_IF(!isVisible(h->visitablePos()), "That hero is not visible!", false);
  240. }
  241. if( (infoLevel == InfoAboutHero::EInfoLevel::BASIC) && nullptr != selectedObject)
  242. {
  243. const auto * selectedHero = dynamic_cast<const CGHeroInstance *>(selectedObject);
  244. if(nullptr != selectedHero)
  245. if(selectedHero->hasVisions(hero, BonusCustomSubtype::visionsHeroes))
  246. infoLevel = InfoAboutHero::EInfoLevel::DETAILED;
  247. }
  248. dest.initFromHero(h, infoLevel);
  249. //DISGUISED bonus implementation
  250. if(getPlayerRelations(*getPlayerID(), hero->tempOwner) == PlayerRelations::ENEMIES)
  251. {
  252. //todo: bonus cashing
  253. int disguiseLevel = h->valOfBonuses(BonusType::DISGUISED);
  254. auto doBasicDisguise = [](InfoAboutHero & info)
  255. {
  256. int maxAIValue = 0;
  257. const CCreature * mostStrong = nullptr;
  258. for(auto & elem : info.army)
  259. {
  260. if(static_cast<int>(elem.second.getCreature()->getAIValue()) > maxAIValue)
  261. {
  262. maxAIValue = elem.second.getCreature()->getAIValue();
  263. mostStrong = elem.second.getCreature();
  264. }
  265. }
  266. if(nullptr == mostStrong)//just in case
  267. logGlobal->error("CGameInfoCallback::getHeroInfo: Unable to select most strong stack");
  268. else
  269. for(auto & elem : info.army)
  270. {
  271. elem.second.setType(mostStrong);
  272. }
  273. };
  274. auto doAdvancedDisguise = [&doBasicDisguise](InfoAboutHero & info)
  275. {
  276. doBasicDisguise(info);
  277. for(auto & elem : info.army)
  278. elem.second.setCount(0);
  279. };
  280. auto doExpertDisguise = [this,h](InfoAboutHero & info)
  281. {
  282. for(auto & elem : info.army)
  283. elem.second.setCount(0);
  284. const auto factionIndex = getStartInfo()->playerInfos.at(h->tempOwner).castle;
  285. int maxAIValue = 0;
  286. const CCreature * mostStrong = nullptr;
  287. for(const auto & creature : LIBRARY->creh->objects)
  288. {
  289. if(creature->getFactionID() == factionIndex && static_cast<int>(creature->getAIValue()) > maxAIValue)
  290. {
  291. maxAIValue = creature->getAIValue();
  292. mostStrong = creature.get();
  293. }
  294. }
  295. if(nullptr != mostStrong) //possible, faction may have no creatures at all
  296. for(auto & elem : info.army)
  297. elem.second.setType(mostStrong);
  298. };
  299. switch (disguiseLevel)
  300. {
  301. case 0:
  302. //no bonus at all - do nothing
  303. break;
  304. case 1:
  305. doBasicDisguise(dest);
  306. break;
  307. case 2:
  308. doAdvancedDisguise(dest);
  309. break;
  310. case 3:
  311. doExpertDisguise(dest);
  312. break;
  313. default:
  314. //invalid value
  315. logGlobal->error("CGameInfoCallback::getHeroInfo: Invalid DISGUISED bonus value %d", disguiseLevel);
  316. break;
  317. }
  318. }
  319. return true;
  320. }
  321. int CGameInfoCallback::getDate(Date mode) const
  322. {
  323. return gameState().getDate(mode);
  324. }
  325. bool CGameInfoCallback::isVisibleFor(int3 pos, PlayerColor player) const
  326. {
  327. return gameState().isVisibleFor(pos, player);
  328. }
  329. bool CGameInfoCallback::isVisible(int3 pos) const
  330. {
  331. if (!getPlayerID().has_value())
  332. return true; // weird, but we do have such calls
  333. return gameState().isVisibleFor(pos, *getPlayerID());
  334. }
  335. bool CGameInfoCallback::isVisibleFor(const CGObjectInstance * obj, PlayerColor player) const
  336. {
  337. return gameState().isVisibleFor(obj, player);
  338. }
  339. bool CGameInfoCallback::isVisible(const CGObjectInstance *obj) const
  340. {
  341. if (!getPlayerID().has_value())
  342. return true; // weird, but we do have such calls
  343. return gameState().isVisibleFor(obj, *getPlayerID());
  344. }
  345. std::vector <const CGObjectInstance *> CGameInfoCallback::getBlockingObjs( int3 pos ) const
  346. {
  347. std::vector<const CGObjectInstance *> ret;
  348. const TerrainTile *t = getTile(pos);
  349. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  350. for(const auto & objID : t->blockingObjects)
  351. ret.push_back(getObj(objID));
  352. return ret;
  353. }
  354. std::vector <const CGObjectInstance *> CGameInfoCallback::getVisitableObjs(int3 pos, bool verbose) const
  355. {
  356. std::vector<const CGObjectInstance *> ret;
  357. const TerrainTile *t = getTile(pos, verbose);
  358. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!t, verbose, pos.toString() + " is not visible!", ret);
  359. for(const auto & objID : t->visitableObjects)
  360. {
  361. const auto & object = getObj(objID, false);
  362. if (!object)
  363. continue; // event - visitable, but not visible
  364. if(!getPlayerID().has_value() || object->ID != Obj::EVENT) //hide events from players
  365. ret.push_back(object);
  366. }
  367. return ret;
  368. }
  369. std::vector<const CGObjectInstance *> CGameInfoCallback::getAllVisitableObjs() const
  370. {
  371. std::vector<const CGObjectInstance *> ret;
  372. for(auto & obj : gameState().getMap().getObjects())
  373. if(obj->isVisitable() && obj->ID != Obj::EVENT && isVisible(obj))
  374. ret.push_back(obj);
  375. return ret;
  376. }
  377. const CGObjectInstance * CGameInfoCallback::getTopObj(int3 pos) const
  378. {
  379. return vstd::backOrNull(getVisitableObjs(pos));
  380. }
  381. std::vector <const CGObjectInstance *> CGameInfoCallback::getFlaggableObjects(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 auto & objectID : t->blockingObjects)
  387. {
  388. const auto * obj = getObj(objectID);
  389. if(obj->tempOwner != PlayerColor::UNFLAGGABLE)
  390. ret.push_back(obj);
  391. }
  392. return ret;
  393. }
  394. std::vector<const CGHeroInstance *> CGameInfoCallback::getAvailableHeroes(const CGObjectInstance * townOrTavern) const
  395. {
  396. ASSERT_IF_CALLED_WITH_PLAYER
  397. std::vector<const CGHeroInstance *> ret;
  398. //TODO: town needs to be owned, advmap tavern needs to be visited; to be reimplemented when visit tracking is done
  399. const CGTownInstance * town = getTown(townOrTavern->id);
  400. if(townOrTavern->ID == Obj::TAVERN || (town && town->hasBuilt(BuildingID::TAVERN)))
  401. return gameState().heroesPool->getHeroesFor(*getPlayerID());
  402. return ret;
  403. }
  404. const TerrainTile * CGameInfoCallback::getTile(int3 tile, bool verbose) const
  405. {
  406. if(isVisible(tile))
  407. return &gameState().getMap().getTile(tile);
  408. if(verbose)
  409. logGlobal->error("\r\n%s: %s\r\n", BOOST_CURRENT_FUNCTION, tile.toString() + " is not visible!");
  410. return nullptr;
  411. }
  412. const TerrainTile * CGameInfoCallback::getTileUnchecked(int3 tile) const
  413. {
  414. if (isInTheMap(tile))
  415. return &gameState().getMap().getTile(tile);
  416. return nullptr;
  417. }
  418. EDiggingStatus CGameInfoCallback::getTileDigStatus(int3 tile, bool verbose) const
  419. {
  420. if(!isVisible(tile))
  421. return EDiggingStatus::UNKNOWN;
  422. for(const auto & object : gameState().getMap().getObjects())
  423. {
  424. if(object->ID == Obj::HOLE && object->anchorPos() == tile)
  425. return EDiggingStatus::TILE_OCCUPIED;
  426. }
  427. return getTile(tile)->getDiggingStatus();
  428. }
  429. EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID ) const
  430. {
  431. ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", EBuildingState::TOWN_NOT_OWNED);
  432. if(!t->getTown()->buildings.count(ID))
  433. return EBuildingState::BUILDING_ERROR;
  434. const auto & building = t->getTown()->buildings.at(ID);
  435. if(t->hasBuilt(ID)) //already built
  436. return EBuildingState::ALREADY_PRESENT;
  437. //can we build it?
  438. if(vstd::contains(t->forbiddenBuildings, ID))
  439. return EBuildingState::FORBIDDEN; //forbidden
  440. auto possiblyNotBuiltTest = [&](const BuildingID & id) -> bool
  441. {
  442. return ((id == BuildingID::CAPITOL) ? true : !t->hasBuilt(id));
  443. };
  444. std::function<bool(BuildingID id)> allowedTest = [&](const BuildingID & id) -> bool
  445. {
  446. return !vstd::contains(t->forbiddenBuildings, id);
  447. };
  448. if (!t->genBuildingRequirements(ID, true).satisfiable(allowedTest, possiblyNotBuiltTest))
  449. return EBuildingState::FORBIDDEN;
  450. if(ID == BuildingID::CAPITOL)
  451. {
  452. const PlayerState *ps = getPlayerState(t->tempOwner, false);
  453. if(ps)
  454. {
  455. for(const CGTownInstance *town : ps->getTowns())
  456. {
  457. if(town->hasBuilt(BuildingID::CAPITOL))
  458. {
  459. return EBuildingState::HAVE_CAPITAL; //no more than one capitol
  460. }
  461. }
  462. }
  463. }
  464. else if(ID == BuildingID::SHIPYARD)
  465. {
  466. const TerrainTile *tile = getTile(t->bestLocation(), false);
  467. if(!tile || !tile->isWater())
  468. return EBuildingState::NO_WATER; //lack of water
  469. }
  470. auto buildTest = [&](const BuildingID & id) -> bool
  471. {
  472. return t->hasBuilt(id);
  473. };
  474. if (!t->genBuildingRequirements(ID).test(buildTest))
  475. return EBuildingState::PREREQUIRES;
  476. if(t->built >= getSettings().getInteger(EGameSettings::TOWNS_BUILDINGS_PER_TURN_CAP))
  477. return EBuildingState::CANT_BUILD_TODAY; //building limit
  478. //checking resources
  479. if(!building->resources.canBeAfforded(getPlayerState(t->tempOwner)->resources))
  480. return EBuildingState::NO_RESOURCES; //lack of res
  481. return EBuildingState::ALLOWED;
  482. }
  483. const CMap * CGameInfoCallback::getMapConstPtr() const
  484. {
  485. return &gameState().getMap();
  486. }
  487. bool CGameInfoCallback::hasAccess(std::optional<PlayerColor> playerId) const
  488. {
  489. return !getPlayerID() || getPlayerID()->isSpectator() || getPlayerRelations(*playerId, *getPlayerID()) != PlayerRelations::ENEMIES;
  490. }
  491. EPlayerStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const
  492. {
  493. const PlayerState *ps = gameState().getPlayerState(player, verbose);
  494. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!ps, verbose, "No such player!", EPlayerStatus::WRONG);
  495. return ps->status;
  496. }
  497. std::string CGameInfoCallback::getTavernRumor(const CGObjectInstance * townOrTavern) const
  498. {
  499. MetaString text;
  500. text.appendLocalString(EMetaText::GENERAL_TXT, 216);
  501. std::string extraText;
  502. if(gameState().currentRumor.type == RumorState::TYPE_NONE)
  503. return text.toString();
  504. auto rumor = gameState().currentRumor.last.at(gameState().currentRumor.type);
  505. switch(gameState().currentRumor.type)
  506. {
  507. case RumorState::TYPE_SPECIAL:
  508. text.replaceLocalString(EMetaText::GENERAL_TXT, rumor.first);
  509. if(rumor.first == RumorState::RUMOR_GRAIL)
  510. text.replaceTextID(TextIdentifier("core", "arraytxt", 158 + rumor.second).get());
  511. else
  512. text.replaceTextID(TextIdentifier("core", "plcolors", rumor.second).get());
  513. break;
  514. case RumorState::TYPE_MAP:
  515. text.replaceRawString(gameState().getMap().rumors[rumor.first].text.toString());
  516. break;
  517. case RumorState::TYPE_RAND:
  518. text.replaceTextID(TextIdentifier("core", "randtvrn", rumor.first).get());
  519. break;
  520. }
  521. return text.toString();
  522. }
  523. PlayerRelations CGameInfoCallback::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  524. {
  525. return gameState().getPlayerRelations(color1, color2);
  526. }
  527. bool CGameInfoCallback::canGetFullInfo(const CGObjectInstance *obj) const
  528. {
  529. return !obj || hasAccess(obj->tempOwner);
  530. }
  531. int CGameInfoCallback::getHeroCount( PlayerColor player, bool includeGarrisoned ) const
  532. {
  533. int ret = 0;
  534. const PlayerState *p = gameState().getPlayerState(player);
  535. ERROR_RET_VAL_IF(!p, "No such player!", -1);
  536. if(includeGarrisoned)
  537. return static_cast<int>(p->getHeroes().size());
  538. else
  539. for(const auto & elem : p->getHeroes())
  540. if(!elem->isGarrisoned())
  541. ret++;
  542. return ret;
  543. }
  544. std::vector<const CGHeroInstance*> CGameInfoCallback::getHeroes(PlayerColor player) const
  545. {
  546. std::vector<const CGHeroInstance*> ret;
  547. const PlayerState *p = gameState().getPlayerState(player);
  548. ERROR_RET_VAL_IF(!p, "No such player!", ret);
  549. for(const auto & hero : p->getHeroes())
  550. {
  551. if(!getPlayerID().has_value() || isVisibleFor(hero, *getPlayerID()) || hero->getOwner() == getPlayerID())
  552. ret.push_back(hero);
  553. }
  554. return ret;
  555. }
  556. bool CGameInfoCallback::isPlayerMakingTurn(PlayerColor player) const
  557. {
  558. return gameState().actingPlayers.count(player);
  559. }
  560. const TeamState * CGameInfoCallback::getTeam( TeamID teamID ) const
  561. {
  562. //rewritten by hand, AI calls this function a lot
  563. auto team = gameState().teams.find(teamID);
  564. if (team != gameState().teams.end())
  565. {
  566. const TeamState *ret = &team->second;
  567. if(!getPlayerID().has_value()) //neutral (or invalid) player
  568. return ret;
  569. else
  570. {
  571. if (vstd::contains(ret->players, *getPlayerID())) //specific player
  572. return ret;
  573. else
  574. {
  575. logGlobal->error("Illegal attempt to access team data!");
  576. return nullptr;
  577. }
  578. }
  579. }
  580. else
  581. {
  582. logGlobal->error("Cannot find info for team %d", teamID);
  583. return nullptr;
  584. }
  585. }
  586. const TeamState * CGameInfoCallback::getPlayerTeam( PlayerColor color ) const
  587. {
  588. auto player = gameState().players.find(color);
  589. if (player != gameState().players.end())
  590. {
  591. return getTeam (player->second.team);
  592. }
  593. else
  594. {
  595. return nullptr;
  596. }
  597. }
  598. void CGameInfoCallback::getVisibleTilesInRange(FowTilesType &tiles, int3 pos, int radious, int3::EDistanceFormula distanceFormula) const
  599. {
  600. gameState().getTilesInRange(tiles, pos, radious, ETileVisibility::REVEALED, *getPlayerID(), distanceFormula);
  601. }
  602. void CGameInfoCallback::calculatePaths(const std::shared_ptr<PathfinderConfig> & config) const
  603. {
  604. gameState().calculatePaths(config);
  605. }
  606. const CArtifactSet * CGameInfoCallback::getArtSet(const ArtifactLocation & loc) const
  607. {
  608. auto & gs = const_cast<CGameState&>(gameState());
  609. return gs.getArtSet(loc);
  610. }
  611. std::vector<ObjectInstanceID> CGameInfoCallback::getVisibleTeleportObjects(std::vector<ObjectInstanceID> ids, PlayerColor player) const
  612. {
  613. vstd::erase_if(ids, [&](const ObjectInstanceID & id) -> bool
  614. {
  615. const auto * obj = getObj(id, false);
  616. return player != PlayerColor::UNFLAGGABLE && (!obj || !isVisibleFor(obj->visitablePos(), player));
  617. });
  618. return ids;
  619. }
  620. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelEntrances(TeleportChannelID id, PlayerColor player) const
  621. {
  622. return getVisibleTeleportObjects(gameState().getMap().teleportChannels.at(id)->entrances, player);
  623. }
  624. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelExits(TeleportChannelID id, PlayerColor player) const
  625. {
  626. return getVisibleTeleportObjects(gameState().getMap().teleportChannels.at(id)->exits, player);
  627. }
  628. ETeleportChannelType CGameInfoCallback::getTeleportChannelType(TeleportChannelID id, PlayerColor player) const
  629. {
  630. std::vector<ObjectInstanceID> entrances = getTeleportChannelEntrances(id, player);
  631. std::vector<ObjectInstanceID> exits = getTeleportChannelExits(id, player);
  632. if((entrances.empty() || exits.empty()) // impassable if exits or entrances list are empty
  633. || (entrances.size() == 1 && entrances == exits)) // impassable if only entrance and only exit is same object. e.g bidirectional monolith
  634. {
  635. return ETeleportChannelType::IMPASSABLE;
  636. }
  637. auto intersection = vstd::intersection(entrances, exits);
  638. if(intersection.size() == entrances.size() && intersection.size() == exits.size())
  639. return ETeleportChannelType::BIDIRECTIONAL;
  640. else if(intersection.empty())
  641. return ETeleportChannelType::UNIDIRECTIONAL;
  642. else
  643. return ETeleportChannelType::MIXED;
  644. }
  645. bool CGameInfoCallback::isTeleportChannelImpassable(TeleportChannelID id, PlayerColor player) const
  646. {
  647. return ETeleportChannelType::IMPASSABLE == getTeleportChannelType(id, player);
  648. }
  649. bool CGameInfoCallback::isTeleportChannelBidirectional(TeleportChannelID id, PlayerColor player) const
  650. {
  651. return ETeleportChannelType::BIDIRECTIONAL == getTeleportChannelType(id, player);
  652. }
  653. bool CGameInfoCallback::isTeleportChannelUnidirectional(TeleportChannelID id, PlayerColor player) const
  654. {
  655. return ETeleportChannelType::UNIDIRECTIONAL == getTeleportChannelType(id, player);
  656. }
  657. bool CGameInfoCallback::isTeleportEntrancePassable(const CGTeleport * obj, PlayerColor player) const
  658. {
  659. return obj && obj->isEntrance() && !isTeleportChannelImpassable(obj->channel, player);
  660. }
  661. void CGameInfoCallback::getFreeTiles(std::vector<int3> & tiles, bool skipIfNearbyGuarded) const
  662. {
  663. std::vector<int> floors;
  664. floors.reserve(gameState().getMap().levels());
  665. for(int b = 0; b < gameState().getMap().levels(); ++b)
  666. {
  667. floors.push_back(b);
  668. }
  669. const TerrainTile * tinfo = nullptr;
  670. for (auto zd : floors)
  671. {
  672. for (int xd = 0; xd < gameState().getMap().width; xd++)
  673. {
  674. for (int yd = 0; yd < gameState().getMap().height; yd++)
  675. {
  676. tinfo = getTile(int3 (xd,yd,zd));
  677. if (tinfo->isLand() && tinfo->getTerrain()->isPassable() && !tinfo->blocked()) //land and free
  678. {
  679. // Ensure that CGameHandler::spawnWanderingMonsters won't set a random monster next to another monster
  680. // because Nullkiller AI is not able to go to one monster without falling into the attack range of the nearby one
  681. // See GraphPaths::addChainInfo if(node.linkDanger > 0) (no link between random monsters and map monsters)
  682. // Ivan: When new monster spawns, AI should receive AIGateway::newObject call for each object visible to AI. Probably you need to invalidate
  683. // that data for AI & force recalculation on next turn. New queries to gamestate, like getGuardingCreaturePosition that are done either
  684. // from AIGateway::newObject method or at any point later should correctly include newly spawned monsters
  685. // TODO: Ensure this linking issue is properly fixed, not just with the workaround below
  686. if (skipIfNearbyGuarded && guardingCreaturePosition(int3 (xd,yd,zd)).isValid())
  687. {
  688. continue;
  689. }
  690. tiles.emplace_back(xd, yd, zd);
  691. }
  692. }
  693. }
  694. }
  695. }
  696. void CGameInfoCallback::getTilesInRange(FowTilesType & tiles,
  697. const int3 & pos,
  698. int radious,
  699. ETileVisibility mode,
  700. std::optional<PlayerColor> player,
  701. int3::EDistanceFormula distanceFormula) const
  702. {
  703. if(player.has_value() && !player->isValidPlayer())
  704. {
  705. logGlobal->error("Illegal call to getTilesInRange!");
  706. return;
  707. }
  708. if(radious == GameConstants::FULL_MAP_RANGE)
  709. getAllTiles (tiles, player, -1, [](auto * tile){return true;});
  710. else
  711. {
  712. const TeamState * team = !player ? nullptr : gameState().getPlayerTeam(*player);
  713. for (int xd = std::max<int>(pos.x - radious , 0); xd <= std::min<int>(pos.x + radious, gameState().getMap().width - 1); xd++)
  714. {
  715. for (int yd = std::max<int>(pos.y - radious, 0); yd <= std::min<int>(pos.y + radious, gameState().getMap().height - 1); yd++)
  716. {
  717. int3 tilePos(xd,yd,pos.z);
  718. int distance = pos.dist(tilePos, distanceFormula);
  719. if(distance <= radious)
  720. {
  721. if(!player
  722. || (mode == ETileVisibility::HIDDEN && team->fogOfWarMap[pos.z][xd][yd] == 0)
  723. || (mode == ETileVisibility::REVEALED && team->fogOfWarMap[pos.z][xd][yd] == 1)
  724. )
  725. tiles.insert(int3(xd,yd,pos.z));
  726. }
  727. }
  728. }
  729. }
  730. }
  731. void CGameInfoCallback::getAllTiles(FowTilesType & tiles, std::optional<PlayerColor> Player, int level, const std::function<bool(const TerrainTile *)> & filter) const
  732. {
  733. if(Player.has_value() && !Player->isValidPlayer())
  734. {
  735. logGlobal->error("Illegal call to getAllTiles !");
  736. return;
  737. }
  738. std::vector<int> floors;
  739. if(level == -1)
  740. {
  741. for(int b = 0; b < gameState().getMap().levels(); ++b)
  742. {
  743. floors.push_back(b);
  744. }
  745. }
  746. else
  747. floors.push_back(level);
  748. for(auto zd: floors)
  749. {
  750. for(int xd = 0; xd < gameState().getMap().width; xd++)
  751. {
  752. for(int yd = 0; yd < gameState().getMap().height; yd++)
  753. {
  754. int3 coordinates(xd, yd, zd);
  755. if (filter(getTile(coordinates)))
  756. tiles.insert(coordinates);
  757. }
  758. }
  759. }
  760. }
  761. void CGameInfoCallback::getAllowedSpells(std::vector<SpellID> & out, std::optional<ui16> level) const
  762. {
  763. for (auto const & spellID : gameState().getMap().allowedSpells)
  764. {
  765. const auto * spell = spellID.toEntity(LIBRARY);
  766. if (!isAllowed(spellID))
  767. continue;
  768. if (level.has_value() && spell->getLevel() != level)
  769. continue;
  770. out.push_back(spellID);
  771. }
  772. }
  773. bool CGameInfoCallback::checkForVisitableDir(const int3 & src, const int3 & dst) const
  774. {
  775. const CMap & map = gameState().getMap();
  776. const TerrainTile * pom = &map.getTile(dst);
  777. return map.checkForVisitableDir(src, pom, dst);
  778. }
  779. #if SCRIPTING_ENABLED
  780. scripting::Pool * CGameInfoCallback::getGlobalContextPool() const
  781. {
  782. return nullptr; // TODO
  783. }
  784. #endif
  785. VCMI_LIB_NAMESPACE_END