IGameCallback.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. #include "StdInc.h"
  2. #include "IGameCallback.h"
  3. #include "CGameState.h"
  4. #include "mapping/CMap.h"
  5. #include "CObjectHandler.h"
  6. #include "CHeroHandler.h"
  7. #include "StartInfo.h"
  8. #include "CArtHandler.h"
  9. #include "CSpellHandler.h"
  10. #include "VCMI_Lib.h"
  11. #include "CTownHandler.h"
  12. #include "BattleState.h"
  13. #include "NetPacks.h"
  14. #include "CBuildingHandler.h"
  15. #include "GameConstants.h"
  16. #include "CModHandler.h"
  17. #include "CDefObjInfoHandler.h"
  18. #include "CBonusTypeHandler.h"
  19. #include "Connection.h"
  20. /*
  21. * IGameCallback.cpp, part of VCMI engine
  22. *
  23. * Authors: listed in file AUTHORS in main folder
  24. *
  25. * License: GNU General Public License v2.0 or later
  26. * Full text of license available in license.txt file, in main folder
  27. *
  28. */
  29. //TODO make clean
  30. #define ERROR_SILENT_RET_VAL_IF(cond, txt, retVal) do {if(cond){return retVal;}} while(0)
  31. #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)
  32. #define ERROR_RET_IF(cond, txt) do {if(cond){logGlobal->errorStream() << BOOST_CURRENT_FUNCTION << ": " << txt; return;}} while(0)
  33. #define ERROR_RET_VAL_IF(cond, txt, retVal) do {if(cond){logGlobal->errorStream() << BOOST_CURRENT_FUNCTION << ": " << txt; return retVal;}} while(0)
  34. extern std::minstd_rand ran;
  35. CGameState * CPrivilagedInfoCallback::gameState ()
  36. {
  37. return gs;
  38. }
  39. PlayerColor CGameInfoCallback::getOwner(ObjectInstanceID heroID) const
  40. {
  41. const CGObjectInstance *obj = getObj(heroID);
  42. ERROR_RET_VAL_IF(!obj, "No such object!", PlayerColor::CANNOT_DETERMINE);
  43. return obj->tempOwner;
  44. }
  45. int CGameInfoCallback::getResource(PlayerColor Player, Res::ERes which) const
  46. {
  47. const PlayerState *p = getPlayer(Player);
  48. ERROR_RET_VAL_IF(!p, "No player info!", -1);
  49. ERROR_RET_VAL_IF(p->resources.size() <= which || which < 0, "No such resource!", -1);
  50. return p->resources[which];
  51. }
  52. const CGHeroInstance* CGameInfoCallback::getSelectedHero( PlayerColor Player ) const
  53. {
  54. const PlayerState *p = getPlayer(Player);
  55. ERROR_RET_VAL_IF(!p, "No player info!", nullptr);
  56. return getHero(p->currentSelection);
  57. }
  58. const CGHeroInstance* CGameInfoCallback::getSelectedHero() const
  59. {
  60. return getSelectedHero(gs->currentPlayer);
  61. }
  62. const PlayerSettings * CGameInfoCallback::getPlayerSettings(PlayerColor color) const
  63. {
  64. return &gs->scenarioOps->getIthPlayersSettings(color);
  65. }
  66. void CPrivilagedInfoCallback::getTilesInRange( std::unordered_set<int3, ShashInt3> &tiles, int3 pos, int radious, boost::optional<PlayerColor> player/*=uninit*/, int mode/*=0*/ ) const
  67. {
  68. if(!!player && *player >= PlayerColor::PLAYER_LIMIT)
  69. {
  70. logGlobal->errorStream() << "Illegal call to getTilesInRange!";
  71. return;
  72. }
  73. if (radious == -1) //reveal entire map
  74. getAllTiles (tiles, player, -1, 0);
  75. else
  76. {
  77. const TeamState * team = !player ? nullptr : gs->getPlayerTeam(*player);
  78. for (int xd = std::max<int>(pos.x - radious , 0); xd <= std::min<int>(pos.x + radious, gs->map->width - 1); xd++)
  79. {
  80. for (int yd = std::max<int>(pos.y - radious, 0); yd <= std::min<int>(pos.y + radious, gs->map->height - 1); yd++)
  81. {
  82. double distance = pos.dist2d(int3(xd,yd,pos.z)) - 0.5;
  83. if(distance <= radious)
  84. {
  85. if(!player
  86. || (mode == 1 && team->fogOfWarMap[xd][yd][pos.z]==0)
  87. || (mode == -1 && team->fogOfWarMap[xd][yd][pos.z]==1)
  88. )
  89. tiles.insert(int3(xd,yd,pos.z));
  90. }
  91. }
  92. }
  93. }
  94. }
  95. void CPrivilagedInfoCallback::getAllTiles (std::unordered_set<int3, ShashInt3> &tiles, boost::optional<PlayerColor> Player/*=uninit*/, int level, int surface ) const
  96. {
  97. if(!!Player && *Player >= PlayerColor::PLAYER_LIMIT)
  98. {
  99. logGlobal->errorStream() << "Illegal call to getAllTiles !";
  100. return;
  101. }
  102. bool water = surface == 0 || surface == 2,
  103. land = surface == 0 || surface == 1;
  104. std::vector<int> floors;
  105. if(level == -1)
  106. {
  107. for(int b = 0; b < (gs->map->twoLevel ? 2 : 1); ++b)
  108. {
  109. floors.push_back(b);
  110. }
  111. }
  112. else
  113. floors.push_back(level);
  114. for (auto zd : floors)
  115. {
  116. for (int xd = 0; xd < gs->map->width; xd++)
  117. {
  118. for (int yd = 0; yd < gs->map->height; yd++)
  119. {
  120. if ((getTile (int3 (xd,yd,zd))->terType == ETerrainType::WATER && water)
  121. || (getTile (int3 (xd,yd,zd))->terType != ETerrainType::WATER && land))
  122. tiles.insert(int3(xd,yd,zd));
  123. }
  124. }
  125. }
  126. }
  127. void CPrivilagedInfoCallback::getFreeTiles (std::vector<int3> &tiles) const
  128. {
  129. std::vector<int> floors;
  130. for (int b = 0; b < (gs->map->twoLevel ? 2 : 1); ++b)
  131. {
  132. floors.push_back(b);
  133. }
  134. const TerrainTile *tinfo;
  135. for (auto zd : floors)
  136. {
  137. for (int xd = 0; xd < gs->map->width; xd++)
  138. {
  139. for (int yd = 0; yd < gs->map->height; yd++)
  140. {
  141. tinfo = getTile(int3 (xd,yd,zd));
  142. if (tinfo->terType != ETerrainType::WATER && !tinfo->blocked) //land and free
  143. tiles.push_back (int3 (xd,yd,zd));
  144. }
  145. }
  146. }
  147. }
  148. bool CGameInfoCallback::isAllowed( int type, int id )
  149. {
  150. switch(type)
  151. {
  152. case 0:
  153. return gs->map->allowedSpell[id];
  154. case 1:
  155. return gs->map->allowedArtifact[id];
  156. case 2:
  157. return gs->map->allowedAbilities[id];
  158. default:
  159. ERROR_RET_VAL_IF(1, "Wrong type!", false);
  160. }
  161. }
  162. void CPrivilagedInfoCallback::pickAllowedArtsSet(std::vector<const CArtifact*> &out)
  163. {
  164. for (int j = 0; j < 3 ; j++)
  165. out.push_back(VLC->arth->artifacts[getRandomArt(CArtifact::ART_TREASURE)]);
  166. for (int j = 0; j < 3 ; j++)
  167. out.push_back(VLC->arth->artifacts[getRandomArt(CArtifact::ART_MINOR)]);
  168. out.push_back(VLC->arth->artifacts[getRandomArt(CArtifact::ART_MAJOR)]);
  169. }
  170. ArtifactID CPrivilagedInfoCallback::getRandomArt (int flags)
  171. {
  172. return VLC->arth->getRandomArt(flags);
  173. }
  174. ArtifactID CPrivilagedInfoCallback::getArtSync (ui32 rand, int flags, bool erasePicked)
  175. {
  176. return VLC->arth->getArtSync (rand, flags, erasePicked);
  177. }
  178. void CPrivilagedInfoCallback::getAllowedSpells(std::vector<SpellID> &out, ui16 level)
  179. {
  180. for (ui32 i = 0; i < gs->map->allowedSpell.size(); i++) //spellh size appears to be greater (?)
  181. {
  182. const CSpell *spell = SpellID(i).toSpell();
  183. if (isAllowed (0, spell->id) && spell->level == level)
  184. {
  185. out.push_back(spell->id);
  186. }
  187. }
  188. }
  189. template<typename Loader>
  190. void CPrivilagedInfoCallback::loadCommonState(Loader &in)
  191. {
  192. logGlobal->infoStream() << "Loading lib part of game...";
  193. in.checkMagicBytes(SAVEGAME_MAGIC);
  194. CMapHeader dum;
  195. StartInfo *si;
  196. logGlobal->infoStream() <<"\tReading header";
  197. in >> dum;
  198. logGlobal->infoStream() << "\tReading options";
  199. in >> si;
  200. logGlobal->infoStream() <<"\tReading handlers";
  201. in >> *VLC;
  202. logGlobal->infoStream() <<"\tReading gamestate";
  203. in >> gs;
  204. }
  205. template<typename Saver>
  206. void CPrivilagedInfoCallback::saveCommonState(Saver &out) const
  207. {
  208. logGlobal->infoStream() << "Saving lib part of game...";
  209. out.putMagicBytes(SAVEGAME_MAGIC);
  210. logGlobal->infoStream() <<"\tSaving header";
  211. out << static_cast<CMapHeader&>(*gs->map);
  212. logGlobal->infoStream() << "\tSaving options";
  213. out << gs->scenarioOps;
  214. logGlobal->infoStream() << "\tSaving handlers";
  215. out << *VLC;
  216. logGlobal->infoStream() << "\tSaving gamestate";
  217. out << gs;
  218. }
  219. template DLL_LINKAGE void CPrivilagedInfoCallback::loadCommonState<CLoadIntegrityValidator>(CLoadIntegrityValidator&);
  220. template DLL_LINKAGE void CPrivilagedInfoCallback::loadCommonState<CLoadFile>(CLoadFile&);
  221. template DLL_LINKAGE void CPrivilagedInfoCallback::saveCommonState<CSaveFile>(CSaveFile&) const;
  222. TerrainTile * CNonConstInfoCallback::getTile( int3 pos )
  223. {
  224. if(!gs->map->isInTheMap(pos))
  225. return nullptr;
  226. return &gs->map->getTile(pos);
  227. }
  228. const PlayerState * CGameInfoCallback::getPlayer(PlayerColor color, bool verbose) const
  229. {
  230. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!hasAccess(color), verbose, "Cannot access player " << color << "info!", nullptr);
  231. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!vstd::contains(gs->players,color), verbose, "Cannot find player " << color << "info!", nullptr);
  232. return &gs->players[color];
  233. }
  234. const CTown * CGameInfoCallback::getNativeTown(PlayerColor color) const
  235. {
  236. const PlayerSettings *ps = getPlayerSettings(color);
  237. ERROR_RET_VAL_IF(!ps, "There is no such player!", nullptr);
  238. return VLC->townh->factions[ps->castle]->town;
  239. }
  240. const CGObjectInstance * CGameInfoCallback::getObjByQuestIdentifier(int identifier) const
  241. {
  242. ERROR_RET_VAL_IF(!vstd::contains(gs->map->questIdentifierToId, identifier), "There is no object with such quest identifier!", nullptr);
  243. return getObj(gs->map->questIdentifierToId[identifier]);
  244. }
  245. /************************************************************************/
  246. /* */
  247. /************************************************************************/
  248. const CGObjectInstance* CGameInfoCallback::getObj(ObjectInstanceID objid, bool verbose) const
  249. {
  250. si32 oid = objid.num;
  251. if(oid < 0 || oid >= gs->map->objects.size())
  252. {
  253. if(verbose)
  254. logGlobal->errorStream() << "Cannot get object with id " << oid;
  255. return nullptr;
  256. }
  257. const CGObjectInstance *ret = gs->map->objects[oid];
  258. if(!ret)
  259. {
  260. if(verbose)
  261. logGlobal->errorStream() << "Cannot get object with id " << oid << ". Object was removed.";
  262. return nullptr;
  263. }
  264. if(!isVisible(ret, player))
  265. {
  266. if(verbose)
  267. logGlobal->errorStream() << "Cannot get object with id " << oid << ". Object is not visible.";
  268. return nullptr;
  269. }
  270. return ret;
  271. }
  272. const CGHeroInstance* CGameInfoCallback::getHero(ObjectInstanceID objid) const
  273. {
  274. const CGObjectInstance *obj = getObj(objid, false);
  275. if(obj)
  276. return dynamic_cast<const CGHeroInstance*>(obj);
  277. else
  278. return nullptr;
  279. }
  280. const CGTownInstance* CGameInfoCallback::getTown(ObjectInstanceID objid) const
  281. {
  282. const CGObjectInstance *obj = getObj(objid, false);
  283. if(obj)
  284. return dynamic_cast<const CGTownInstance*>(obj);
  285. else
  286. return nullptr;
  287. }
  288. void CGameInfoCallback::getUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  289. {
  290. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  291. ERROR_RET_IF(!canGetFullInfo(obj), "Cannot get info about not owned object!");
  292. ERROR_RET_IF(!obj->hasStackAtSlot(stackPos), "There is no such stack!");
  293. out = gs->getUpgradeInfo(obj->getStack(stackPos));
  294. //return gs->getUpgradeInfo(obj->getStack(stackPos));
  295. }
  296. const StartInfo * CGameInfoCallback::getStartInfo(bool beforeRandomization /*= false*/) const
  297. {
  298. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  299. if(beforeRandomization)
  300. return gs->initialOpts;
  301. else
  302. return gs->scenarioOps;
  303. }
  304. int CGameInfoCallback::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  305. {
  306. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  307. ERROR_RET_VAL_IF(!canGetFullInfo(caster), "Cannot get info about caster!", -1);
  308. //if there is a battle
  309. if(gs->curB)
  310. return gs->curB->battleGetSpellCost(sp, caster);
  311. //if there is no battle
  312. return caster->getSpellCost(sp);
  313. }
  314. int CGameInfoCallback::estimateSpellDamage(const CSpell * sp, const CGHeroInstance * hero) const
  315. {
  316. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  317. ERROR_RET_VAL_IF(hero && !canGetFullInfo(hero), "Cannot get info about caster!", -1);
  318. if(!gs->curB) //no battle
  319. {
  320. if (hero) //but we see hero's spellbook
  321. return gs->curB->calculateSpellDmg(
  322. sp, hero, nullptr, hero->getSpellSchoolLevel(sp), hero->getPrimSkillLevel(PrimarySkill::SPELL_POWER));
  323. else
  324. return 0; //mage guild
  325. }
  326. //gs->getHero(gs->currentPlayer)
  327. //const CGHeroInstance * ourHero = gs->curB->heroes[0]->tempOwner == player ? gs->curB->heroes[0] : gs->curB->heroes[1];
  328. const CGHeroInstance * ourHero = hero;
  329. return gs->curB->calculateSpellDmg(
  330. sp, ourHero, nullptr, ourHero->getSpellSchoolLevel(sp), ourHero->getPrimSkillLevel(PrimarySkill::SPELL_POWER));
  331. }
  332. void CGameInfoCallback::getThievesGuildInfo(SThievesGuildInfo & thi, const CGObjectInstance * obj)
  333. {
  334. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  335. ERROR_RET_IF(!obj, "No guild object!");
  336. ERROR_RET_IF(obj->ID == Obj::TOWN && !canGetFullInfo(obj), "Cannot get info about town guild object!");
  337. //TODO: advmap object -> check if they're visited by our hero
  338. if(obj->ID == Obj::TOWN || obj->ID == Obj::TAVERN)
  339. {
  340. gs->obtainPlayersStats(thi, gs->players[obj->tempOwner].towns.size());
  341. }
  342. else if(obj->ID == Obj::DEN_OF_THIEVES)
  343. {
  344. gs->obtainPlayersStats(thi, 20);
  345. }
  346. }
  347. int CGameInfoCallback::howManyTowns(PlayerColor Player) const
  348. {
  349. ERROR_RET_VAL_IF(!hasAccess(Player), "Access forbidden!", -1);
  350. return gs->players[Player].towns.size();
  351. }
  352. bool CGameInfoCallback::getTownInfo( const CGObjectInstance *town, InfoAboutTown &dest ) const
  353. {
  354. ERROR_RET_VAL_IF(!isVisible(town, player), "Town is not visible!", false); //it's not a town or it's not visible for layer
  355. bool detailed = hasAccess(town->tempOwner);
  356. //TODO vision support
  357. if(town->ID == Obj::TOWN)
  358. dest.initFromTown(static_cast<const CGTownInstance *>(town), detailed);
  359. else if(town->ID == Obj::GARRISON || town->ID == Obj::GARRISON2)
  360. dest.initFromArmy(static_cast<const CArmedInstance *>(town), detailed);
  361. else
  362. return false;
  363. return true;
  364. }
  365. int3 CGameInfoCallback::guardingCreaturePosition (int3 pos) const
  366. {
  367. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", int3(-1,-1,-1));
  368. return gs->guardingCreaturePosition(pos);
  369. }
  370. std::vector<const CGObjectInstance*> CGameInfoCallback::getGuardingCreatures (int3 pos) const
  371. {
  372. ERROR_RET_VAL_IF(!isVisible(pos), "Tile is not visible!", std::vector<const CGObjectInstance*>());
  373. std::vector<const CGObjectInstance*> ret;
  374. for(auto cr : gs->guardingCreatures(pos))
  375. {
  376. ret.push_back(cr);
  377. }
  378. return ret;
  379. }
  380. bool CGameInfoCallback::getHeroInfo( const CGObjectInstance *hero, InfoAboutHero &dest ) const
  381. {
  382. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(hero);
  383. ERROR_RET_VAL_IF(!h, "That's not a hero!", false);
  384. ERROR_RET_VAL_IF(!isVisible(h->getPosition(false)), "That hero is not visible!", false);
  385. //TODO vision support
  386. dest.initFromHero(h, hasAccess(h->tempOwner));
  387. return true;
  388. }
  389. int CGameInfoCallback::getDate(Date::EDateType mode) const
  390. {
  391. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  392. return gs->getDate(mode);
  393. }
  394. std::vector < std::string > CGameInfoCallback::getObjDescriptions(int3 pos) const
  395. {
  396. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  397. std::vector<std::string> ret;
  398. const TerrainTile *t = getTile(pos);
  399. ERROR_RET_VAL_IF(!t, "Not a valid tile given!", ret);
  400. for(const CGObjectInstance * obj : t->blockingObjects)
  401. ret.push_back(obj->getHoverText());
  402. return ret;
  403. }
  404. bool CGameInfoCallback::isVisible(int3 pos, boost::optional<PlayerColor> Player) const
  405. {
  406. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  407. return gs->map->isInTheMap(pos) && (!Player || gs->isVisible(pos, *Player));
  408. }
  409. bool CGameInfoCallback::isVisible(int3 pos) const
  410. {
  411. return isVisible(pos, player);
  412. }
  413. bool CGameInfoCallback::isVisible( const CGObjectInstance *obj, boost::optional<PlayerColor> Player ) const
  414. {
  415. return gs->isVisible(obj, Player);
  416. }
  417. bool CGameInfoCallback::isVisible(const CGObjectInstance *obj) const
  418. {
  419. return isVisible(obj, player);
  420. }
  421. // const CCreatureSet* CInfoCallback::getGarrison(const CGObjectInstance *obj) const
  422. // {
  423. // //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  424. // if()
  425. // const CArmedInstance *armi = dynamic_cast<const CArmedInstance*>(obj);
  426. // if(!armi)
  427. // return nullptr;
  428. // else
  429. // return armi;
  430. // }
  431. std::vector < const CGObjectInstance * > CGameInfoCallback::getBlockingObjs( int3 pos ) const
  432. {
  433. std::vector<const CGObjectInstance *> ret;
  434. const TerrainTile *t = getTile(pos);
  435. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  436. for(const CGObjectInstance * obj : t->blockingObjects)
  437. ret.push_back(obj);
  438. return ret;
  439. }
  440. std::vector <const CGObjectInstance * > CGameInfoCallback::getVisitableObjs(int3 pos, bool verbose /*= true*/) const
  441. {
  442. std::vector<const CGObjectInstance *> ret;
  443. const TerrainTile *t = getTile(pos, verbose);
  444. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!t, verbose, pos << " is not visible!", ret);
  445. for(const CGObjectInstance * obj : t->visitableObjects)
  446. {
  447. if(player < nullptr || obj->ID != Obj::EVENT) //hide events from players
  448. ret.push_back(obj);
  449. }
  450. return ret;
  451. }
  452. std::vector < const CGObjectInstance * > CGameInfoCallback::getFlaggableObjects(int3 pos) const
  453. {
  454. std::vector<const CGObjectInstance *> ret;
  455. const TerrainTile *t = getTile(pos);
  456. ERROR_RET_VAL_IF(!t, "Not a valid tile requested!", ret);
  457. for(const CGObjectInstance *obj : t->blockingObjects)
  458. if(obj->tempOwner != PlayerColor::UNFLAGGABLE)
  459. ret.push_back(obj);
  460. // const std::vector < std::pair<const CGObjectInstance*,SDL_Rect> > & objs = CGI->mh->ttiles[pos.x][pos.y][pos.z].objects;
  461. // for(size_t b=0; b<objs.size(); ++b)
  462. // {
  463. // 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))
  464. // ret.push_back(CGI->mh->ttiles[pos.x][pos.y][pos.z].objects[b].first);
  465. // }
  466. return ret;
  467. }
  468. int3 CGameInfoCallback::getMapSize() const
  469. {
  470. return int3(gs->map->width, gs->map->height, gs->map->twoLevel ? 2 : 1);
  471. }
  472. std::vector<const CGHeroInstance *> CGameInfoCallback::getAvailableHeroes(const CGObjectInstance * townOrTavern) const
  473. {
  474. ASSERT_IF_CALLED_WITH_PLAYER
  475. std::vector<const CGHeroInstance *> ret;
  476. //ERROR_RET_VAL_IF(!isOwnedOrVisited(townOrTavern), "Town or tavern must be owned or visited!", ret);
  477. //TODO: town needs to be owned, advmap tavern needs to be visited; to be reimplemented when visit tracking is done
  478. ret.resize(gs->players[*player].availableHeroes.size());
  479. std::copy(gs->players[*player].availableHeroes.begin(),gs->players[*player].availableHeroes.end(),ret.begin());
  480. return ret;
  481. }
  482. const TerrainTile * CGameInfoCallback::getTile( int3 tile, bool verbose) const
  483. {
  484. ERROR_VERBOSE_OR_NOT_RET_VAL_IF(!isVisible(tile), verbose, tile << " is not visible!", nullptr);
  485. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  486. return &gs->map->getTile(tile);
  487. }
  488. EBuildingState::EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID )
  489. {
  490. ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", EBuildingState::TOWN_NOT_OWNED);
  491. if(!t->town->buildings.count(ID))
  492. return EBuildingState::BUILDING_ERROR;
  493. const CBuilding * pom = t->town->buildings.at(ID);
  494. if(t->hasBuilt(ID)) //already built
  495. return EBuildingState::ALREADY_PRESENT;
  496. //can we build it?
  497. if(vstd::contains(t->forbiddenBuildings, ID))
  498. return EBuildingState::FORBIDDEN; //forbidden
  499. //checking for requirements
  500. std::set<BuildingID> reqs = getBuildingRequiments(t, ID);//getting all requirements
  501. bool notAllBuilt = false;
  502. for(auto & req : reqs)
  503. {
  504. if(!t->hasBuilt(req)) //lack of requirements - cannot build
  505. {
  506. if(vstd::contains(t->forbiddenBuildings, req)) // not built requirement forbidden - same goes to this build
  507. return EBuildingState::FORBIDDEN;
  508. else
  509. notAllBuilt = true; // no return here - we need to check if any required builds are forbidden
  510. }
  511. }
  512. if(t->builded >= VLC->modh->settings.MAX_BUILDING_PER_TURN)
  513. return EBuildingState::CANT_BUILD_TODAY; //building limit
  514. if (notAllBuilt)
  515. return EBuildingState::PREREQUIRES;
  516. if(ID == BuildingID::CAPITOL)
  517. {
  518. const PlayerState *ps = getPlayer(t->tempOwner);
  519. if(ps)
  520. {
  521. for(const CGTownInstance *t : ps->towns)
  522. {
  523. if(t->hasBuilt(BuildingID::CAPITOL))
  524. {
  525. return EBuildingState::HAVE_CAPITAL; //no more than one capitol
  526. }
  527. }
  528. }
  529. }
  530. else if(ID == BuildingID::SHIPYARD)
  531. {
  532. const TerrainTile *tile = getTile(t->bestLocation(), false);
  533. if(!tile || tile->terType != ETerrainType::WATER)
  534. return EBuildingState::NO_WATER; //lack of water
  535. }
  536. //checking resources
  537. if(!pom->resources.canBeAfforded(getPlayer(t->tempOwner)->resources))
  538. return EBuildingState::NO_RESOURCES; //lack of res
  539. return EBuildingState::ALLOWED;
  540. }
  541. std::set<BuildingID> CGameInfoCallback::getBuildingRequiments( const CGTownInstance *t, BuildingID ID )
  542. {
  543. ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", std::set<BuildingID>());
  544. ERROR_RET_VAL_IF(!t->town->buildings.count(ID), "No such building!", std::set<BuildingID>());
  545. std::set<int> used;
  546. used.insert(ID);
  547. auto reqs = t->town->buildings.at(ID)->requirements;
  548. bool found;
  549. do
  550. {
  551. found = false;
  552. for(auto i=reqs.begin();i!=reqs.end();i++)
  553. {
  554. if(used.find(*i)==used.end()) //we haven't added requirements for this building
  555. {
  556. found = true;
  557. auto & requires = t->town->buildings.at(*i)->requirements;
  558. used.insert(*i);
  559. for(auto & require : requires)
  560. reqs.insert(require);//creating full list of requirements
  561. }
  562. }
  563. }
  564. while (found);
  565. return reqs;
  566. }
  567. const CMapHeader * CGameInfoCallback::getMapHeader() const
  568. {
  569. return gs->map;
  570. }
  571. bool CGameInfoCallback::hasAccess(boost::optional<PlayerColor> playerId) const
  572. {
  573. return !player || gs->getPlayerRelations( *playerId, *player ) != PlayerRelations::ENEMIES;
  574. }
  575. EPlayerStatus::EStatus CGameInfoCallback::getPlayerStatus(PlayerColor player) const
  576. {
  577. const PlayerState *ps = gs->getPlayer(player, false);
  578. ERROR_RET_VAL_IF(!ps, "No such player!", EPlayerStatus::WRONG);
  579. return ps->status;
  580. }
  581. std::string CGameInfoCallback::getTavernGossip(const CGObjectInstance * townOrTavern) const
  582. {
  583. return "GOSSIP TEST";
  584. }
  585. PlayerRelations::PlayerRelations CGameInfoCallback::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  586. {
  587. return gs->getPlayerRelations(color1, color2);
  588. }
  589. bool CGameInfoCallback::canGetFullInfo(const CGObjectInstance *obj) const
  590. {
  591. return !obj || hasAccess(obj->tempOwner);
  592. }
  593. int CGameInfoCallback::getHeroCount( PlayerColor player, bool includeGarrisoned ) const
  594. {
  595. int ret = 0;
  596. const PlayerState *p = gs->getPlayer(player);
  597. ERROR_RET_VAL_IF(!p, "No such player!", -1);
  598. if(includeGarrisoned)
  599. return p->heroes.size();
  600. else
  601. for(auto & elem : p->heroes)
  602. if(!elem->inTownGarrison)
  603. ret++;
  604. return ret;
  605. }
  606. bool CGameInfoCallback::isOwnedOrVisited(const CGObjectInstance *obj) const
  607. {
  608. if(canGetFullInfo(obj))
  609. return true;
  610. const TerrainTile *t = getTile(obj->visitablePos()); //get entrance tile
  611. const CGObjectInstance *visitor = t->visitableObjects.back(); //visitong hero if present or the obejct itself at last
  612. return visitor->ID == Obj::HERO && canGetFullInfo(visitor); //owned or allied hero is a visitor
  613. }
  614. PlayerColor CGameInfoCallback::getCurrentPlayer() const
  615. {
  616. return gs->currentPlayer;
  617. }
  618. CGameInfoCallback::CGameInfoCallback()
  619. {
  620. }
  621. CGameInfoCallback::CGameInfoCallback(CGameState *GS, boost::optional<PlayerColor> Player)
  622. {
  623. gs = GS;
  624. player = Player;
  625. }
  626. const std::vector< std::vector< std::vector<ui8> > > & CPlayerSpecificInfoCallback::getVisibilityMap() const
  627. {
  628. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  629. return gs->getPlayerTeam(*player)->fogOfWarMap;
  630. }
  631. int CPlayerSpecificInfoCallback::howManyTowns() const
  632. {
  633. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  634. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", -1);
  635. return CGameInfoCallback::howManyTowns(*player);
  636. }
  637. std::vector < const CGTownInstance *> CPlayerSpecificInfoCallback::getTownsInfo(bool onlyOur) const
  638. {
  639. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  640. std::vector < const CGTownInstance *> ret = std::vector < const CGTownInstance *>();
  641. for(const auto & i : gs->players)
  642. {
  643. for(const auto & town : i.second.towns)
  644. {
  645. if (i.first==player || (isVisible(town, player) && !onlyOur))
  646. {
  647. ret.push_back(town);
  648. }
  649. }
  650. } // for ( std::map<int, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  651. return ret;
  652. }
  653. std::vector < const CGHeroInstance *> CPlayerSpecificInfoCallback::getHeroesInfo(bool onlyOur) const
  654. {
  655. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  656. std::vector < const CGHeroInstance *> ret;
  657. for(auto hero : gs->map->heroesOnMap)
  658. {
  659. if( !player || (hero->tempOwner == *player) ||
  660. (isVisible(hero->getPosition(false), player) && !onlyOur) )
  661. {
  662. ret.push_back(hero);
  663. }
  664. }
  665. return ret;
  666. }
  667. boost::optional<PlayerColor> CPlayerSpecificInfoCallback::getMyColor() const
  668. {
  669. return player;
  670. }
  671. int CPlayerSpecificInfoCallback::getHeroSerial(const CGHeroInstance * hero, bool includeGarrisoned) const
  672. {
  673. if (hero->inTownGarrison && !includeGarrisoned)
  674. return -1;
  675. size_t index = 0;
  676. auto & heroes = gs->players[*player].heroes;
  677. for (auto & heroe : heroes)
  678. {
  679. if (includeGarrisoned || !(heroe)->inTownGarrison)
  680. index++;
  681. if (heroe == hero)
  682. return index;
  683. }
  684. return -1;
  685. }
  686. int3 CPlayerSpecificInfoCallback::getGrailPos( double &outKnownRatio )
  687. {
  688. if (!player || CGObelisk::obeliskCount == 0)
  689. {
  690. outKnownRatio = 0.0;
  691. }
  692. else
  693. {
  694. outKnownRatio = static_cast<double>(CGObelisk::visited[gs->getPlayerTeam(*player)->id]) / CGObelisk::obeliskCount;
  695. }
  696. return gs->map->grailPos;
  697. }
  698. std::vector < const CGObjectInstance * > CPlayerSpecificInfoCallback::getMyObjects() const
  699. {
  700. std::vector < const CGObjectInstance * > ret;
  701. for(const CGObjectInstance * obj : gs->map->objects)
  702. {
  703. if(obj && obj->tempOwner == player)
  704. ret.push_back(obj);
  705. }
  706. return ret;
  707. }
  708. std::vector < const CGDwelling * > CPlayerSpecificInfoCallback::getMyDwellings() const
  709. {
  710. ASSERT_IF_CALLED_WITH_PLAYER
  711. std::vector < const CGDwelling * > ret;
  712. for(CGDwelling * dw : gs->getPlayer(*player)->dwellings)
  713. {
  714. ret.push_back(dw);
  715. }
  716. return ret;
  717. }
  718. std::vector <QuestInfo> CPlayerSpecificInfoCallback::getMyQuests() const
  719. {
  720. std::vector <QuestInfo> ret;
  721. for (auto quest : gs->getPlayer(*player)->quests)
  722. {
  723. ret.push_back (quest);
  724. }
  725. return ret;
  726. }
  727. int CPlayerSpecificInfoCallback::howManyHeroes(bool includeGarrisoned) const
  728. {
  729. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  730. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", -1);
  731. return getHeroCount(*player,includeGarrisoned);
  732. }
  733. const CGHeroInstance* CPlayerSpecificInfoCallback::getHeroBySerial(int serialId, bool includeGarrisoned) const
  734. {
  735. ASSERT_IF_CALLED_WITH_PLAYER
  736. const PlayerState *p = getPlayer(*player);
  737. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  738. if (!includeGarrisoned)
  739. {
  740. for(ui32 i = 0; i < p->heroes.size() && i<=serialId; i++)
  741. if(p->heroes[i]->inTownGarrison)
  742. serialId++;
  743. }
  744. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->heroes.size(), "No player info", nullptr);
  745. return p->heroes[serialId];
  746. }
  747. const CGTownInstance* CPlayerSpecificInfoCallback::getTownBySerial(int serialId) const
  748. {
  749. ASSERT_IF_CALLED_WITH_PLAYER
  750. const PlayerState *p = getPlayer(*player);
  751. ERROR_RET_VAL_IF(!p, "No player info", nullptr);
  752. ERROR_RET_VAL_IF(serialId < 0 || serialId >= p->towns.size(), "No player info", nullptr);
  753. return p->towns[serialId];
  754. }
  755. int CPlayerSpecificInfoCallback::getResourceAmount(Res::ERes type) const
  756. {
  757. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  758. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", -1);
  759. return getResource(*player, type);
  760. }
  761. TResources CPlayerSpecificInfoCallback::getResourceAmount() const
  762. {
  763. //boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  764. ERROR_RET_VAL_IF(!player, "Applicable only for player callbacks", TResources());
  765. return gs->players[*player].resources;
  766. }
  767. CGHeroInstance *CNonConstInfoCallback::getHero(ObjectInstanceID objid)
  768. {
  769. return const_cast<CGHeroInstance*>(CGameInfoCallback::getHero(objid));
  770. }
  771. CGTownInstance *CNonConstInfoCallback::getTown(ObjectInstanceID objid)
  772. {
  773. return const_cast<CGTownInstance*>(CGameInfoCallback::getTown(objid));
  774. }
  775. TeamState *CNonConstInfoCallback::getTeam(TeamID teamID)
  776. {
  777. return const_cast<TeamState*>(CGameInfoCallback::getTeam(teamID));
  778. }
  779. TeamState *CNonConstInfoCallback::getPlayerTeam(PlayerColor color)
  780. {
  781. return const_cast<TeamState*>(CGameInfoCallback::getPlayerTeam(color));
  782. }
  783. PlayerState * CNonConstInfoCallback::getPlayer( PlayerColor color, bool verbose )
  784. {
  785. return const_cast<PlayerState*>(CGameInfoCallback::getPlayer(color, verbose));
  786. }
  787. CArtifactInstance * CNonConstInfoCallback::getArtInstance( ArtifactInstanceID aid )
  788. {
  789. return gs->map->artInstances[aid.num];
  790. }
  791. CGObjectInstance * CNonConstInfoCallback::getObjInstance( ObjectInstanceID oid )
  792. {
  793. return gs->map->objects[oid.num];
  794. }
  795. const TeamState * CGameInfoCallback::getTeam( TeamID teamID ) const
  796. {
  797. ERROR_RET_VAL_IF(!vstd::contains(gs->teams, teamID), "Cannot find info for team " << teamID, nullptr);
  798. const TeamState *ret = &gs->teams[teamID];
  799. ERROR_RET_VAL_IF(!!player && !vstd::contains(ret->players, *player), "Illegal attempt to access team data!", nullptr);
  800. return ret;
  801. }
  802. const TeamState * CGameInfoCallback::getPlayerTeam( PlayerColor color ) const
  803. {
  804. const PlayerState * ps = getPlayer(color);
  805. if (ps)
  806. return getTeam(ps->team);
  807. return nullptr;
  808. }
  809. const CGHeroInstance* CGameInfoCallback::getHeroWithSubid( int subid ) const
  810. {
  811. for(const CGHeroInstance *h : gs->map->heroesOnMap)
  812. if(h->subID == subid)
  813. return h;
  814. return nullptr;
  815. }
  816. PlayerColor CGameInfoCallback::getLocalPlayer() const
  817. {
  818. return getCurrentPlayer();
  819. }
  820. bool CGameInfoCallback::isInTheMap(const int3 &pos) const
  821. {
  822. return gs->map->isInTheMap(pos);
  823. }
  824. const CArtifactInstance * CGameInfoCallback::getArtInstance( ArtifactInstanceID aid ) const
  825. {
  826. return gs->map->artInstances[aid.num];
  827. }
  828. const CGObjectInstance * CGameInfoCallback::getObjInstance( ObjectInstanceID oid ) const
  829. {
  830. return gs->map->objects[oid.num];
  831. }
  832. void IGameEventRealizer::showInfoDialog( InfoWindow *iw )
  833. {
  834. commitPackage(iw);
  835. }
  836. void IGameEventRealizer::showInfoDialog(const std::string &msg, PlayerColor player)
  837. {
  838. InfoWindow iw;
  839. iw.player = player;
  840. iw.text << msg;
  841. showInfoDialog(&iw);
  842. }
  843. void IGameEventRealizer::setObjProperty(ObjectInstanceID objid, int prop, si64 val)
  844. {
  845. SetObjectProperty sob;
  846. sob.id = objid;
  847. sob.what = prop;
  848. sob.val = static_cast<ui32>(val);
  849. commitPackage(&sob);
  850. }
  851. const CGObjectInstance * IGameCallback::putNewObject(Obj ID, int subID, int3 pos)
  852. {
  853. NewObject no;
  854. no.ID = ID; //creature
  855. no.subID= subID;
  856. no.pos = pos;
  857. commitPackage(&no);
  858. return getObj(no.id); //id field will be filled during applying on gs
  859. }
  860. const CGCreature * IGameCallback::putNewMonster(CreatureID creID, int count, int3 pos)
  861. {
  862. const CGObjectInstance *m = putNewObject(Obj::MONSTER, creID, pos);
  863. setObjProperty(m->id, ObjProperty::MONSTER_COUNT, count);
  864. setObjProperty(m->id, ObjProperty::MONSTER_POWER, (si64)1000*count);
  865. return dynamic_cast<const CGCreature*>(m);
  866. }
  867. bool IGameCallback::isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero)
  868. {
  869. //only server knows
  870. assert(0);
  871. return false;
  872. }