CGameInfoCallback.cpp 29 KB

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