CGameInfoCallback.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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<const 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->levels();
  442. auto ptr = new boost::multi_array<TerrainTile*, 3>(boost::extents[levels][width][height]);
  443. int3 tile;
  444. for(tile.z = 0; tile.z < levels; tile.z++)
  445. for(tile.x = 0; tile.x < width; tile.x++)
  446. for(tile.y = 0; tile.y < height; tile.y++)
  447. {
  448. if ((*team->fogOfWarMap)[tile.z][tile.x][tile.y])
  449. (*ptr)[tile.z][tile.x][tile.y] = &gs->map->getTile(tile);
  450. else
  451. (*ptr)[tile.z][tile.x][tile.y] = nullptr;
  452. }
  453. return std::shared_ptr<const boost::multi_array<TerrainTile*, 3>>(ptr);
  454. }
  455. EBuildingState::EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID )
  456. {
  457. ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", EBuildingState::TOWN_NOT_OWNED);
  458. if(!t->town->buildings.count(ID))
  459. return EBuildingState::BUILDING_ERROR;
  460. const CBuilding * building = t->town->buildings.at(ID);
  461. if(t->hasBuilt(ID)) //already built
  462. return EBuildingState::ALREADY_PRESENT;
  463. //can we build it?
  464. if(vstd::contains(t->forbiddenBuildings, ID))
  465. return EBuildingState::FORBIDDEN; //forbidden
  466. auto possiblyNotBuiltTest = [&](BuildingID id) -> bool
  467. {
  468. return ((id == BuildingID::CAPITOL) ? true : !t->hasBuilt(id));
  469. };
  470. std::function<bool(BuildingID id)> allowedTest = [&](BuildingID id) -> bool
  471. {
  472. return !vstd::contains(t->forbiddenBuildings, id);
  473. };
  474. if (!t->genBuildingRequirements(ID, true).satisfiable(allowedTest, possiblyNotBuiltTest))
  475. return EBuildingState::FORBIDDEN;
  476. if(ID == BuildingID::CAPITOL)
  477. {
  478. const PlayerState *ps = getPlayerState(t->tempOwner, false);
  479. if(ps)
  480. {
  481. for(const CGTownInstance *town : ps->towns)
  482. {
  483. if(town->hasBuilt(BuildingID::CAPITOL))
  484. {
  485. return EBuildingState::HAVE_CAPITAL; //no more than one capitol
  486. }
  487. }
  488. }
  489. }
  490. else if(ID == BuildingID::SHIPYARD)
  491. {
  492. const TerrainTile *tile = getTile(t->bestLocation(), false);
  493. if(!tile || tile->terType.isLand())
  494. return EBuildingState::NO_WATER; //lack of water
  495. }
  496. auto buildTest = [&](BuildingID id) -> bool
  497. {
  498. return t->hasBuilt(id);
  499. };
  500. if (!t->genBuildingRequirements(ID).test(buildTest))
  501. return EBuildingState::PREREQUIRES;
  502. if(t->builded >= VLC->modh->settings.MAX_BUILDING_PER_TURN)
  503. return EBuildingState::CANT_BUILD_TODAY; //building limit
  504. //checking resources
  505. if(!building->resources.canBeAfforded(getPlayerState(t->tempOwner)->resources))
  506. return EBuildingState::NO_RESOURCES; //lack of res
  507. return EBuildingState::ALLOWED;
  508. }
  509. const CMapHeader * CGameInfoCallback::getMapHeader() const
  510. {
  511. return gs->map;
  512. }
  513. bool CGameInfoCallback::hasAccess(boost::optional<PlayerColor> playerId) const
  514. {
  515. return !player || player.get().isSpectator() || gs->getPlayerRelations( *playerId, *player ) != PlayerRelations::ENEMIES;
  516. }
  517. EPlayerStatus::EStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const
  518. {
  519. const PlayerState *ps = gs->getPlayerState(player, verbose);
  520. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!ps, verbose, "No such player!", EPlayerStatus::WRONG);
  521. return ps->status;
  522. }
  523. std::string CGameInfoCallback::getTavernRumor(const CGObjectInstance * townOrTavern) const
  524. {
  525. std::string text = "", extraText = "";
  526. if(gs->rumor.type == RumorState::TYPE_NONE)
  527. return text;
  528. auto rumor = gs->rumor.last[gs->rumor.type];
  529. switch(gs->rumor.type)
  530. {
  531. case RumorState::TYPE_SPECIAL:
  532. if(rumor.first == RumorState::RUMOR_GRAIL)
  533. extraText = VLC->generaltexth->arraytxt[158 + rumor.second];
  534. else
  535. extraText = VLC->generaltexth->capColors[rumor.second];
  536. text = boost::str(boost::format(VLC->generaltexth->allTexts[rumor.first]) % extraText);
  537. break;
  538. case RumorState::TYPE_MAP:
  539. text = gs->map->rumors[rumor.first].text;
  540. break;
  541. case RumorState::TYPE_RAND:
  542. text = VLC->generaltexth->tavernRumors[rumor.first];
  543. break;
  544. }
  545. return text;
  546. }
  547. PlayerRelations::PlayerRelations CGameInfoCallback::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  548. {
  549. return gs->getPlayerRelations(color1, color2);
  550. }
  551. bool CGameInfoCallback::canGetFullInfo(const CGObjectInstance *obj) const
  552. {
  553. return !obj || hasAccess(obj->tempOwner);
  554. }
  555. int CGameInfoCallback::getHeroCount( PlayerColor player, bool includeGarrisoned ) const
  556. {
  557. int ret = 0;
  558. const PlayerState *p = gs->getPlayerState(player);
  559. ERROR_RET_VAL_IF(!p, "No such player!", -1);
  560. if(includeGarrisoned)
  561. return static_cast<int>(p->heroes.size());
  562. else
  563. for(auto & elem : p->heroes)
  564. if(!elem->inTownGarrison)
  565. ret++;
  566. return ret;
  567. }
  568. bool CGameInfoCallback::isOwnedOrVisited(const CGObjectInstance *obj) const
  569. {
  570. if(canGetFullInfo(obj))
  571. return true;
  572. const TerrainTile *t = getTile(obj->visitablePos()); //get entrance tile
  573. const CGObjectInstance *visitor = t->visitableObjects.back(); //visitong hero if present or the obejct itself at last
  574. return visitor->ID == Obj::HERO && canGetFullInfo(visitor); //owned or allied hero is a visitor
  575. }
  576. PlayerColor CGameInfoCallback::getCurrentPlayer() const
  577. {
  578. return gs->currentPlayer;
  579. }
  580. CGameInfoCallback::CGameInfoCallback()
  581. {
  582. }
  583. CGameInfoCallback::CGameInfoCallback(CGameState *GS, boost::optional<PlayerColor> Player)
  584. {
  585. gs = GS;
  586. player = Player;
  587. }
  588. std::shared_ptr<const boost::multi_array<ui8, 3>> CPlayerSpecificInfoCallback::getVisibilityMap() const
  589. {
  590. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  591. return gs->getPlayerTeam(*player)->fogOfWarMap;
  592. }
  593. int CPlayerSpecificInfoCallback::howManyTowns() const
  594. {
  595. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  596. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", -1);
  597. return CGameInfoCallback::howManyTowns(*player);
  598. }
  599. std::vector < const CGTownInstance *> CPlayerSpecificInfoCallback::getTownsInfo(bool onlyOur) const
  600. {
  601. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  602. std::vector < const CGTownInstance *> ret = std::vector < const CGTownInstance *>();
  603. for(const auto & i : gs->players)
  604. {
  605. for(const auto & town : i.second.towns)
  606. {
  607. if(i.first == player || (!onlyOur && isVisible(town, player)))
  608. {
  609. ret.push_back(town);
  610. }
  611. }
  612. } // for ( std::map<int, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  613. return ret;
  614. }
  615. std::vector < const CGHeroInstance *> CPlayerSpecificInfoCallback::getHeroesInfo(bool onlyOur) const
  616. {
  617. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  618. std::vector < const CGHeroInstance *> ret;
  619. for(auto hero : gs->map->heroesOnMap)
  620. {
  621. // !player || // - why would we even get access to hero not owned by any player?
  622. if((hero->tempOwner == *player) ||
  623. (isVisible(hero->getPosition(false), player) && !onlyOur) )
  624. {
  625. ret.push_back(hero);
  626. }
  627. }
  628. return ret;
  629. }
  630. boost::optional<PlayerColor> CPlayerSpecificInfoCallback::getMyColor() const
  631. {
  632. return player;
  633. }
  634. int CPlayerSpecificInfoCallback::getHeroSerial(const CGHeroInstance * hero, bool includeGarrisoned) const
  635. {
  636. if (hero->inTownGarrison && !includeGarrisoned)
  637. return -1;
  638. size_t index = 0;
  639. auto & heroes = gs->players[*player].heroes;
  640. for (auto & heroe : heroes)
  641. {
  642. if (includeGarrisoned || !(heroe)->inTownGarrison)
  643. index++;
  644. if (heroe == hero)
  645. return static_cast<int>(index);
  646. }
  647. return -1;
  648. }
  649. int3 CPlayerSpecificInfoCallback::getGrailPos( double *outKnownRatio )
  650. {
  651. if (!player || CGObelisk::obeliskCount == 0)
  652. {
  653. *outKnownRatio = 0.0;
  654. }
  655. else
  656. {
  657. TeamID t = gs->getPlayerTeam(*player)->id;
  658. double visited = 0.0;
  659. if(CGObelisk::visited.count(t))
  660. visited = static_cast<double>(CGObelisk::visited[t]);
  661. *outKnownRatio = visited / CGObelisk::obeliskCount;
  662. }
  663. return gs->map->grailPos;
  664. }
  665. std::vector < const CGObjectInstance * > CPlayerSpecificInfoCallback::getMyObjects() const
  666. {
  667. std::vector < const CGObjectInstance * > ret;
  668. for(const CGObjectInstance * obj : gs->map->objects)
  669. {
  670. if(obj && obj->tempOwner == player)
  671. ret.push_back(obj);
  672. }
  673. return ret;
  674. }
  675. std::vector < const CGDwelling * > CPlayerSpecificInfoCallback::getMyDwellings() const
  676. {
  677. ASSERT_IF_CALLED_WITH_PLAYER
  678. std::vector < const CGDwelling * > ret;
  679. for(CGDwelling * dw : gs->getPlayerState(*player)->dwellings)
  680. {
  681. ret.push_back(dw);
  682. }
  683. return ret;
  684. }
  685. std::vector <QuestInfo> CPlayerSpecificInfoCallback::getMyQuests() const
  686. {
  687. std::vector <QuestInfo> ret;
  688. for (auto quest : gs->getPlayerState(*player)->quests)
  689. {
  690. ret.push_back (quest);
  691. }
  692. return ret;
  693. }
  694. int CPlayerSpecificInfoCallback::howManyHeroes(bool includeGarrisoned) const
  695. {
  696. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  697. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", -1);
  698. return getHeroCount(*player,includeGarrisoned);
  699. }
  700. const CGHeroInstance* CPlayerSpecificInfoCallback::getHeroBySerial(int serialId, bool includeGarrisoned) const
  701. {
  702. ASSERT_IF_CALLED_WITH_PLAYER
  703. const PlayerState *p = getPlayerState(*player);
  704. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  705. if (!includeGarrisoned)
  706. {
  707. for(ui32 i = 0; i < p->heroes.size() && (int)i<=serialId; i++)
  708. if(p->heroes[i]->inTownGarrison)
  709. serialId++;
  710. }
  711. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->heroes.size(), "No player info", nullptr);
  712. return p->heroes[serialId];
  713. }
  714. const CGTownInstance* CPlayerSpecificInfoCallback::getTownBySerial(int serialId) const
  715. {
  716. ASSERT_IF_CALLED_WITH_PLAYER
  717. const PlayerState *p = getPlayerState(*player);
  718. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  719. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->towns.size(), "No player info", nullptr);
  720. return p->towns[serialId];
  721. }
  722. int CPlayerSpecificInfoCallback::getResourceAmount(Res::ERes type) const
  723. {
  724. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  725. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", -1);
  726. return getResource(*player, type);
  727. }
  728. TResources CPlayerSpecificInfoCallback::getResourceAmount() const
  729. {
  730. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  731. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", TResources());
  732. return gs->players[*player].resources;
  733. }
  734. const TeamState * CGameInfoCallback::getTeam( TeamID teamID ) const
  735. {
  736. //rewritten by hand, AI calls this function a lot
  737. auto team = gs->teams.find(teamID);
  738. if (team != gs->teams.end())
  739. {
  740. const TeamState *ret = &team->second;
  741. if (!player.is_initialized()) //neutral (or invalid) player
  742. return ret;
  743. else
  744. {
  745. if (vstd::contains(ret->players, *player)) //specific player
  746. return ret;
  747. else
  748. {
  749. logGlobal->error("Illegal attempt to access team data!");
  750. return nullptr;
  751. }
  752. }
  753. }
  754. else
  755. {
  756. logGlobal->error("Cannot find info for team %d", teamID);
  757. return nullptr;
  758. }
  759. }
  760. const TeamState * CGameInfoCallback::getPlayerTeam( PlayerColor color ) const
  761. {
  762. auto player = gs->players.find(color);
  763. if (player != gs->players.end())
  764. {
  765. return getTeam (player->second.team);
  766. }
  767. else
  768. {
  769. return nullptr;
  770. }
  771. }
  772. const CGHeroInstance * CGameInfoCallback::getHeroWithSubid( int subid ) const
  773. {
  774. if(subid<0)
  775. return nullptr;
  776. if(subid>= gs->map->allHeroes.size())
  777. return nullptr;
  778. return gs->map->allHeroes.at(subid).get();
  779. }
  780. PlayerColor CGameInfoCallback::getLocalPlayer() const
  781. {
  782. return getCurrentPlayer();
  783. }
  784. bool CGameInfoCallback::isInTheMap(const int3 &pos) const
  785. {
  786. return gs->map->isInTheMap(pos);
  787. }
  788. void CGameInfoCallback::getVisibleTilesInRange(std::unordered_set<int3, ShashInt3> &tiles, int3 pos, int radious, int3::EDistanceFormula distanceFormula) const
  789. {
  790. gs->getTilesInRange(tiles, pos, radious, getLocalPlayer(), -1, distanceFormula);
  791. }
  792. void CGameInfoCallback::calculatePaths(std::shared_ptr<PathfinderConfig> config)
  793. {
  794. gs->calculatePaths(config);
  795. }
  796. const CArtifactInstance * CGameInfoCallback::getArtInstance( ArtifactInstanceID aid ) const
  797. {
  798. return gs->map->artInstances[aid.num];
  799. }
  800. const CGObjectInstance * CGameInfoCallback::getObjInstance( ObjectInstanceID oid ) const
  801. {
  802. return gs->map->objects[oid.num];
  803. }
  804. std::vector<ObjectInstanceID> CGameInfoCallback::getVisibleTeleportObjects(std::vector<ObjectInstanceID> ids, PlayerColor player) const
  805. {
  806. vstd::erase_if(ids, [&](ObjectInstanceID id) -> bool
  807. {
  808. auto obj = getObj(id, false);
  809. return player != PlayerColor::UNFLAGGABLE && (!obj || !isVisible(obj->pos, player));
  810. });
  811. return ids;
  812. }
  813. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelEntraces(TeleportChannelID id, PlayerColor player) const
  814. {
  815. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->entrances, player);
  816. }
  817. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelExits(TeleportChannelID id, PlayerColor player) const
  818. {
  819. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->exits, player);
  820. }
  821. ETeleportChannelType CGameInfoCallback::getTeleportChannelType(TeleportChannelID id, PlayerColor player) const
  822. {
  823. std::vector<ObjectInstanceID> entrances = getTeleportChannelEntraces(id, player);
  824. std::vector<ObjectInstanceID> exits = getTeleportChannelExits(id, player);
  825. if((!entrances.size() || !exits.size()) // impassable if exits or entrances list are empty
  826. || (entrances.size() == 1 && entrances == exits)) // impassable if only entrance and only exit is same object. e.g bidirectional monolith
  827. {
  828. return ETeleportChannelType::IMPASSABLE;
  829. }
  830. auto intersection = vstd::intersection(entrances, exits);
  831. if(intersection.size() == entrances.size() && intersection.size() == exits.size())
  832. return ETeleportChannelType::BIDIRECTIONAL;
  833. else if(!intersection.size())
  834. return ETeleportChannelType::UNIDIRECTIONAL;
  835. else
  836. return ETeleportChannelType::MIXED;
  837. }
  838. bool CGameInfoCallback::isTeleportChannelImpassable(TeleportChannelID id, PlayerColor player) const
  839. {
  840. return ETeleportChannelType::IMPASSABLE == getTeleportChannelType(id, player);
  841. }
  842. bool CGameInfoCallback::isTeleportChannelBidirectional(TeleportChannelID id, PlayerColor player) const
  843. {
  844. return ETeleportChannelType::BIDIRECTIONAL == getTeleportChannelType(id, player);
  845. }
  846. bool CGameInfoCallback::isTeleportChannelUnidirectional(TeleportChannelID id, PlayerColor player) const
  847. {
  848. return ETeleportChannelType::UNIDIRECTIONAL == getTeleportChannelType(id, player);
  849. }
  850. bool CGameInfoCallback::isTeleportEntrancePassable(const CGTeleport * obj, PlayerColor player) const
  851. {
  852. return obj && obj->isEntrance() && !isTeleportChannelImpassable(obj->channel, player);
  853. }