CGameInfoCallback.cpp 29 KB

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