BattleState.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. /*
  2. * BattleState.h, 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. #pragma once
  11. #include "BattleHex.h"
  12. #include "mapObjects/CArmedInstance.h" // for army serialization
  13. #include "mapObjects/CGHeroInstance.h" // for commander serialization
  14. #include "CCreatureHandler.h"
  15. #include "ConstTransitivePtr.h"
  16. #include "GameConstants.h"
  17. #include "CBattleCallback.h"
  18. #include "int3.h"
  19. #include "spells/Magic.h"
  20. class CGHeroInstance;
  21. class CStack;
  22. class CArmedInstance;
  23. class CGTownInstance;
  24. class CStackInstance;
  25. struct BattleStackAttacked;
  26. class CRandomGenerator;
  27. //only for use in BattleInfo
  28. struct DLL_LINKAGE SiegeInfo
  29. {
  30. std::array<si8, EWallPart::PARTS_COUNT> wallState;
  31. EGateState gateState;
  32. // return EWallState decreased by value of damage points
  33. static EWallState::EWallState applyDamage(EWallState::EWallState state, unsigned int value)
  34. {
  35. if (value == 0)
  36. return state;
  37. switch (applyDamage(state, value - 1))
  38. {
  39. case EWallState::INTACT : return EWallState::DAMAGED;
  40. case EWallState::DAMAGED : return EWallState::DESTROYED;
  41. case EWallState::DESTROYED : return EWallState::DESTROYED;
  42. default: return EWallState::NONE;
  43. }
  44. }
  45. template <typename Handler> void serialize(Handler &h, const int version)
  46. {
  47. h & wallState & gateState;
  48. }
  49. };
  50. struct DLL_LINKAGE SideInBattle
  51. {
  52. PlayerColor color;
  53. const CGHeroInstance *hero; //may be NULL if army is not commanded by hero
  54. const CArmedInstance *armyObject; //adv. map object with army that participates in battle; may be same as hero
  55. ui8 castSpellsCount; //how many spells each side has cast this turn
  56. std::vector<const CSpell *> usedSpellsHistory; //every time hero casts spell, it's inserted here -> eagle eye skill
  57. si16 enchanterCounter; //tends to pass through 0, so sign is needed
  58. SideInBattle();
  59. void init(const CGHeroInstance *Hero, const CArmedInstance *Army);
  60. template <typename Handler> void serialize(Handler &h, const int version)
  61. {
  62. h & color & hero & armyObject;
  63. h & castSpellsCount & usedSpellsHistory & enchanterCounter;
  64. }
  65. };
  66. struct DLL_LINKAGE BattleInfo : public CBonusSystemNode, public CBattleInfoCallback
  67. {
  68. std::array<SideInBattle, 2> sides; //sides[0] - attacker, sides[1] - defender
  69. si32 round, activeStack, selectedStack;
  70. const CGTownInstance * town; //used during town siege, nullptr if this is not a siege (note that fortless town IS also a siege)
  71. int3 tile; //for background and bonuses
  72. std::vector<CStack*> stacks;
  73. std::vector<std::shared_ptr<CObstacleInstance> > obstacles;
  74. SiegeInfo si;
  75. BFieldType battlefieldType; //like !!BA:B
  76. ETerrainType terrainType; //used for some stack nativity checks (not the bonus limiters though that have their own copy)
  77. ui8 tacticsSide; //which side is requested to play tactics phase
  78. ui8 tacticDistance; //how many hexes we can go forward (1 = only hexes adjacent to margin line)
  79. template <typename Handler> void serialize(Handler &h, const int version)
  80. {
  81. h & sides;
  82. h & round & activeStack & selectedStack & town & tile & stacks & obstacles
  83. & si & battlefieldType & terrainType;
  84. h & tacticsSide & tacticDistance;
  85. h & static_cast<CBonusSystemNode&>(*this);
  86. }
  87. //////////////////////////////////////////////////////////////////////////
  88. BattleInfo();
  89. ~BattleInfo(){};
  90. //////////////////////////////////////////////////////////////////////////
  91. CStack * getStackT(BattleHex tileID, bool onlyAlive = true);
  92. CStack * getStack(int stackID, bool onlyAlive = true);
  93. using CBattleInfoEssentials::battleGetArmyObject;
  94. CArmedInstance * battleGetArmyObject(ui8 side) const;
  95. using CBattleInfoEssentials::battleGetFightingHero;
  96. CGHeroInstance * battleGetFightingHero(ui8 side) const;
  97. const CStack * getNextStack() const; //which stack will have turn after current one
  98. //void getStackQueue(std::vector<const CStack *> &out, int howMany, int turn = 0, int lastMoved = -1) const; //returns stack in order of their movement action
  99. //void getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<BattleHex> & occupyable, bool flying, const CStack* stackToOmmit = nullptr) const; //send pointer to at least 187 allocated bytes
  100. //static bool isAccessible(BattleHex hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos); //helper for makeBFS
  101. int getAvaliableHex(CreatureID creID, bool attackerOwned, int initialPos = -1) const; //find place for summon / clone effects
  102. //void makeBFS(BattleHex start, bool*accessibility, BattleHex *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const; //*accessibility must be prepared bool[187] array; last two pointers must point to the at least 187-elements int arrays - there is written result
  103. std::pair< std::vector<BattleHex>, int > getPath(BattleHex start, BattleHex dest, const CStack *stack); //returned value: pair<path, length>; length may be different than number of elements in path since flying vreatures jump between distant hexes
  104. //std::vector<BattleHex> getAccessibility(const CStack * stack, bool addOccupiable, std::vector<BattleHex> * attackable = nullptr, bool forPassingBy = false) const; //returns vector of accessible tiles (taking into account the creature range)
  105. //bool isObstacleVisibleForSide(const CObstacleInstance &obstacle, ui8 side) const;
  106. std::shared_ptr<CObstacleInstance> getObstacleOnTile(BattleHex tile) const;
  107. std::set<BattleHex> getStoppers(bool whichSidePerspective) const;
  108. ui32 calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg, CRandomGenerator & rand); //charge - number of hexes travelled before attack (for champion's jousting)
  109. void calculateCasualties(std::map<ui32,si32> *casualties) const; //casualties are array of maps size 2 (attacker, defeneder), maps are (crid => amount)
  110. //void getPotentiallyAttackableHexes(AttackableTiles &at, const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos); //hexes around target that could be attacked in melee
  111. //std::set<CStack*> getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos = BattleHex::INVALID); //calculates range of multi-hex attacks
  112. //std::set<BattleHex> getAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos = BattleHex::INVALID); //calculates range of multi-hex attacks
  113. CStack * generateNewStack(const CStackInstance &base, bool attackerOwned, SlotID slot, BattleHex position) const; //helper for CGameHandler::setupBattle and spells addign new stacks to the battlefield
  114. CStack * generateNewStack(const CStackBasicDescriptor &base, bool attackerOwned, SlotID slot, BattleHex position) const; //helper for CGameHandler::setupBattle and spells addign new stacks to the battlefield
  115. int getIdForNewStack() const; //suggest a currently unused ID that'd suitable for generating a new stack
  116. //std::pair<const CStack *, BattleHex> getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const; //if attackerOwned is indetermnate, returened stack is of any owner; hex is the number of hex we should be looking from; returns (nerarest creature, predecessorHex)
  117. const CGHeroInstance * getHero(PlayerColor player) const; //returns fighting hero that belongs to given player
  118. const CStack * battleGetStack(BattleHex pos, bool onlyAlive); //returns stack at given tile
  119. const CGHeroInstance * battleGetOwner(const CStack * stack) const; //returns hero that owns given stack; nullptr if none
  120. void localInit();
  121. void localInitStack(CStack * s);
  122. static BattleInfo * setupBattle( int3 tile, ETerrainType terrain, BFieldType battlefieldType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town );
  123. //bool hasNativeStack(ui8 side) const;
  124. PlayerColor theOtherPlayer(PlayerColor player) const;
  125. ui8 whatSide(PlayerColor player) const;
  126. static BattlefieldBI::BattlefieldBI battlefieldTypeToBI(BFieldType bfieldType); //converts above to ERM BI format
  127. static int battlefieldTypeToTerrain(int bfieldType); //converts above to ERM BI format
  128. };
  129. class DLL_LINKAGE CStack : public CBonusSystemNode, public CStackBasicDescriptor, public ISpellCaster
  130. {
  131. public:
  132. const CStackInstance *base; //garrison slot from which stack originates (nullptr for war machines, summoned cres, etc)
  133. ui32 ID; //unique ID of stack
  134. ui32 baseAmount;
  135. ui32 firstHPleft; //HP of first creature in stack
  136. PlayerColor owner; //owner - player colour (255 for neutrals)
  137. SlotID slot; //slot - position in garrison (may be 255 for neutrals/called creatures)
  138. bool attackerOwned; //if true, this stack is owned by attakcer (this one from left hand side of battle)
  139. BattleHex position; //position on battlefield; -2 - keep, -3 - lower tower, -4 - upper tower
  140. ///how many times this stack has been counterattacked this round
  141. ui8 counterAttacksPerformed;
  142. ///cached total count of counterattacks; should be cleared each round;do not serialize
  143. mutable ui8 counterAttacksTotalCache;
  144. si16 shots; //how many shots left
  145. ui8 casts; //how many casts left
  146. TQuantity resurrected; // these units will be taken back after battle is over
  147. ///id of alive clone of this stack clone if any
  148. si32 cloneID;
  149. std::set<EBattleStackState::EBattleStackState> state;
  150. //overrides
  151. const CCreature* getCreature() const {return type;}
  152. CStack(const CStackInstance *base, PlayerColor O, int I, bool AO, SlotID S); //c-tor
  153. CStack(const CStackBasicDescriptor *stack, PlayerColor O, int I, bool AO, SlotID S = SlotID(255)); //c-tor
  154. CStack(); //c-tor
  155. ~CStack();
  156. std::string nodeName() const override;
  157. void init(); //set initial (invalid) values
  158. void postInit(); //used to finish initialization when inheriting creature parameters is working
  159. std::string getName() const; //plural or singular
  160. bool willMove(int turn = 0) const; //if stack has remaining move this turn
  161. bool ableToRetaliate() const; //if stack can retaliate after attacked
  162. ///how many times this stack can counterattack in one round
  163. ui8 counterAttacksTotal() const;
  164. ///how many times this stack can counterattack in one round more
  165. si8 counterAttacksRemaining() const;
  166. bool moved(int turn = 0) const; //if stack was already moved this turn
  167. bool waited(int turn = 0) const;
  168. bool canMove(int turn = 0) const; //if stack can move
  169. bool canBeHealed() const; //for first aid tent - only harmed stacks that are not war machines
  170. ///returns actual heal value based on internal state
  171. ui32 calculateHealedHealthPoints(ui32 toHeal, const bool resurrect) const;
  172. ui32 level() const;
  173. si32 magicResistance() const override; //include aura of resistance
  174. static void stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse);
  175. std::vector<si32> activeSpells() const; //returns vector of active spell IDs sorted by time of cast
  176. const CGHeroInstance *getMyHero() const; //if stack belongs to hero (directly or was by him summoned) returns hero, nullptr otherwise
  177. static inline Bonus featureGenerator(Bonus::BonusType type, si16 subtype, si32 value, ui16 turnsRemain, si32 additionalInfo = 0, Bonus::LimitEffect limit = Bonus::NO_LIMIT)
  178. {
  179. Bonus hb = makeFeatureVal(type, Bonus::N_TURNS, subtype, value, Bonus::SPELL_EFFECT, turnsRemain, additionalInfo);
  180. hb.effectRange = limit;
  181. return hb;
  182. }
  183. static bool isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos = BattleHex::INVALID, BattleHex defenderPos = BattleHex::INVALID);
  184. bool doubleWide() const;
  185. BattleHex occupiedHex() const; //returns number of occupied hex (not the position) if stack is double wide; otherwise -1
  186. BattleHex occupiedHex(BattleHex assumedPos) const; //returns number of occupied hex (not the position) if stack is double wide and would stand on assumedPos; otherwise -1
  187. std::vector<BattleHex> getHexes() const; //up to two occupied hexes, starting from front
  188. std::vector<BattleHex> getHexes(BattleHex assumedPos) const; //up to two occupied hexes, starting from front
  189. static std::vector<BattleHex> getHexes(BattleHex assumedPos, bool twoHex, bool AttackerOwned); //up to two occupied hexes, starting from front
  190. bool coversPos(BattleHex position) const; //checks also if unit is double-wide
  191. std::vector<BattleHex> getSurroundingHexes(BattleHex attackerPos = BattleHex::INVALID) const; // get six or 8 surrounding hexes depending on creature size
  192. std::pair<int,int> countKilledByAttack(int damageReceived) const; //returns pair<killed count, new left HP>
  193. void prepareAttacked(BattleStackAttacked &bsa, CRandomGenerator & rand, boost::optional<int> customCount = boost::none) const; //requires bsa.damageAmout filled
  194. ///ISpellCaster
  195. ui8 getSpellSchoolLevel(const CSpell * spell, int *outSelectedSchool = nullptr) const override;
  196. ui32 getSpellBonus(const CSpell * spell, ui32 base, const CStack * affectedStack) const override;
  197. ///default spell school level for effect calculation
  198. int getEffectLevel(const CSpell * spell) const override;
  199. ///default spell-power for damage/heal calculation
  200. int getEffectPower(const CSpell * spell) const override;
  201. ///default spell-power for timed effects duration
  202. int getEnchantPower(const CSpell * spell) const override;
  203. ///damage/heal override(ignores spell configuration, effect level and effect power)
  204. int getEffectValue(const CSpell * spell) const override;
  205. const PlayerColor getOwner() const override;
  206. template <typename Handler> void serialize(Handler &h, const int version)
  207. {
  208. assert(isIndependentNode());
  209. h & static_cast<CBonusSystemNode&>(*this);
  210. h & static_cast<CStackBasicDescriptor&>(*this);
  211. h & ID & baseAmount & firstHPleft & owner & slot & attackerOwned & position & state & counterAttacksPerformed
  212. & shots & casts & count & resurrected;
  213. const CArmedInstance *army = (base ? base->armyObj : nullptr);
  214. SlotID slot = (base ? base->armyObj->findStack(base) : SlotID());
  215. if(h.saving)
  216. {
  217. h & army & slot;
  218. }
  219. else
  220. {
  221. h & army & slot;
  222. if (slot == SlotID::COMMANDER_SLOT_PLACEHOLDER) //TODO
  223. {
  224. auto hero = dynamic_cast<const CGHeroInstance *>(army);
  225. assert (hero);
  226. base = hero->commander;
  227. }
  228. else if(!army || slot == SlotID() || !army->hasStackAtSlot(slot))
  229. {
  230. base = nullptr;
  231. logGlobal->warnStream() << type->nameSing << " doesn't have a base stack!";
  232. }
  233. else
  234. {
  235. base = &army->getStack(slot);
  236. }
  237. }
  238. }
  239. bool alive() const //determines if stack is alive
  240. {
  241. return vstd::contains(state,EBattleStackState::ALIVE);
  242. }
  243. bool idDeadClone() const //determines if stack is alive
  244. {
  245. return vstd::contains(state,EBattleStackState::DEAD_CLONE);
  246. }
  247. bool isValidTarget(bool allowDead = false) const; //alive non-turret stacks (can be attacked or be object of magic effect)
  248. };
  249. class DLL_LINKAGE CMP_stack
  250. {
  251. int phase; //rules of which phase will be used
  252. int turn;
  253. public:
  254. bool operator ()(const CStack* a, const CStack* b);
  255. CMP_stack(int Phase = 1, int Turn = 0);
  256. };