CGameInfoCallback.cpp 29 KB

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