CGameInfoCallback.cpp 28 KB

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