CGameInfoCallback.cpp 29 KB

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