CSpellHandler.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. /*
  2. * CSpellHandler.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 "Magic.h"
  12. #include "../IHandlerBase.h"
  13. #include "../ConstTransitivePtr.h"
  14. #include "../int3.h"
  15. #include "../GameConstants.h"
  16. #include "../battle/BattleHex.h"
  17. #include "../HeroBonus.h"
  18. class CGObjectInstance;
  19. class CSpell;
  20. class ISpellMechanics;
  21. class IAdventureSpellMechanics;
  22. class CLegacyConfigParser;
  23. class CGHeroInstance;
  24. class CStack;
  25. class CBattleInfoCallback;
  26. struct BattleInfo;
  27. struct CPackForClient;
  28. struct BattleSpellCast;
  29. class CGameInfoCallback;
  30. class CRandomGenerator;
  31. class CMap;
  32. struct AdventureSpellCastParameters;
  33. struct BattleSpellCastParameters;
  34. class SpellCastEnvironment;
  35. struct SpellSchoolInfo
  36. {
  37. ESpellSchool id; //backlink
  38. Bonus::BonusType damagePremyBonus;
  39. Bonus::BonusType immunityBonus;
  40. std::string jsonName;
  41. SecondarySkill::ESecondarySkill skill;
  42. Bonus::BonusType knoledgeBonus;
  43. };
  44. enum class VerticalPosition : ui8{TOP, CENTER, BOTTOM};
  45. class DLL_LINKAGE CSpell
  46. {
  47. public:
  48. struct ProjectileInfo
  49. {
  50. ///in radians. Only positive value. Negative angle is handled by vertical flip
  51. double minimumAngle;
  52. ///resource name
  53. std::string resourceName;
  54. template <typename Handler> void serialize(Handler & h, const int version)
  55. {
  56. h & minimumAngle;
  57. h & resourceName;
  58. }
  59. };
  60. struct AnimationItem
  61. {
  62. std::string resourceName;
  63. VerticalPosition verticalPosition;
  64. int pause;
  65. AnimationItem();
  66. template <typename Handler> void serialize(Handler & h, const int version)
  67. {
  68. h & resourceName;
  69. h & verticalPosition;
  70. if(version >= 754) //save format backward compatibility
  71. {
  72. h & pause;
  73. }
  74. else if(!h.saving)
  75. {
  76. pause = 0;
  77. }
  78. }
  79. };
  80. typedef AnimationItem TAnimation;
  81. typedef std::vector<TAnimation> TAnimationQueue;
  82. struct DLL_LINKAGE AnimationInfo
  83. {
  84. AnimationInfo();
  85. ~AnimationInfo();
  86. ///displayed on all affected targets.
  87. TAnimationQueue affect;
  88. ///displayed on caster.
  89. TAnimationQueue cast;
  90. ///displayed on target hex. If spell was cast with no target selection displayed on entire battlefield (f.e. ARMAGEDDON)
  91. TAnimationQueue hit;
  92. ///displayed "between" caster and (first) target. Ignored if spell was cast with no target selection.
  93. ///use selectProjectile to access
  94. std::vector<ProjectileInfo> projectile;
  95. template <typename Handler> void serialize(Handler & h, const int version)
  96. {
  97. h & projectile;
  98. h & hit;
  99. h & cast;
  100. if(version >= 762)
  101. {
  102. h & affect;
  103. }
  104. }
  105. std::string selectProjectile(const double angle) const;
  106. } animationInfo;
  107. public:
  108. struct LevelInfo
  109. {
  110. std::string description; //descriptions of spell for skill level
  111. si32 cost;
  112. si32 power;
  113. si32 AIValue;
  114. bool smartTarget;
  115. bool clearTarget;
  116. bool clearAffected;
  117. std::string range;
  118. std::vector<std::shared_ptr<Bonus>> effects;
  119. std::vector<std::shared_ptr<Bonus>> cumulativeEffects;
  120. LevelInfo();
  121. ~LevelInfo();
  122. template <typename Handler> void serialize(Handler &h, const int version)
  123. {
  124. h & description;
  125. h & cost;
  126. h & power;
  127. h & AIValue;
  128. h & smartTarget;
  129. h & range;
  130. if(version >= 773)
  131. {
  132. h & effects;
  133. h & cumulativeEffects;
  134. }
  135. else
  136. {
  137. //all old effects treated as not cumulative, special cases handled by CSpell::serialize
  138. std::vector<Bonus> old;
  139. h & old;
  140. if(!h.saving)
  141. {
  142. effects.clear();
  143. cumulativeEffects.clear();
  144. for(const Bonus & oldBonus : old)
  145. effects.push_back(std::make_shared<Bonus>(oldBonus));
  146. }
  147. }
  148. h & clearTarget;
  149. h & clearAffected;
  150. }
  151. };
  152. /** \brief Low level accessor. Don`t use it if absolutely necessary
  153. *
  154. * \param level. spell school level
  155. * \return Spell level info structure
  156. *
  157. */
  158. const CSpell::LevelInfo& getLevelInfo(const int level) const;
  159. public:
  160. enum ETargetType {NO_TARGET, CREATURE, OBSTACLE, LOCATION};
  161. enum ESpellPositiveness {NEGATIVE = -1, NEUTRAL = 0, POSITIVE = 1};
  162. struct DLL_LINKAGE TargetInfo
  163. {
  164. ETargetType type;
  165. bool smart;
  166. bool massive;
  167. bool onlyAlive;
  168. ///no immunity on primary target (mostly spell-like attack)
  169. bool alwaysHitDirectly;
  170. bool clearTarget;
  171. bool clearAffected;
  172. TargetInfo(const CSpell * spell, const int level);
  173. TargetInfo(const CSpell * spell, const int level, ECastingMode::ECastingMode mode);
  174. private:
  175. void init(const CSpell * spell, const int level);
  176. };
  177. SpellID id;
  178. std::string identifier;
  179. std::string name;
  180. si32 level;
  181. std::map<ESpellSchool, bool> school;
  182. si32 power; //spell's power
  183. std::map<TFaction, si32> probabilities; //% chance to gain for castles
  184. bool combatSpell; //is this spell combat (true) or adventure (false)
  185. bool creatureAbility; //if true, only creatures can use this spell
  186. si8 positiveness; //1 if spell is positive for influenced stacks, 0 if it is indifferent, -1 if it's negative
  187. std::vector<SpellID> counteredSpells; //spells that are removed when effect of this spell is placed on creature (for bless-curse, haste-slow, and similar pairs)
  188. CSpell();
  189. ~CSpell();
  190. std::vector<BattleHex> rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool * outDroppedHexes = nullptr ) const; //convert range to specific hexes; last optional out parameter is set to true, if spell would cover unavailable hexes (that are not included in ret)
  191. ETargetType getTargetType() const; //deprecated
  192. bool isCombatSpell() const;
  193. bool isAdventureSpell() const;
  194. bool isCreatureAbility() const;
  195. bool isPositive() const;
  196. bool isNegative() const;
  197. bool isNeutral() const;
  198. boost::logic::tribool getPositiveness() const;
  199. bool isDamageSpell() const;
  200. bool isRisingSpell() const;
  201. bool isOffensiveSpell() const;
  202. bool isSpecialSpell() const;
  203. bool hasEffects() const;
  204. void getEffects(std::vector<Bonus> & lst, const int level, const bool cumulative, const si32 duration, boost::optional<si32 *> maxDuration = boost::none) const;
  205. ///calculate spell damage on stack taking caster`s secondary skills and affectedCreature`s bonuses into account
  206. ui32 calculateDamage(const ISpellCaster * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower) const;
  207. ///selects from allStacks actually affected stacks
  208. std::vector<const CStack *> getAffectedStacks(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, const ISpellCaster * caster, int spellLvl, BattleHex destination) const;
  209. si32 getCost(const int skillLevel) const;
  210. /**
  211. * Returns spell level power, base power ignored
  212. */
  213. si32 getPower(const int skillLevel) const;
  214. si32 getProbability(const TFaction factionId) const;
  215. /**
  216. * Calls cb for each school this spell belongs to
  217. *
  218. * Set stop to true to abort looping
  219. */
  220. void forEachSchool(const std::function<void (const SpellSchoolInfo &, bool &)> & cb) const;
  221. /**
  222. * Returns resource name of icon for SPELL_IMMUNITY bonus
  223. */
  224. const std::string& getIconImmune() const;
  225. const std::string& getCastSound() const;
  226. template <typename Handler> void serialize(Handler &h, const int version)
  227. {
  228. h & identifier;
  229. h & id;
  230. h & name;
  231. h & level;
  232. h & power;
  233. h & probabilities;
  234. h & attributes;
  235. h & combatSpell;
  236. h & creatureAbility;
  237. h & positiveness;
  238. h & counteredSpells;
  239. h & isRising;
  240. h & isDamage;
  241. h & isOffensive;
  242. h & targetType;
  243. h & immunities;
  244. h & limiters;
  245. h & absoluteImmunities;
  246. h & absoluteLimiters;
  247. h & iconImmune;
  248. h & defaultProbability;
  249. h & isSpecial;
  250. h & castSound;
  251. h & iconBook;
  252. h & iconEffect;
  253. h & iconScenarioBonus;
  254. h & iconScroll;
  255. h & levels;
  256. h & school;
  257. h & animationInfo;
  258. if(!h.saving)
  259. {
  260. setup();
  261. }
  262. //backward compatibility
  263. //can not be added to level structure as level structure does not know spell id
  264. if(!h.saving && version < 773)
  265. {
  266. if(id == SpellID::DISRUPTING_RAY || id == SpellID::ACID_BREATH_DEFENSE)
  267. for(auto & level : levels)
  268. std::swap(level.effects, level.cumulativeEffects);
  269. }
  270. }
  271. friend class CSpellHandler;
  272. friend class Graphics;
  273. public:
  274. ///internal interface (for callbacks)
  275. ///Checks general but spell-specific problems. Use only during battle.
  276. ESpellCastProblem::ESpellCastProblem canBeCast(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, const ISpellCaster * caster) const;
  277. ///checks for creature immunity / anything that prevent casting *at given hex*
  278. ESpellCastProblem::ESpellCastProblem canBeCastAt(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, const ISpellCaster * caster, BattleHex destination) const;
  279. ///checks for creature immunity / anything that prevent casting *at given target* - doesn't take into account general problems such as not having spellbook or mana points etc.
  280. ESpellCastProblem::ESpellCastProblem isImmuneByStack(const ISpellCaster * caster, const CStack * obj) const;
  281. public:
  282. ///Server logic. Has write access to GameState via packets.
  283. ///May be executed on client side by (future) non-cheat-proof scripts.
  284. bool adventureCast(const SpellCastEnvironment * env, const AdventureSpellCastParameters & parameters) const;
  285. void battleCast(const SpellCastEnvironment * env, const BattleSpellCastParameters & parameters) const;
  286. public:
  287. ///Client-server logic. Has direct write access to GameState.
  288. ///Shall be called (only) when applying packets on BOTH SIDES
  289. ///implementation of BattleSpellCast applying
  290. void applyBattle(BattleInfo * battle, const BattleSpellCast * packet) const;
  291. public://internal, for use only by Mechanics classes
  292. ///applies caster`s secondary skills and affectedCreature`s to raw damage
  293. int adjustRawDamage(const ISpellCaster * caster, const CStack * affectedCreature, int rawDamage) const;
  294. ///returns raw damage or healed HP
  295. int calculateRawEffectValue(int effectLevel, int effectPower) const;
  296. ///generic immunity calculation
  297. ESpellCastProblem::ESpellCastProblem internalIsImmune(const ISpellCaster * caster, const CStack *obj) const;
  298. private:
  299. void setIsOffensive(const bool val);
  300. void setIsRising(const bool val);
  301. //call this after load or deserialization. cant be done in constructor.
  302. void setup();
  303. void setupMechanics();
  304. private:
  305. si32 defaultProbability;
  306. bool isRising;
  307. bool isDamage;
  308. bool isOffensive;
  309. bool isSpecial;
  310. std::string attributes; //reference only attributes //todo: remove or include in configuration format, currently unused
  311. ETargetType targetType;
  312. std::vector<Bonus::BonusType> immunities; //any of these grants immunity
  313. std::vector<Bonus::BonusType> absoluteImmunities; //any of these grants immunity, can't be negated
  314. std::vector<Bonus::BonusType> limiters; //all of them are required to be affected
  315. std::vector<Bonus::BonusType> absoluteLimiters; //all of them are required to be affected, can't be negated
  316. ///graphics related stuff
  317. std::string iconImmune;
  318. std::string iconBook;
  319. std::string iconEffect;
  320. std::string iconScenarioBonus;
  321. std::string iconScroll;
  322. ///sound related stuff
  323. std::string castSound;
  324. std::vector<LevelInfo> levels;
  325. std::unique_ptr<ISpellMechanics> mechanics;//(!) do not serialize
  326. std::unique_ptr<IAdventureSpellMechanics> adventureMechanics;//(!) do not serialize
  327. };
  328. bool DLL_LINKAGE isInScreenRange(const int3 &center, const int3 &pos); //for spells like Dimension Door
  329. class DLL_LINKAGE CSpellHandler: public CHandlerBase<SpellID, CSpell>
  330. {
  331. public:
  332. CSpellHandler();
  333. virtual ~CSpellHandler();
  334. ///IHandler base
  335. std::vector<JsonNode> loadLegacyData(size_t dataSize) override;
  336. void afterLoadFinalization() override;
  337. void beforeValidate(JsonNode & object) override;
  338. /**
  339. * Gets a list of default allowed spells. OH3 spells are all allowed by default.
  340. *
  341. * @return a list of allowed spells, the index is the spell id and the value either 0 for not allowed or 1 for allowed
  342. */
  343. std::vector<bool> getDefaultAllowed() const override;
  344. const std::string getTypeName() const override;
  345. ///json serialization helper
  346. static si32 decodeSpell(const std::string & identifier);
  347. ///json serialization helper
  348. static std::string encodeSpell(const si32 index);
  349. template <typename Handler> void serialize(Handler &h, const int version)
  350. {
  351. h & objects ;
  352. }
  353. protected:
  354. CSpell * loadFromJson(const JsonNode & json, const std::string & identifier) override;
  355. };