CGameInfoCallback.cpp 28 KB

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