2
0

CGameInfoCallback.cpp 29 KB

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