CBattleCallback.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. #pragma once
  2. #include "BattleHex.h"
  3. /*
  4. * CBattleCallback.h, part of VCMI engine
  5. *
  6. * Authors: listed in file AUTHORS in main folder
  7. *
  8. * License: GNU General Public License v2.0 or later
  9. * Full text of license available in license.txt file, in main folder
  10. *
  11. */
  12. class CGameState;
  13. class CGTownInstance;
  14. class CGHeroInstance;
  15. class CStack;
  16. class ISpellCaster;
  17. class CSpell;
  18. struct BattleInfo;
  19. struct CObstacleInstance;
  20. class IBonusBearer;
  21. struct InfoAboutHero;
  22. class CArmedInstance;
  23. class CRandomGenerator;
  24. namespace boost
  25. {class shared_mutex;}
  26. namespace BattleSide
  27. {
  28. enum {ATTACKER = 0, DEFENDER = 1};
  29. }
  30. typedef std::vector<const CStack*> TStacks;
  31. typedef std::function<bool(const CStack *)> TStackFilter;
  32. class CBattleInfoEssentials;
  33. //Basic class for various callbacks (interfaces called by players to get info about game and so forth)
  34. class DLL_LINKAGE CCallbackBase
  35. {
  36. const BattleInfo *battle; //battle to which the player is engaged, nullptr if none or not applicable
  37. const BattleInfo * getBattle() const
  38. {
  39. return battle;
  40. }
  41. protected:
  42. CGameState *gs;
  43. boost::optional<PlayerColor> player; // not set gives access to all information, otherwise callback provides only information "visible" for player
  44. CCallbackBase(CGameState *GS, boost::optional<PlayerColor> Player)
  45. : battle(nullptr), gs(GS), player(Player)
  46. {}
  47. CCallbackBase()
  48. : battle(nullptr), gs(nullptr)
  49. {}
  50. void setBattle(const BattleInfo *B);
  51. bool duringBattle() const;
  52. public:
  53. boost::shared_mutex &getGsMutex(); //just return a reference to mutex, does not lock nor anything
  54. boost::optional<PlayerColor> getPlayerID() const;
  55. friend class CBattleInfoEssentials;
  56. };
  57. struct DLL_LINKAGE AttackableTiles
  58. {
  59. std::set<BattleHex> hostileCreaturePositions;
  60. std::set<BattleHex> friendlyCreaturePositions; //for Dragon Breath
  61. template <typename Handler> void serialize(Handler &h, const int version)
  62. {
  63. h & hostileCreaturePositions & friendlyCreaturePositions;
  64. }
  65. };
  66. //Accessibility is property of hex in battle. It doesn't depend on stack, side's perspective and so on.
  67. namespace EAccessibility
  68. {
  69. enum EAccessibility
  70. {
  71. ACCESSIBLE,
  72. ALIVE_STACK,
  73. OBSTACLE,
  74. DESTRUCTIBLE_WALL,
  75. GATE, //sieges -> gate opens only for defender stacks
  76. UNAVAILABLE, //indestructible wall parts, special battlefields (like boat-to-boat)
  77. SIDE_COLUMN //used for first and last columns of hexes that are unavailable but wat machines can stand there
  78. };
  79. }
  80. typedef std::array<EAccessibility::EAccessibility, GameConstants::BFIELD_SIZE> TAccessibilityArray;
  81. struct DLL_LINKAGE AccessibilityInfo : TAccessibilityArray
  82. {
  83. bool occupiable(const CStack *stack, BattleHex tile) const;
  84. bool accessible(BattleHex tile, const CStack *stack) const; //checks for both tiles if stack is double wide
  85. bool accessible(BattleHex tile, bool doubleWide, bool attackerOwned) const; //checks for both tiles if stack is double wide
  86. };
  87. namespace BattlePerspective
  88. {
  89. enum BattlePerspective
  90. {
  91. INVALID = -2,
  92. ALL_KNOWING = -1,
  93. LEFT_SIDE,
  94. RIGHT_SIDE
  95. };
  96. }
  97. // Reachability info is result of BFS calculation. It's dependent on stack (it's owner, whether it's flying),
  98. // startPosition and perpective.
  99. struct DLL_LINKAGE ReachabilityInfo
  100. {
  101. typedef std::array<int, GameConstants::BFIELD_SIZE> TDistances;
  102. typedef std::array<BattleHex, GameConstants::BFIELD_SIZE> TPredecessors;
  103. enum { INFINITE_DIST = 1000000 };
  104. struct DLL_LINKAGE Parameters
  105. {
  106. const CStack *stack; //stack for which calculation is mage => not required (kept for debugging mostly), following variables are enough
  107. bool attackerOwned;
  108. bool doubleWide;
  109. bool flying;
  110. std::vector<BattleHex> knownAccessible; //hexes that will be treated as accessible, even if they're occupied by stack (by default - tiles occupied by stack we do reachability for, so it doesn't block itself)
  111. BattleHex startPosition; //assumed position of stack
  112. BattlePerspective::BattlePerspective perspective; //some obstacles (eg. quicksands) may be invisible for some side
  113. Parameters();
  114. Parameters(const CStack *Stack);
  115. };
  116. Parameters params;
  117. AccessibilityInfo accessibility;
  118. TDistances distances;
  119. TPredecessors predecessors;
  120. ReachabilityInfo()
  121. {
  122. distances.fill(INFINITE_DIST);
  123. predecessors.fill(BattleHex::INVALID);
  124. }
  125. bool isReachable(BattleHex hex) const
  126. {
  127. return distances[hex] < INFINITE_DIST;
  128. }
  129. };
  130. class DLL_LINKAGE CBattleInfoEssentials : public virtual CCallbackBase
  131. {
  132. protected:
  133. bool battleDoWeKnowAbout(ui8 side) const;
  134. const IBonusBearer * getBattleNode() const;
  135. public:
  136. enum EStackOwnership
  137. {
  138. ONLY_MINE, ONLY_ENEMY, MINE_AND_ENEMY
  139. };
  140. BattlePerspective::BattlePerspective battleGetMySide() const;
  141. ETerrainType battleTerrainType() const;
  142. BFieldType battleGetBattlefieldType() const;
  143. std::vector<std::shared_ptr<const CObstacleInstance> > battleGetAllObstacles(boost::optional<BattlePerspective::BattlePerspective> perspective = boost::none) const; //returns all obstacles on the battlefield
  144. /** @brief Main method for getting battle stacks
  145. *
  146. * @param predicate Functor that shall return true for desired stack
  147. * @return filtered stacks
  148. *
  149. */
  150. TStacks battleGetStacksIf(TStackFilter predicate) const;
  151. bool battleHasNativeStack(ui8 side) const;
  152. int battleGetMoatDmg() const; //what dmg unit will suffer if ending turn in the moat
  153. const CGTownInstance * battleGetDefendedTown() const; //returns defended town if current battle is a siege, nullptr instead
  154. const CStack *battleActiveStack() const;
  155. si8 battleTacticDist() const; //returns tactic distance in current tactics phase; 0 if not in tactics phase
  156. si8 battleGetTacticsSide() const; //returns which side is in tactics phase, undefined if none (?)
  157. bool battleCanFlee(PlayerColor player) const;
  158. bool battleCanSurrender(PlayerColor player) const;
  159. ui8 playerToSide(PlayerColor player) const;
  160. bool playerHasAccessToHeroInfo(PlayerColor player, const CGHeroInstance * h) const;
  161. ui8 battleGetSiegeLevel() const; //returns 0 when there is no siege, 1 if fort, 2 is citadel, 3 is castle
  162. bool battleHasHero(ui8 side) const;
  163. int battleCastSpells(ui8 side) const; //how many spells has given side cast
  164. const CGHeroInstance * battleGetFightingHero(ui8 side) const; //depracated for players callback, easy to get wrong
  165. const CArmedInstance * battleGetArmyObject(ui8 side) const;
  166. InfoAboutHero battleGetHeroInfo(ui8 side) const;
  167. // for determining state of a part of the wall; format: parameter [0] - keep, [1] - bottom tower, [2] - bottom wall,
  168. // [3] - below gate, [4] - over gate, [5] - upper wall, [6] - uppert tower, [7] - gate; returned value: 1 - intact, 2 - damaged, 3 - destroyed; 0 - no battle
  169. si8 battleGetWallState(int partOfWall) const;
  170. EGateState battleGetGateState() const;
  171. //helpers
  172. ///returns all stacks, alive or dead or undead or mechanical :)
  173. TStacks battleGetAllStacks(bool includeTurrets = false) const;
  174. ///returns all alive stacks excluding turrets
  175. TStacks battleAliveStacks() const;
  176. ///returns all alive stacks from particular side excluding turrets
  177. TStacks battleAliveStacks(ui8 side) const;
  178. const CStack * battleGetStackByID(int ID, bool onlyAlive = true) const; //returns stack info by given ID
  179. bool battleIsObstacleVisibleForSide(const CObstacleInstance & coi, BattlePerspective::BattlePerspective side) const;
  180. ///returns player that controls given stack; mind control included
  181. PlayerColor battleGetOwner(const CStack * stack) const;
  182. ///returns hero that controls given stack; nullptr if none; mind control included
  183. const CGHeroInstance * battleGetOwnerHero(const CStack * stack) const;
  184. ///check that stacks are controlled by same|other player(s) depending on positiveness
  185. ///mind control included
  186. bool battleMatchOwner(const CStack * attacker, const CStack * defender, const boost::logic::tribool positivness = false) const;
  187. };
  188. struct DLL_LINKAGE BattleAttackInfo
  189. {
  190. const IBonusBearer *attackerBonuses, *defenderBonuses;
  191. const CStack *attacker, *defender;
  192. BattleHex attackerPosition, defenderPosition;
  193. int attackerCount, defenderCount;
  194. bool shooting;
  195. int chargedFields;
  196. bool luckyHit;
  197. bool unluckyHit;
  198. bool deathBlow;
  199. bool ballistaDoubleDamage;
  200. BattleAttackInfo(const CStack *Attacker, const CStack *Defender, bool Shooting = false);
  201. BattleAttackInfo reverse() const;
  202. };
  203. class DLL_LINKAGE CBattleInfoCallback : public virtual CBattleInfoEssentials
  204. {
  205. public:
  206. enum ERandomSpell
  207. {
  208. RANDOM_GENIE, RANDOM_AIMED
  209. };
  210. //battle
  211. boost::optional<int> battleIsFinished() const; //return none if battle is ongoing; otherwise the victorious side (0/1) or 2 if it is a draw
  212. std::shared_ptr<const CObstacleInstance> battleGetObstacleOnPos(BattleHex tile, bool onlyBlocking = true) const; //blocking obstacles makes tile inaccessible, others cause special effects (like Land Mines, Moat, Quicksands)
  213. const CStack * battleGetStackByPos(BattleHex pos, bool onlyAlive = true) const; //returns stack info by given pos
  214. void battleGetStackQueue(std::vector<const CStack *> &out, const int howMany, const int turn = 0, int lastMoved = -1) const;
  215. void battleGetStackCountOutsideHexes(bool *ac) const; // returns hexes which when in front of a stack cause us to move the amount box back
  216. std::vector<BattleHex> battleGetAvailableHexes(const CStack * stack, bool addOccupiable, std::vector<BattleHex> * attackable = nullptr) const; //returns hexes reachable by creature with id ID (valid movement destinations), DOES contain stack current position
  217. int battleGetSurrenderCost(PlayerColor Player) const; //returns cost of surrendering battle, -1 if surrendering is not possible
  218. ReachabilityInfo::TDistances battleGetDistances(const CStack * stack, BattleHex hex = BattleHex::INVALID, BattleHex * predecessors = nullptr) const; //returns vector of distances to [dest hex number]
  219. std::set<BattleHex> battleGetAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos = BattleHex::INVALID) const;
  220. bool battleCanAttack(const CStack * stack, const CStack * target, BattleHex dest) const; //determines if stack with given ID can attack target at the selected destination
  221. bool battleCanShoot(const CStack * stack, BattleHex dest) const; //determines if stack with given ID shoot at the selected destination
  222. bool battleIsStackBlocked(const CStack * stack) const; //returns true if there is neighboring enemy stack
  223. std::set<const CStack*> batteAdjacentCreatures (const CStack * stack) const;
  224. TDmgRange calculateDmgRange(const BattleAttackInfo &info) const; //charge - number of hexes travelled before attack (for champion's jousting); returns pair <min dmg, max dmg>
  225. TDmgRange calculateDmgRange(const CStack* attacker, const CStack* defender, TQuantity attackerCount, bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg) const; //charge - number of hexes travelled before attack (for champion's jousting); returns pair <min dmg, max dmg>
  226. TDmgRange calculateDmgRange(const CStack* attacker, const CStack* defender, bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg) const; //charge - number of hexes travelled before attack (for champion's jousting); returns pair <min dmg, max dmg>
  227. //hextowallpart //int battleGetWallUnderHex(BattleHex hex) const; //returns part of destructible wall / gate / keep under given hex or -1 if not found
  228. std::pair<ui32, ui32> battleEstimateDamage(CRandomGenerator & rand, const BattleAttackInfo &bai, std::pair<ui32, ui32> * retaliationDmg = nullptr) const; //estimates damage dealt by attacker to defender; it may be not precise especially when stack has randomly working bonuses; returns pair <min dmg, max dmg>
  229. std::pair<ui32, ui32> battleEstimateDamage(CRandomGenerator & rand, const CStack * attacker, const CStack * defender, std::pair<ui32, ui32> * retaliationDmg = nullptr) const; //estimates damage dealt by attacker to defender; it may be not precise especially when stack has randomly working bonuses; returns pair <min dmg, max dmg>
  230. si8 battleHasDistancePenalty( const CStack * stack, BattleHex destHex ) const;
  231. si8 battleHasDistancePenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex ) const;
  232. si8 battleHasWallPenalty(const CStack * stack, BattleHex destHex) const; //checks if given stack has wall penalty
  233. si8 battleHasWallPenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const; //checks if given stack has wall penalty
  234. BattleHex wallPartToBattleHex(EWallPart::EWallPart part) const;
  235. EWallPart::EWallPart battleHexToWallPart(BattleHex hex) const; //returns part of destructible wall / gate / keep under given hex or -1 if not found
  236. bool isWallPartPotentiallyAttackable(EWallPart::EWallPart wallPart) const; // returns true if the wall part is potentially attackable (independent of wall state), false if not
  237. std::vector<BattleHex> getAttackableBattleHexes() const;
  238. //*** MAGIC
  239. si8 battleMaxSpellLevel(ui8 side) const; //calculates minimum spell level possible to be cast on battlefield - takes into account artifacts of both heroes; if no effects are set, 0 is returned
  240. ui32 battleGetSpellCost(const CSpell * sp, const CGHeroInstance * caster) const; //returns cost of given spell
  241. ESpellCastProblem::ESpellCastProblem battleCanCastSpell(const ISpellCaster * caster, ECastingMode::ECastingMode mode) const; //returns true if there are no general issues preventing from casting a spell
  242. ESpellCastProblem::ESpellCastProblem battleCanCastThisSpell(const ISpellCaster * caster, const CSpell * spell, ECastingMode::ECastingMode mode) const; //checks if given player can cast given spell
  243. ESpellCastProblem::ESpellCastProblem battleCanCastThisSpellHere(const ISpellCaster * caster, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest) const; //checks if given player can cast given spell at given tile in given mode
  244. SpellID battleGetRandomStackSpell(CRandomGenerator & rand, const CStack * stack, ERandomSpell mode) const;
  245. SpellID getRandomBeneficialSpell(CRandomGenerator & rand, const CStack * subject) const;
  246. SpellID getRandomCastedSpell(CRandomGenerator & rand, const CStack * caster) const; //called at the beginning of turn for Faerie Dragon
  247. const CStack * getStackIf(std::function<bool(const CStack*)> pred) const;
  248. si8 battleHasShootingPenalty(const CStack * stack, BattleHex destHex)
  249. {
  250. return battleHasDistancePenalty(stack, destHex) || battleHasWallPenalty(stack, destHex);
  251. }
  252. si8 battleCanTeleportTo(const CStack * stack, BattleHex destHex, int telportLevel) const; //checks if teleportation of given stack to given position can take place
  253. //convenience methods using the ones above
  254. bool isInTacticRange( BattleHex dest ) const;
  255. si8 battleGetTacticDist() const; //returns tactic distance for calling player or 0 if this player is not in tactic phase (for ALL_KNOWING actual distance for tactic side)
  256. AttackableTiles getPotentiallyAttackableHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const; //TODO: apply rotation to two-hex attacker
  257. std::set<const CStack*> getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos = BattleHex::INVALID) const; //calculates range of multi-hex attacks
  258. bool isToReverse(BattleHex hexFrom, BattleHex hexTo, bool curDir /*if true, creature is in attacker's direction*/, bool toDoubleWide, bool toDir) const; //determines if creature should be reversed (it stands on hexFrom and should 'see' hexTo)
  259. bool isToReverseHlp(BattleHex hexFrom, BattleHex hexTo, bool curDir) const; //helper for isToReverse
  260. ReachabilityInfo getReachability(const CStack *stack) const;
  261. ReachabilityInfo getReachability(const ReachabilityInfo::Parameters &params) const;
  262. AccessibilityInfo getAccesibility() const;
  263. AccessibilityInfo getAccesibility(const CStack *stack) const; //Hexes ocupied by stack will be marked as accessible.
  264. AccessibilityInfo getAccesibility(const std::vector<BattleHex> &accessibleHexes) const; //given hexes will be marked as accessible
  265. std::pair<const CStack *, BattleHex> getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const;
  266. protected:
  267. ReachabilityInfo getFlyingReachability(const ReachabilityInfo::Parameters &params) const;
  268. ReachabilityInfo makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters &params) const;
  269. ReachabilityInfo makeBFS(const CStack *stack) const; //uses default parameters -> stack position and owner's perspective
  270. std::set<BattleHex> getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const; //get hexes with stopping obstacles (quicksands)
  271. };
  272. class DLL_LINKAGE CPlayerBattleCallback : public CBattleInfoCallback
  273. {
  274. public:
  275. bool battleCanFlee() const; //returns true if caller can flee from the battle
  276. TStacks battleGetStacks(EStackOwnership whose = MINE_AND_ENEMY, bool onlyAlive = true) const; //returns stacks on battlefield
  277. ESpellCastProblem::ESpellCastProblem battleCanCastThisSpell(const CSpell * spell) const; //determines if given spell can be cast (and returns problem description)
  278. int battleGetSurrenderCost() const; //returns cost of surrendering battle, -1 if surrendering is not possible
  279. bool battleCanCastSpell(ESpellCastProblem::ESpellCastProblem *outProblem = nullptr) const; //returns true, if caller can cast a spell. If not, if pointer is given via arg, the reason will be written.
  280. const CGHeroInstance * battleGetMyHero() const;
  281. InfoAboutHero battleGetEnemyHero() const;
  282. };