CGameInfoCallback.cpp 29 KB

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