CGameInfoCallback.cpp 29 KB

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