CGameInfoCallback.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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 = 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->error("Cannot get object with id %d", oid);
  112. return nullptr;
  113. }
  114. const CGObjectInstance *ret = gs->map->objects[oid];
  115. if(!ret)
  116. {
  117. if(verbose)
  118. logGlobal->error("Cannot get object with id %d. Object was removed", oid);
  119. return nullptr;
  120. }
  121. if(!isVisible(ret, player) && ret->tempOwner != player)
  122. {
  123. if(verbose)
  124. logGlobal->error("Cannot get object with id %d. Object is not visible.", oid);
  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) 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. int64_t 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);
  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 static_cast<int>(gs->players[Player].towns.size());
  205. }
  206. bool CGameInfoCallback::getTownInfo(const CGObjectInstance * town, InfoAboutTown & dest, const CGObjectInstance * selectedObject) 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) 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. if(getPlayerRelations(getLocalPlayer(), hero->tempOwner) == PlayerRelations::ENEMIES)
  265. {
  266. //todo: bonus cashing
  267. int disguiseLevel = h->valOfBonuses(Selector::typeSubtype(Bonus::DISGUISED, 0));
  268. auto doBasicDisguise = [](InfoAboutHero & info)
  269. {
  270. int maxAIValue = 0;
  271. const CCreature * mostStrong = nullptr;
  272. for(auto & elem : info.army)
  273. {
  274. if((int)elem.second.type->AIValue > maxAIValue)
  275. {
  276. maxAIValue = elem.second.type->AIValue;
  277. mostStrong = elem.second.type;
  278. }
  279. }
  280. if(nullptr == mostStrong)//just in case
  281. logGlobal->error("CGameInfoCallback::getHeroInfo: Unable to select most strong stack");
  282. else
  283. for(auto & elem : info.army)
  284. {
  285. elem.second.type = mostStrong;
  286. }
  287. };
  288. auto doAdvancedDisguise = [&doBasicDisguise](InfoAboutHero & info)
  289. {
  290. doBasicDisguise(info);
  291. for(auto & elem : info.army)
  292. elem.second.count = 0;
  293. };
  294. auto doExpertDisguise = [this,h](InfoAboutHero & info)
  295. {
  296. for(auto & elem : info.army)
  297. elem.second.count = 0;
  298. const auto factionIndex = getStartInfo(false)->playerInfos.at(h->tempOwner).castle;
  299. int maxAIValue = 0;
  300. const CCreature * mostStrong = nullptr;
  301. for(auto creature : VLC->creh->creatures)
  302. {
  303. if((si16)creature->faction == factionIndex && (int)creature->AIValue > maxAIValue)
  304. {
  305. maxAIValue = creature->AIValue;
  306. mostStrong = creature;
  307. }
  308. }
  309. if(nullptr != mostStrong) //possible, faction may have no creatures at all
  310. for(auto & elem : info.army)
  311. elem.second.type = mostStrong;
  312. };
  313. switch (disguiseLevel)
  314. {
  315. case 0:
  316. //no bonus at all - do nothing
  317. break;
  318. case 1:
  319. doBasicDisguise(dest);
  320. break;
  321. case 2:
  322. doAdvancedDisguise(dest);
  323. break;
  324. case 3:
  325. doExpertDisguise(dest);
  326. break;
  327. default:
  328. //invalid value
  329. logGlobal->error("CGameInfoCallback::getHeroInfo: Invalid DISGUISED bonus value %d", disguiseLevel);
  330. break;
  331. }
  332. }
  333. return true;
  334. }
  335. int CGameInfoCallback::getDate(Date::EDateType mode) const
  336. {
  337. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  338. return gs->getDate(mode);
  339. }
  340. bool CGameInfoCallback::isVisible(int3 pos, boost::optional<PlayerColor> Player) const
  341. {
  342. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  343. return gs->map->isInTheMap(pos) && (!Player || gs->isVisible(pos, *Player));
  344. }
  345. bool CGameInfoCallback::isVisible(int3 pos) const
  346. {
  347. return isVisible(pos, player);
  348. }
  349. bool CGameInfoCallback::isVisible( const CGObjectInstance *obj, boost::optional<PlayerColor> Player ) const
  350. {
  351. return gs->isVisible(obj, Player);
  352. }
  353. bool CGameInfoCallback::isVisible(const CGObjectInstance *obj) const
  354. {
  355. return isVisible(obj, player);
  356. }
  357. // const CCreatureSet* CInfoCallback::getGarrison(const CGObjectInstance *obj) const
  358. // {
  359. // //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  360. // if()
  361. // const CArmedInstance *armi = dynamic_cast<const CArmedInstance*>(obj);
  362. // if(!armi)
  363. // return nullptr;
  364. // else
  365. // return armi;
  366. // }
  367. std::vector < const CGObjectInstance * > CGameInfoCallback::getBlockingObjs( int3 pos ) const
  368. {
  369. std::vector<const CGObjectInstance *> ret;
  370. const TerrainTile *t = getTile(pos);
  371. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  372. for(const CGObjectInstance * obj : t->blockingObjects)
  373. ret.push_back(obj);
  374. return ret;
  375. }
  376. std::vector <const CGObjectInstance * > CGameInfoCallback::getVisitableObjs(int3 pos, bool verbose) const
  377. {
  378. std::vector<const CGObjectInstance *> ret;
  379. const TerrainTile *t = getTile(pos, verbose);
  380. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!t, verbose, pos.toString() + " is not visible!", ret);
  381. for(const CGObjectInstance * obj : t->visitableObjects)
  382. {
  383. if(player || obj->ID != Obj::EVENT) //hide events from players
  384. ret.push_back(obj);
  385. }
  386. return ret;
  387. }
  388. const CGObjectInstance * CGameInfoCallback::getTopObj (int3 pos) const
  389. {
  390. return vstd::backOrNull(getVisitableObjs(pos));
  391. }
  392. std::vector < const CGObjectInstance * > CGameInfoCallback::getFlaggableObjects(int3 pos) const
  393. {
  394. std::vector<const CGObjectInstance *> ret;
  395. const TerrainTile *t = getTile(pos);
  396. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  397. for(const CGObjectInstance *obj : t->blockingObjects)
  398. if(obj->tempOwner != PlayerColor::UNFLAGGABLE)
  399. ret.push_back(obj);
  400. return ret;
  401. }
  402. int3 CGameInfoCallback::getMapSize() const
  403. {
  404. return int3(gs->map->width, gs->map->height, gs->map->twoLevel ? 2 : 1);
  405. }
  406. std::vector<const CGHeroInstance *> CGameInfoCallback::getAvailableHeroes(const CGObjectInstance * townOrTavern) const
  407. {
  408. ASSERT_IF_CALLED_WITH_PLAYER
  409. std::vector<const CGHeroInstance *> ret;
  410. //ERROR_RET_VAL_IF(!isOwnedOrVisited(townOrTavern), "Town or tavern must be owned or visited!", ret);
  411. //TODO: town needs to be owned, advmap tavern needs to be visited; to be reimplemented when visit tracking is done
  412. const CGTownInstance * town = getTown(townOrTavern->id);
  413. if(townOrTavern->ID == Obj::TAVERN || (town && town->hasBuilt(BuildingID::TAVERN)))
  414. {
  415. range::copy(gs->players[*player].availableHeroes, std::back_inserter(ret));
  416. vstd::erase_if(ret, [](const CGHeroInstance * h) {
  417. return h == nullptr;
  418. });
  419. }
  420. return ret;
  421. }
  422. const TerrainTile * CGameInfoCallback::getTile( int3 tile, bool verbose) const
  423. {
  424. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!isVisible(tile), verbose, tile.toString() + " is not visible!", nullptr);
  425. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  426. return &gs->map->getTile(tile);
  427. }
  428. //TODO: typedef?
  429. std::shared_ptr<boost::multi_array<TerrainTile*, 3>> CGameInfoCallback::getAllVisibleTiles() const
  430. {
  431. assert(player.is_initialized());
  432. auto team = getPlayerTeam(player.get());
  433. size_t width = gs->map->width;
  434. size_t height = gs->map->height;
  435. size_t levels = (gs->map->twoLevel ? 2 : 1);
  436. boost::multi_array<TerrainTile*, 3> tileArray(boost::extents[width][height][levels]);
  437. for (size_t x = 0; x < width; x++)
  438. for (size_t y = 0; y < height; y++)
  439. for (size_t z = 0; z < levels; z++)
  440. {
  441. if (team->fogOfWarMap[x][y][z])
  442. tileArray[x][y][z] = &gs->map->getTile(int3((si32)x, (si32)y, (si32)z));
  443. else
  444. tileArray[x][y][z] = nullptr;
  445. }
  446. return std::make_shared<boost::multi_array<TerrainTile*, 3>>(tileArray);
  447. }
  448. EBuildingState::EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID )
  449. {
  450. ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", EBuildingState::TOWN_NOT_OWNED);
  451. if(!t->town->buildings.count(ID))
  452. return EBuildingState::BUILDING_ERROR;
  453. const CBuilding * building = t->town->buildings.at(ID);
  454. if(t->hasBuilt(ID)) //already built
  455. return EBuildingState::ALREADY_PRESENT;
  456. //can we build it?
  457. if(vstd::contains(t->forbiddenBuildings, ID))
  458. return EBuildingState::FORBIDDEN; //forbidden
  459. auto possiblyNotBuiltTest = [&](BuildingID id) -> bool
  460. {
  461. return ((id == BuildingID::CAPITOL) ? true : !t->hasBuilt(id));
  462. };
  463. std::function<bool(BuildingID id)> allowedTest = [&](BuildingID id) -> bool
  464. {
  465. return !vstd::contains(t->forbiddenBuildings, id);
  466. };
  467. if (!t->genBuildingRequirements(ID, true).satisfiable(allowedTest, possiblyNotBuiltTest))
  468. return EBuildingState::FORBIDDEN;
  469. if(ID == BuildingID::CAPITOL)
  470. {
  471. const PlayerState *ps = getPlayer(t->tempOwner, false);
  472. if(ps)
  473. {
  474. for(const CGTownInstance *town : ps->towns)
  475. {
  476. if(town->hasBuilt(BuildingID::CAPITOL))
  477. {
  478. return EBuildingState::HAVE_CAPITAL; //no more than one capitol
  479. }
  480. }
  481. }
  482. }
  483. else if(ID == BuildingID::SHIPYARD)
  484. {
  485. const TerrainTile *tile = getTile(t->bestLocation(), false);
  486. if(!tile || tile->terType != ETerrainType::WATER)
  487. return EBuildingState::NO_WATER; //lack of water
  488. }
  489. auto buildTest = [&](BuildingID id) -> bool
  490. {
  491. return t->hasBuilt(id);
  492. };
  493. if (!t->genBuildingRequirements(ID).test(buildTest))
  494. return EBuildingState::PREREQUIRES;
  495. if(t->builded >= VLC->modh->settings.MAX_BUILDING_PER_TURN)
  496. return EBuildingState::CANT_BUILD_TODAY; //building limit
  497. //checking resources
  498. if(!building->resources.canBeAfforded(getPlayer(t->tempOwner)->resources))
  499. return EBuildingState::NO_RESOURCES; //lack of res
  500. return EBuildingState::ALLOWED;
  501. }
  502. const CMapHeader * CGameInfoCallback::getMapHeader() const
  503. {
  504. return gs->map;
  505. }
  506. bool CGameInfoCallback::hasAccess(boost::optional<PlayerColor> playerId) const
  507. {
  508. return !player || player.get().isSpectator() || gs->getPlayerRelations( *playerId, *player ) != PlayerRelations::ENEMIES;
  509. }
  510. EPlayerStatus::EStatus CGameInfoCallback::getPlayerStatus(PlayerColor player, bool verbose) const
  511. {
  512. const PlayerState *ps = gs->getPlayer(player, verbose);
  513. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!ps, verbose, "No such player!", EPlayerStatus::WRONG);
  514. return ps->status;
  515. }
  516. std::string CGameInfoCallback::getTavernRumor(const CGObjectInstance * townOrTavern) const
  517. {
  518. std::string text = "", extraText = "";
  519. if(gs->rumor.type == RumorState::TYPE_NONE)
  520. return text;
  521. auto rumor = gs->rumor.last[gs->rumor.type];
  522. switch(gs->rumor.type)
  523. {
  524. case RumorState::TYPE_SPECIAL:
  525. if(rumor.first == RumorState::RUMOR_GRAIL)
  526. extraText = VLC->generaltexth->arraytxt[158 + rumor.second];
  527. else
  528. extraText = VLC->generaltexth->capColors[rumor.second];
  529. text = boost::str(boost::format(VLC->generaltexth->allTexts[rumor.first]) % extraText);
  530. break;
  531. case RumorState::TYPE_MAP:
  532. text = gs->map->rumors[rumor.first].text;
  533. break;
  534. case RumorState::TYPE_RAND:
  535. text = VLC->generaltexth->tavernRumors[rumor.first];
  536. break;
  537. }
  538. return text;
  539. }
  540. PlayerRelations::PlayerRelations CGameInfoCallback::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  541. {
  542. return gs->getPlayerRelations(color1, color2);
  543. }
  544. bool CGameInfoCallback::canGetFullInfo(const CGObjectInstance *obj) const
  545. {
  546. return !obj || hasAccess(obj->tempOwner);
  547. }
  548. int CGameInfoCallback::getHeroCount( PlayerColor player, bool includeGarrisoned ) const
  549. {
  550. int ret = 0;
  551. const PlayerState *p = gs->getPlayer(player);
  552. ERROR_RET_VAL_IF(!p, "No such player!", -1);
  553. if(includeGarrisoned)
  554. return static_cast<int>(p->heroes.size());
  555. else
  556. for(auto & elem : p->heroes)
  557. if(!elem->inTownGarrison)
  558. ret++;
  559. return ret;
  560. }
  561. bool CGameInfoCallback::isOwnedOrVisited(const CGObjectInstance *obj) const
  562. {
  563. if(canGetFullInfo(obj))
  564. return true;
  565. const TerrainTile *t = getTile(obj->visitablePos()); //get entrance tile
  566. const CGObjectInstance *visitor = t->visitableObjects.back(); //visitong hero if present or the obejct itself at last
  567. return visitor->ID == Obj::HERO && canGetFullInfo(visitor); //owned or allied hero is a visitor
  568. }
  569. PlayerColor CGameInfoCallback::getCurrentPlayer() const
  570. {
  571. return gs->currentPlayer;
  572. }
  573. CGameInfoCallback::CGameInfoCallback()
  574. {
  575. }
  576. CGameInfoCallback::CGameInfoCallback(CGameState *GS, boost::optional<PlayerColor> Player)
  577. {
  578. gs = GS;
  579. player = Player;
  580. }
  581. const std::vector< std::vector< std::vector<ui8> > > & CPlayerSpecificInfoCallback::getVisibilityMap() const
  582. {
  583. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  584. return gs->getPlayerTeam(*player)->fogOfWarMap;
  585. }
  586. int CPlayerSpecificInfoCallback::howManyTowns() const
  587. {
  588. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  589. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", -1);
  590. return CGameInfoCallback::howManyTowns(*player);
  591. }
  592. std::vector < const CGTownInstance *> CPlayerSpecificInfoCallback::getTownsInfo(bool onlyOur) const
  593. {
  594. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  595. std::vector < const CGTownInstance *> ret = std::vector < const CGTownInstance *>();
  596. for(const auto & i : gs->players)
  597. {
  598. for(const auto & town : i.second.towns)
  599. {
  600. if(i.first == player || (!onlyOur && isVisible(town, player)))
  601. {
  602. ret.push_back(town);
  603. }
  604. }
  605. } // for ( std::map<int, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  606. return ret;
  607. }
  608. std::vector < const CGHeroInstance *> CPlayerSpecificInfoCallback::getHeroesInfo(bool onlyOur) const
  609. {
  610. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  611. std::vector < const CGHeroInstance *> ret;
  612. for(auto hero : gs->map->heroesOnMap)
  613. {
  614. // !player || // - why would we even get access to hero not owned by any player?
  615. if((hero->tempOwner == *player) ||
  616. (isVisible(hero->getPosition(false), player) && !onlyOur) )
  617. {
  618. ret.push_back(hero);
  619. }
  620. }
  621. return ret;
  622. }
  623. boost::optional<PlayerColor> CPlayerSpecificInfoCallback::getMyColor() const
  624. {
  625. return player;
  626. }
  627. int CPlayerSpecificInfoCallback::getHeroSerial(const CGHeroInstance * hero, bool includeGarrisoned) const
  628. {
  629. if (hero->inTownGarrison && !includeGarrisoned)
  630. return -1;
  631. size_t index = 0;
  632. auto & heroes = gs->players[*player].heroes;
  633. for (auto & heroe : heroes)
  634. {
  635. if (includeGarrisoned || !(heroe)->inTownGarrison)
  636. index++;
  637. if (heroe == hero)
  638. return static_cast<int>(index);
  639. }
  640. return -1;
  641. }
  642. int3 CPlayerSpecificInfoCallback::getGrailPos( double *outKnownRatio )
  643. {
  644. if (!player || CGObelisk::obeliskCount == 0)
  645. {
  646. *outKnownRatio = 0.0;
  647. }
  648. else
  649. {
  650. TeamID t = gs->getPlayerTeam(*player)->id;
  651. double visited = 0.0;
  652. if(CGObelisk::visited.count(t))
  653. visited = static_cast<double>(CGObelisk::visited[t]);
  654. *outKnownRatio = visited / CGObelisk::obeliskCount;
  655. }
  656. return gs->map->grailPos;
  657. }
  658. std::vector < const CGObjectInstance * > CPlayerSpecificInfoCallback::getMyObjects() const
  659. {
  660. std::vector < const CGObjectInstance * > ret;
  661. for(const CGObjectInstance * obj : gs->map->objects)
  662. {
  663. if(obj && obj->tempOwner == player)
  664. ret.push_back(obj);
  665. }
  666. return ret;
  667. }
  668. std::vector < const CGDwelling * > CPlayerSpecificInfoCallback::getMyDwellings() const
  669. {
  670. ASSERT_IF_CALLED_WITH_PLAYER
  671. std::vector < const CGDwelling * > ret;
  672. for(CGDwelling * dw : gs->getPlayer(*player)->dwellings)
  673. {
  674. ret.push_back(dw);
  675. }
  676. return ret;
  677. }
  678. std::vector <QuestInfo> CPlayerSpecificInfoCallback::getMyQuests() const
  679. {
  680. std::vector <QuestInfo> ret;
  681. for (auto quest : gs->getPlayer(*player)->quests)
  682. {
  683. ret.push_back (quest);
  684. }
  685. return ret;
  686. }
  687. int CPlayerSpecificInfoCallback::howManyHeroes(bool includeGarrisoned) const
  688. {
  689. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  690. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", -1);
  691. return getHeroCount(*player,includeGarrisoned);
  692. }
  693. const CGHeroInstance* CPlayerSpecificInfoCallback::getHeroBySerial(int serialId, bool includeGarrisoned) const
  694. {
  695. ASSERT_IF_CALLED_WITH_PLAYER
  696. const PlayerState *p = getPlayer(*player);
  697. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  698. if (!includeGarrisoned)
  699. {
  700. for(ui32 i = 0; i < p->heroes.size() && (int)i<=serialId; i++)
  701. if(p->heroes[i]->inTownGarrison)
  702. serialId++;
  703. }
  704. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->heroes.size(), "No player info", nullptr);
  705. return p->heroes[serialId];
  706. }
  707. const CGTownInstance* CPlayerSpecificInfoCallback::getTownBySerial(int serialId) const
  708. {
  709. ASSERT_IF_CALLED_WITH_PLAYER
  710. const PlayerState *p = getPlayer(*player);
  711. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  712. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->towns.size(), "No player info", nullptr);
  713. return p->towns[serialId];
  714. }
  715. int CPlayerSpecificInfoCallback::getResourceAmount(Res::ERes type) const
  716. {
  717. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  718. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", -1);
  719. return getResource(*player, type);
  720. }
  721. TResources CPlayerSpecificInfoCallback::getResourceAmount() const
  722. {
  723. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  724. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", TResources());
  725. return gs->players[*player].resources;
  726. }
  727. const TeamState * CGameInfoCallback::getTeam( TeamID teamID ) const
  728. {
  729. //rewritten by hand, AI calls this function a lot
  730. auto team = gs->teams.find(teamID);
  731. if (team != gs->teams.end())
  732. {
  733. const TeamState *ret = &team->second;
  734. if (!player.is_initialized()) //neutral (or invalid) player
  735. return ret;
  736. else
  737. {
  738. if (vstd::contains(ret->players, *player)) //specific player
  739. return ret;
  740. else
  741. {
  742. logGlobal->error("Illegal attempt to access team data!");
  743. return nullptr;
  744. }
  745. }
  746. }
  747. else
  748. {
  749. logGlobal->error("Cannot find info for team %d", teamID);
  750. return nullptr;
  751. }
  752. }
  753. const TeamState * CGameInfoCallback::getPlayerTeam( PlayerColor color ) const
  754. {
  755. auto player = gs->players.find(color);
  756. if (player != gs->players.end())
  757. {
  758. return getTeam (player->second.team);
  759. }
  760. else
  761. {
  762. return nullptr;
  763. }
  764. }
  765. const CGHeroInstance* CGameInfoCallback::getHeroWithSubid( int subid ) const
  766. {
  767. for(const CGHeroInstance *h : gs->map->heroesOnMap)
  768. if(h->subID == subid)
  769. return h;
  770. return nullptr;
  771. }
  772. PlayerColor CGameInfoCallback::getLocalPlayer() const
  773. {
  774. return getCurrentPlayer();
  775. }
  776. bool CGameInfoCallback::isInTheMap(const int3 &pos) const
  777. {
  778. return gs->map->isInTheMap(pos);
  779. }
  780. void CGameInfoCallback::getVisibleTilesInRange(std::unordered_set<int3, ShashInt3> &tiles, int3 pos, int radious, int3::EDistanceFormula distanceFormula) const
  781. {
  782. gs->getTilesInRange(tiles, pos, radious, getLocalPlayer(), -1, distanceFormula);
  783. }
  784. void CGameInfoCallback::calculatePaths(std::shared_ptr<PathfinderConfig> config, const CGHeroInstance * hero)
  785. {
  786. gs->calculatePaths(config, hero);
  787. }
  788. const CArtifactInstance * CGameInfoCallback::getArtInstance( ArtifactInstanceID aid ) const
  789. {
  790. return gs->map->artInstances[aid.num];
  791. }
  792. const CGObjectInstance * CGameInfoCallback::getObjInstance( ObjectInstanceID oid ) const
  793. {
  794. return gs->map->objects[oid.num];
  795. }
  796. std::vector<ObjectInstanceID> CGameInfoCallback::getVisibleTeleportObjects(std::vector<ObjectInstanceID> ids, PlayerColor player) const
  797. {
  798. vstd::erase_if(ids, [&](ObjectInstanceID id) -> bool
  799. {
  800. auto obj = getObj(id, false);
  801. return player != PlayerColor::UNFLAGGABLE && (!obj || !isVisible(obj->pos, player));
  802. });
  803. return ids;
  804. }
  805. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelEntraces(TeleportChannelID id, PlayerColor player) const
  806. {
  807. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->entrances, player);
  808. }
  809. std::vector<ObjectInstanceID> CGameInfoCallback::getTeleportChannelExits(TeleportChannelID id, PlayerColor player) const
  810. {
  811. return getVisibleTeleportObjects(gs->map->teleportChannels[id]->exits, player);
  812. }
  813. ETeleportChannelType CGameInfoCallback::getTeleportChannelType(TeleportChannelID id, PlayerColor player) const
  814. {
  815. std::vector<ObjectInstanceID> entrances = getTeleportChannelEntraces(id, player);
  816. std::vector<ObjectInstanceID> exits = getTeleportChannelExits(id, player);
  817. if((!entrances.size() || !exits.size()) // impassable if exits or entrances list are empty
  818. || (entrances.size() == 1 && entrances == exits)) // impassable if only entrance and only exit is same object. e.g bidirectional monolith
  819. {
  820. return ETeleportChannelType::IMPASSABLE;
  821. }
  822. auto intersection = vstd::intersection(entrances, exits);
  823. if(intersection.size() == entrances.size() && intersection.size() == exits.size())
  824. return ETeleportChannelType::BIDIRECTIONAL;
  825. else if(!intersection.size())
  826. return ETeleportChannelType::UNIDIRECTIONAL;
  827. else
  828. return ETeleportChannelType::MIXED;
  829. }
  830. bool CGameInfoCallback::isTeleportChannelImpassable(TeleportChannelID id, PlayerColor player) const
  831. {
  832. return ETeleportChannelType::IMPASSABLE == getTeleportChannelType(id, player);
  833. }
  834. bool CGameInfoCallback::isTeleportChannelBidirectional(TeleportChannelID id, PlayerColor player) const
  835. {
  836. return ETeleportChannelType::BIDIRECTIONAL == getTeleportChannelType(id, player);
  837. }
  838. bool CGameInfoCallback::isTeleportChannelUnidirectional(TeleportChannelID id, PlayerColor player) const
  839. {
  840. return ETeleportChannelType::UNIDIRECTIONAL == getTeleportChannelType(id, player);
  841. }
  842. bool CGameInfoCallback::isTeleportEntrancePassable(const CGTeleport * obj, PlayerColor player) const
  843. {
  844. return obj && obj->isEntrance() && !isTeleportChannelImpassable(obj->channel, player);
  845. }
  846. void IGameEventRealizer::showInfoDialog( InfoWindow *iw )
  847. {
  848. commitPackage(iw);
  849. }
  850. void IGameEventRealizer::showInfoDialog(const std::string &msg, PlayerColor player)
  851. {
  852. InfoWindow iw;
  853. iw.player = player;
  854. iw.text << msg;
  855. showInfoDialog(&iw);
  856. }
  857. void IGameEventRealizer::setObjProperty(ObjectInstanceID objid, int prop, si64 val)
  858. {
  859. SetObjectProperty sob;
  860. sob.id = objid;
  861. sob.what = prop;
  862. sob.val = static_cast<ui32>(val);
  863. commitPackage(&sob);
  864. }