HeroBonus.h 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. /*
  2. * HeroBonus.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 "GameConstants.h"
  12. #include "JsonNode.h"
  13. class CCreature;
  14. struct Bonus;
  15. class IBonusBearer;
  16. class CBonusSystemNode;
  17. class ILimiter;
  18. class IPropagator;
  19. class IUpdater;
  20. class BonusList;
  21. typedef std::shared_ptr<BonusList> TBonusListPtr;
  22. typedef std::shared_ptr<const BonusList> TConstBonusListPtr;
  23. typedef std::shared_ptr<ILimiter> TLimiterPtr;
  24. typedef std::shared_ptr<IPropagator> TPropagatorPtr;
  25. typedef std::shared_ptr<IUpdater> TUpdaterPtr;
  26. typedef std::set<CBonusSystemNode*> TNodes;
  27. typedef std::set<const CBonusSystemNode*> TCNodes;
  28. typedef std::vector<CBonusSystemNode *> TNodesVector;
  29. class CSelector : std::function<bool(const Bonus*)>
  30. {
  31. typedef std::function<bool(const Bonus*)> TBase;
  32. public:
  33. CSelector() {}
  34. template<typename T>
  35. CSelector(const T &t, //SFINAE trick -> include this c-tor in overload resolution only if parameter is class
  36. //(includes functors, lambdas) or function. Without that VC is going mad about ambiguities.
  37. typename std::enable_if < boost::mpl::or_ < std::is_class<T>, std::is_function<T >> ::value>::type *dummy = nullptr)
  38. : TBase(t)
  39. {}
  40. CSelector(std::nullptr_t)
  41. {}
  42. CSelector And(CSelector rhs) const
  43. {
  44. //lambda may likely outlive "this" (it can be even a temporary) => we copy the OBJECT (not pointer)
  45. auto thisCopy = *this;
  46. return [thisCopy, rhs](const Bonus *b) mutable { return thisCopy(b) && rhs(b); };
  47. }
  48. CSelector Or(CSelector rhs) const
  49. {
  50. auto thisCopy = *this;
  51. return [thisCopy, rhs](const Bonus *b) mutable { return thisCopy(b) || rhs(b); };
  52. }
  53. CSelector Not() const
  54. {
  55. auto thisCopy = *this;
  56. return [thisCopy](const Bonus *b) mutable { return !thisCopy(b); };
  57. }
  58. bool operator()(const Bonus *b) const
  59. {
  60. return TBase::operator()(b);
  61. }
  62. operator bool() const
  63. {
  64. return !!static_cast<const TBase&>(*this);
  65. }
  66. };
  67. class DLL_LINKAGE CBonusProxy
  68. {
  69. public:
  70. CBonusProxy(const IBonusBearer * Target, CSelector Selector);
  71. CBonusProxy(const CBonusProxy & other);
  72. CBonusProxy(CBonusProxy && other);
  73. CBonusProxy & operator=(CBonusProxy && other);
  74. CBonusProxy & operator=(const CBonusProxy & other);
  75. const BonusList * operator->() const;
  76. TConstBonusListPtr getBonusList() const;
  77. protected:
  78. CSelector selector;
  79. const IBonusBearer * target;
  80. mutable int64_t bonusListCachedLast;
  81. mutable TConstBonusListPtr bonusList;
  82. };
  83. class DLL_LINKAGE CTotalsProxy : public CBonusProxy
  84. {
  85. public:
  86. CTotalsProxy(const IBonusBearer * Target, CSelector Selector, int InitialValue);
  87. CTotalsProxy(const CTotalsProxy & other);
  88. CTotalsProxy(CTotalsProxy && other) = delete;
  89. CTotalsProxy & operator=(const CTotalsProxy & other);
  90. CTotalsProxy & operator=(CTotalsProxy && other) = delete;
  91. int getMeleeValue() const;
  92. int getRangedValue() const;
  93. int getValue() const;
  94. /**
  95. Returns total value of all selected bonuses and sets bonusList as a pointer to the list of selected bonuses
  96. @param bonusList is the out list of all selected bonuses
  97. @return total value of all selected bonuses and 0 otherwise
  98. */
  99. int getValueAndList(TConstBonusListPtr & bonusList) const;
  100. private:
  101. int initialValue;
  102. mutable int64_t valueCachedLast;
  103. mutable int value;
  104. mutable int64_t meleeCachedLast;
  105. mutable int meleeValue;
  106. mutable int64_t rangedCachedLast;
  107. mutable int rangedValue;
  108. };
  109. class DLL_LINKAGE CCheckProxy
  110. {
  111. public:
  112. CCheckProxy(const IBonusBearer * Target, CSelector Selector);
  113. CCheckProxy(const CCheckProxy & other);
  114. bool getHasBonus() const;
  115. private:
  116. const IBonusBearer * target;
  117. CSelector selector;
  118. mutable int64_t cachedLast;
  119. mutable bool hasBonus;
  120. };
  121. class DLL_LINKAGE CAddInfo : public std::vector<si32>
  122. {
  123. public:
  124. enum { NONE = -1 };
  125. CAddInfo();
  126. CAddInfo(si32 value);
  127. bool operator==(si32 value) const;
  128. bool operator!=(si32 value) const;
  129. si32 & operator[](size_type pos);
  130. si32 operator[](size_type pos) const;
  131. std::string toString() const;
  132. JsonNode toJsonNode() const;
  133. };
  134. #define BONUS_TREE_DESERIALIZATION_FIX if(!h.saving && h.smartPointerSerialization) deserializationFix();
  135. #define BONUS_LIST \
  136. BONUS_NAME(NONE) \
  137. BONUS_NAME(LEVEL_COUNTER) /* for commander artifacts*/ \
  138. BONUS_NAME(MOVEMENT) /*both water/land*/ \
  139. BONUS_NAME(LAND_MOVEMENT) \
  140. BONUS_NAME(SEA_MOVEMENT) \
  141. BONUS_NAME(MORALE) \
  142. BONUS_NAME(LUCK) \
  143. BONUS_NAME(PRIMARY_SKILL) /*uses subtype to pick skill; additional info if set: 1 - only melee, 2 - only distance*/ \
  144. BONUS_NAME(SIGHT_RADIOUS) /*the correct word is RADIUS, but this one's already used in mods */\
  145. BONUS_NAME(MANA_REGENERATION) /*points per turn apart from normal (1 + mysticism)*/ \
  146. BONUS_NAME(FULL_MANA_REGENERATION) /*all mana points are replenished every day*/ \
  147. BONUS_NAME(NONEVIL_ALIGNMENT_MIX) /*good and neutral creatures can be mixed without morale penalty*/ \
  148. BONUS_NAME(SECONDARY_SKILL_PREMY) /*%*/ \
  149. BONUS_NAME(SURRENDER_DISCOUNT) /*%*/ \
  150. BONUS_NAME(STACKS_SPEED) /*additional info - percent of speed bonus applied after direct bonuses; >0 - added, <0 - subtracted to this part*/ \
  151. BONUS_NAME(FLYING_MOVEMENT) /*value - penalty percentage*/ \
  152. BONUS_NAME(SPELL_DURATION) \
  153. BONUS_NAME(AIR_SPELL_DMG_PREMY) \
  154. BONUS_NAME(EARTH_SPELL_DMG_PREMY) \
  155. BONUS_NAME(FIRE_SPELL_DMG_PREMY) \
  156. BONUS_NAME(WATER_SPELL_DMG_PREMY) \
  157. BONUS_NAME(WATER_WALKING) /*value - penalty percentage*/ \
  158. BONUS_NAME(NEGATE_ALL_NATURAL_IMMUNITIES) \
  159. BONUS_NAME(STACK_HEALTH) \
  160. BONUS_NAME(BLOCK_MORALE) \
  161. BONUS_NAME(BLOCK_LUCK) \
  162. BONUS_NAME(FIRE_SPELLS) \
  163. BONUS_NAME(AIR_SPELLS) \
  164. BONUS_NAME(WATER_SPELLS) \
  165. BONUS_NAME(EARTH_SPELLS) \
  166. BONUS_NAME(GENERATE_RESOURCE) /*daily value, uses subtype (resource type)*/ \
  167. BONUS_NAME(CREATURE_GROWTH) /*for legion artifacts: value - week growth bonus, subtype - monster level if aplicable*/ \
  168. BONUS_NAME(WHIRLPOOL_PROTECTION) /*hero won't lose army when teleporting through whirlpool*/ \
  169. BONUS_NAME(SPELL) /*hero knows spell, val - skill level (0 - 3), subtype - spell id*/ \
  170. BONUS_NAME(SPELLS_OF_LEVEL) /*hero knows all spells of given level, val - skill level; subtype - level*/ \
  171. BONUS_NAME(BATTLE_NO_FLEEING) /*for shackles of war*/ \
  172. BONUS_NAME(MAGIC_SCHOOL_SKILL) /* //eg. for magic plains terrain, subtype: school of magic (0 - all, 1 - fire, 2 - air, 4 - water, 8 - earth), value - level*/ \
  173. BONUS_NAME(FREE_SHOOTING) /*stacks can shoot even if otherwise blocked (sharpshooter's bow effect)*/ \
  174. BONUS_NAME(OPENING_BATTLE_SPELL) /*casts a spell at expert level at beginning of battle, val - spell power, subtype - spell id*/ \
  175. BONUS_NAME(IMPROVED_NECROMANCY) /* raise more powerful creatures: subtype - creature type raised, addInfo - [required necromancy level, required stack level] */ \
  176. BONUS_NAME(CREATURE_GROWTH_PERCENT) /*increases growth of all units in all towns, val - percentage*/ \
  177. BONUS_NAME(FREE_SHIP_BOARDING) /*movement points preserved with ship boarding and landing*/ \
  178. BONUS_NAME(NO_TYPE) \
  179. BONUS_NAME(FLYING) \
  180. BONUS_NAME(SHOOTER) \
  181. BONUS_NAME(CHARGE_IMMUNITY) \
  182. BONUS_NAME(ADDITIONAL_ATTACK) \
  183. BONUS_NAME(UNLIMITED_RETALIATIONS) \
  184. BONUS_NAME(NO_MELEE_PENALTY) \
  185. BONUS_NAME(JOUSTING) /*for champions*/ \
  186. BONUS_NAME(HATE) /*eg. angels hate devils, subtype - ID of hated creature, val - damage bonus percent */ \
  187. BONUS_NAME(KING1) \
  188. BONUS_NAME(KING2) \
  189. BONUS_NAME(KING3) \
  190. BONUS_NAME(MAGIC_RESISTANCE) /*in % (value)*/ \
  191. BONUS_NAME(CHANGES_SPELL_COST_FOR_ALLY) /*in mana points (value) , eg. mage*/ \
  192. BONUS_NAME(CHANGES_SPELL_COST_FOR_ENEMY) /*in mana points (value) , eg. pegasus */ \
  193. BONUS_NAME(SPELL_AFTER_ATTACK) /* subtype - spell id, value - chance %, addInfo[0] - level, addInfo[1] -> [0 - all attacks, 1 - shot only, 2 - melee only] */ \
  194. BONUS_NAME(SPELL_BEFORE_ATTACK) /* subtype - spell id, value - chance %, addInfo[0] - level, addInfo[1] -> [0 - all attacks, 1 - shot only, 2 - melee only] */ \
  195. BONUS_NAME(SPELL_RESISTANCE_AURA) /*eg. unicorns, value - resistance bonus in % for adjacent creatures*/ \
  196. BONUS_NAME(LEVEL_SPELL_IMMUNITY) /*creature is immune to all spell with level below or equal to value of this bonus */ \
  197. BONUS_NAME(BLOCK_MAGIC_ABOVE) /*blocks casting spells of the level > value */ \
  198. BONUS_NAME(BLOCK_ALL_MAGIC) /*blocks casting spells*/ \
  199. BONUS_NAME(TWO_HEX_ATTACK_BREATH) /*eg. dragons*/ \
  200. BONUS_NAME(SPELL_DAMAGE_REDUCTION) /*eg. golems; value - reduction in %, subtype - spell school; -1 - all, 0 - air, 1 - fire, 2 - water, 3 - earth*/ \
  201. BONUS_NAME(NO_WALL_PENALTY) \
  202. BONUS_NAME(NON_LIVING) /*eg. golems, cannot be rised or healed, only neutral morale */ \
  203. BONUS_NAME(RANDOM_SPELLCASTER) /*eg. master genie, val - level*/ \
  204. BONUS_NAME(BLOCKS_RETALIATION) /*eg. naga*/ \
  205. BONUS_NAME(SPELL_IMMUNITY) /*subid - spell id*/ \
  206. BONUS_NAME(MANA_CHANNELING) /*value in %, eg. familiar*/ \
  207. BONUS_NAME(SPELL_LIKE_ATTACK) /*subtype - spell, value - spell level; range is taken from spell, but damage from creature; eg. magog*/ \
  208. BONUS_NAME(THREE_HEADED_ATTACK) /*eg. cerberus*/ \
  209. BONUS_NAME(DAEMON_SUMMONING) /*pit lord, subtype - type of creatures, val - hp per unit*/ \
  210. BONUS_NAME(FIRE_IMMUNITY) /*subtype 0 - all, 1 - all except positive, 2 - only damage spells*/ \
  211. BONUS_NAME(WATER_IMMUNITY) \
  212. BONUS_NAME(EARTH_IMMUNITY) \
  213. BONUS_NAME(AIR_IMMUNITY) \
  214. BONUS_NAME(MIND_IMMUNITY) \
  215. BONUS_NAME(FIRE_SHIELD) \
  216. BONUS_NAME(UNDEAD) \
  217. BONUS_NAME(HP_REGENERATION) /*creature regenerates val HP every new round*/ \
  218. BONUS_NAME(FULL_HP_REGENERATION) /*first creature regenerates all HP every new round; subtype 0 - animation 4 (trolllike), 1 - animation 47 (wightlike)*/ \
  219. BONUS_NAME(MANA_DRAIN) /*value - spell points per turn*/ \
  220. BONUS_NAME(LIFE_DRAIN) \
  221. BONUS_NAME(DOUBLE_DAMAGE_CHANCE) /*value in %, eg. dread knight*/ \
  222. BONUS_NAME(RETURN_AFTER_STRIKE) \
  223. BONUS_NAME(SELF_MORALE) /*eg. minotaur*/ \
  224. BONUS_NAME(SPELLCASTER) /*subtype - spell id, value - level of school, additional info - weighted chance. use SPECIFIC_SPELL_POWER, CREATURE_SPELL_POWER or CREATURE_ENCHANT_POWER for calculating the power*/ \
  225. BONUS_NAME(CATAPULT) \
  226. BONUS_NAME(ENEMY_DEFENCE_REDUCTION) /*in % (value) eg. behemots*/ \
  227. BONUS_NAME(GENERAL_DAMAGE_REDUCTION) /* shield / air shield effect */ \
  228. BONUS_NAME(GENERAL_ATTACK_REDUCTION) /*eg. while stoned or blinded - in %,// subtype not used, use ONLY_MELEE_FIGHT / DISTANCE_FIGHT*/ \
  229. BONUS_NAME(DEFENSIVE_STANCE) /* val - bonus to defense while defending */ \
  230. BONUS_NAME(ATTACKS_ALL_ADJACENT) /*eg. hydra*/ \
  231. BONUS_NAME(MORE_DAMAGE_FROM_SPELL) /*value - damage increase in %, subtype - spell id*/ \
  232. BONUS_NAME(FEAR) \
  233. BONUS_NAME(FEARLESS) \
  234. BONUS_NAME(NO_DISTANCE_PENALTY) \
  235. BONUS_NAME(SELF_LUCK) /*halfling*/ \
  236. BONUS_NAME(ENCHANTER)/* for Enchanter spells, val - skill level, subtype - spell id, additionalInfo - cooldown */ \
  237. BONUS_NAME(HEALER) \
  238. BONUS_NAME(SIEGE_WEAPON) \
  239. BONUS_NAME(HYPNOTIZED) \
  240. BONUS_NAME(NO_RETALIATION) /*temporary bonus for basilisk, unicorn and scorpicore paralyze*/\
  241. BONUS_NAME(ADDITIONAL_RETALIATION) /*value - number of additional retaliations*/ \
  242. BONUS_NAME(MAGIC_MIRROR) /* value - chance of redirecting in %*/ \
  243. BONUS_NAME(ALWAYS_MINIMUM_DAMAGE) /*unit does its minimum damage from range; subtype: -1 - any attack, 0 - melee, 1 - ranged, value: additional damage penalty (it'll subtracted from dmg), additional info - multiplicative anti-bonus for dmg in % [eg 20 means that creature will inflict 80% of normal minimal dmg]*/ \
  244. BONUS_NAME(ALWAYS_MAXIMUM_DAMAGE) /*eg. bless effect, subtype: -1 - any attack, 0 - melee, 1 - ranged, value: additional damage, additional info - multiplicative bonus for dmg in %*/ \
  245. BONUS_NAME(ATTACKS_NEAREST_CREATURE) /*while in berserk*/ \
  246. BONUS_NAME(IN_FRENZY) /*value - level*/ \
  247. BONUS_NAME(SLAYER) /*value - level*/ \
  248. BONUS_NAME(FORGETFULL) /*forgetfulness spell effect, value - level*/ \
  249. BONUS_NAME(NOT_ACTIVE) /* subtype - spell ID (paralyze, blind, stone gaze) for graphical effect*/ \
  250. BONUS_NAME(NO_LUCK) /*eg. when fighting on cursed ground*/ \
  251. BONUS_NAME(NO_MORALE) /*eg. when fighting on cursed ground*/ \
  252. BONUS_NAME(DARKNESS) /*val = radius */ \
  253. BONUS_NAME(SPECIAL_SECONDARY_SKILL) /*subtype = id, val = value per level in percent*/ \
  254. BONUS_NAME(SPECIAL_SPELL_LEV) /*subtype = id, val = value per level in percent*/\
  255. BONUS_NAME(SPELL_DAMAGE) /*val = value*/\
  256. BONUS_NAME(SPECIFIC_SPELL_DAMAGE) /*subtype = id of spell, val = value*/\
  257. BONUS_NAME(SPECIAL_BLESS_DAMAGE) /*val = spell (bless), additionalInfo = value per level in percent*/\
  258. BONUS_NAME(MAXED_SPELL) /*val = id*/\
  259. BONUS_NAME(SPECIAL_PECULIAR_ENCHANT) /*blesses and curses with id = val dependent on unit's level, subtype = 0 or 1 for Coronius*/\
  260. BONUS_NAME(SPECIAL_UPGRADE) /*subtype = base, additionalInfo = target */\
  261. BONUS_NAME(DRAGON_NATURE) \
  262. BONUS_NAME(CREATURE_DAMAGE)/*subtype 0 = both, 1 = min, 2 = max*/\
  263. BONUS_NAME(EXP_MULTIPLIER)/* val - percent of additional exp gained by stack/commander (base value 100)*/\
  264. BONUS_NAME(SHOTS)\
  265. BONUS_NAME(DEATH_STARE) /*subtype 0 - gorgon, 1 - commander*/\
  266. BONUS_NAME(POISON) /*val - max health penalty from poison possible*/\
  267. BONUS_NAME(BIND_EFFECT) /*doesn't do anything particular, works as a marker)*/\
  268. BONUS_NAME(ACID_BREATH) /*additional val damage per creature after attack, additional info - chance in percent*/\
  269. BONUS_NAME(RECEPTIVE) /*accepts friendly spells even with immunity*/\
  270. BONUS_NAME(DIRECT_DAMAGE_IMMUNITY) /*direct damage spells, that is*/\
  271. BONUS_NAME(CASTS) /*how many times creature can cast activated spell*/ \
  272. BONUS_NAME(SPECIFIC_SPELL_POWER) /* value used for Thunderbolt and Resurrection cast by units, subtype - spell id */\
  273. BONUS_NAME(CREATURE_SPELL_POWER) /* value per unit, divided by 100 (so faerie Dragons have 800)*/ \
  274. BONUS_NAME(CREATURE_ENCHANT_POWER) /* total duration of spells cast by creature */ \
  275. BONUS_NAME(ENCHANTED) /* permanently enchanted with spell subID of level = val, if val > 3 then spell is mass and has level of val-3*/ \
  276. BONUS_NAME(REBIRTH) /* val - percent of life restored, subtype = 0 - regular, 1 - at least one unit (sacred Phoenix) */\
  277. BONUS_NAME(ADDITIONAL_UNITS) /*val of units with id = subtype will be added to hero's army at the beginning of battle */\
  278. BONUS_NAME(SPOILS_OF_WAR) /*val * 10^-6 * gained exp resources of subtype will be given to hero after battle*/\
  279. BONUS_NAME(BLOCK)\
  280. BONUS_NAME(DISGUISED) /* subtype - spell level */\
  281. BONUS_NAME(VISIONS) /* subtype - spell level */\
  282. BONUS_NAME(NO_TERRAIN_PENALTY) /* subtype - terrain type */\
  283. BONUS_NAME(SOUL_STEAL) /*val - number of units gained per enemy killed, subtype = 0 - gained units survive after battle, 1 - they do not*/ \
  284. BONUS_NAME(TRANSMUTATION) /*val - chance to trigger in %, subtype = 0 - resurrection based on HP, 1 - based on unit count, additional info - target creature ID (attacker default)*/\
  285. BONUS_NAME(SUMMON_GUARDIANS) /*val - amount in % of stack count, subtype = creature ID*/\
  286. BONUS_NAME(CATAPULT_EXTRA_SHOTS) /*val - number of additional shots, requires CATAPULT bonus to work*/\
  287. BONUS_NAME(RANGED_RETALIATION) /*allows shooters to perform ranged retaliation*/\
  288. BONUS_NAME(BLOCKS_RANGED_RETALIATION) /*disallows ranged retaliation for shooter unit, BLOCKS_RETALIATION bonus is for melee retaliation only*/\
  289. BONUS_NAME(SECONDARY_SKILL_VAL2) /*for secondary skills that have multiple effects, like eagle eye (max level and chance)*/ \
  290. BONUS_NAME(MANUAL_CONTROL) /* manually control warmachine with id = subtype, chance = val */ \
  291. BONUS_NAME(WIDE_BREATH) /* initial desigh: dragon breath affecting multiple nearby hexes */\
  292. BONUS_NAME(FIRST_STRIKE) /* first counterattack, then attack if possible */\
  293. BONUS_NAME(SYNERGY_TARGET) /* dummy skill for alternative upgrades mod */\
  294. BONUS_NAME(SHOOTS_ALL_ADJACENT) /* H4 Cyclops-like shoot (attacks all hexes neighboring with target) without spell-like mechanics */\
  295. BONUS_NAME(BLOCK_MAGIC_BELOW) /*blocks casting spells of the level < value */ \
  296. BONUS_NAME(DESTRUCTION) /*kills extra units after hit, subtype = 0 - kill percentage of units, 1 - kill amount, val = chance in percent to trigger, additional info - amount/percentage to kill*/ \
  297. BONUS_NAME(SPECIAL_CRYSTAL_GENERATION) /*crystal dragon crystal generation*/ \
  298. BONUS_NAME(NO_SPELLCAST_BY_DEFAULT) /*spellcast will not be default attack option for this creature*/ \
  299. BONUS_NAME(GARGOYLE) /* gargoyle is special than NON_LIVING, cannot be rised or healed */ \
  300. BONUS_NAME(SPECIAL_ADD_VALUE_ENCHANT) /*specialty spell like Aenin has, increased effect of spell, additionalInfo = value to add*/\
  301. BONUS_NAME(SPECIAL_FIXED_VALUE_ENCHANT) /*specialty spell like Melody has, constant spell effect (i.e. 3 luck), additionalInfo = value to fix.*/\
  302. BONUS_NAME(TOWN_MAGIC_WELL) /*one-time pseudo-bonus to implement Magic Well in the town*/ \
  303. /* end of list */
  304. #define BONUS_SOURCE_LIST \
  305. BONUS_SOURCE(ARTIFACT)\
  306. BONUS_SOURCE(ARTIFACT_INSTANCE)\
  307. BONUS_SOURCE(OBJECT)\
  308. BONUS_SOURCE(CREATURE_ABILITY)\
  309. BONUS_SOURCE(TERRAIN_NATIVE)\
  310. BONUS_SOURCE(TERRAIN_OVERLAY)\
  311. BONUS_SOURCE(SPELL_EFFECT)\
  312. BONUS_SOURCE(TOWN_STRUCTURE)\
  313. BONUS_SOURCE(HERO_BASE_SKILL)\
  314. BONUS_SOURCE(SECONDARY_SKILL)\
  315. BONUS_SOURCE(HERO_SPECIAL)\
  316. BONUS_SOURCE(ARMY)\
  317. BONUS_SOURCE(CAMPAIGN_BONUS)\
  318. BONUS_SOURCE(SPECIAL_WEEK)\
  319. BONUS_SOURCE(STACK_EXPERIENCE)\
  320. BONUS_SOURCE(COMMANDER) /*TODO: consider using simply STACK_INSTANCE */\
  321. BONUS_SOURCE(OTHER) /*used for defensive stance and default value of spell level limit*/
  322. #define BONUS_VALUE_LIST \
  323. BONUS_VALUE(ADDITIVE_VALUE)\
  324. BONUS_VALUE(BASE_NUMBER)\
  325. BONUS_VALUE(PERCENT_TO_ALL)\
  326. BONUS_VALUE(PERCENT_TO_BASE)\
  327. BONUS_VALUE(INDEPENDENT_MAX) /*used for SPELL bonus */\
  328. BONUS_VALUE(INDEPENDENT_MIN) //used for SECONDARY_SKILL_PREMY bonus
  329. /// Struct for handling bonuses of several types. Can be transferred to any hero
  330. struct DLL_LINKAGE Bonus : public std::enable_shared_from_this<Bonus>
  331. {
  332. enum { EVERY_TYPE = -1 };
  333. enum BonusType
  334. {
  335. #define BONUS_NAME(x) x,
  336. BONUS_LIST
  337. #undef BONUS_NAME
  338. };
  339. enum BonusDuration //when bonus is automatically removed
  340. {
  341. PERMANENT = 1,
  342. ONE_BATTLE = 2, //at the end of battle
  343. ONE_DAY = 4, //at the end of day
  344. ONE_WEEK = 8, //at the end of week (bonus lasts till the end of week, thats NOT 7 days
  345. N_TURNS = 16, //used during battles, after battle bonus is always removed
  346. N_DAYS = 32,
  347. UNTIL_BEING_ATTACKED = 64, /*removed after attack and counterattacks are performed*/
  348. UNTIL_ATTACK = 128, /*removed after attack and counterattacks are performed*/
  349. STACK_GETS_TURN = 256, /*removed when stack gets its turn - used for defensive stance*/
  350. COMMANDER_KILLED = 512
  351. };
  352. enum BonusSource
  353. {
  354. #define BONUS_SOURCE(x) x,
  355. BONUS_SOURCE_LIST
  356. #undef BONUS_SOURCE
  357. };
  358. enum LimitEffect
  359. {
  360. NO_LIMIT = 0,
  361. ONLY_DISTANCE_FIGHT=1, ONLY_MELEE_FIGHT, //used to mark bonuses for attack/defense primary skills from spells like Precision (distance only)
  362. ONLY_ENEMY_ARMY
  363. };
  364. enum ValueType
  365. {
  366. #define BONUS_VALUE(x) x,
  367. BONUS_VALUE_LIST
  368. #undef BONUS_VALUE
  369. };
  370. ui16 duration; //uses BonusDuration values
  371. si16 turnsRemain; //used if duration is N_TURNS, N_DAYS or ONE_WEEK
  372. BonusType type; //uses BonusType values - says to what is this bonus - 1 byte
  373. TBonusSubtype subtype; //-1 if not applicable - 4 bytes
  374. BonusSource source;//source type" uses BonusSource values - what gave that bonus
  375. si32 val;
  376. ui32 sid; //source id: id of object/artifact/spell
  377. ValueType valType;
  378. std::string stacking; // bonuses with the same stacking value don't stack (e.g. Angel/Archangel morale bonus)
  379. CAddInfo additionalInfo;
  380. LimitEffect effectRange; //if not NO_LIMIT, bonus will be omitted by default
  381. TLimiterPtr limiter;
  382. TPropagatorPtr propagator;
  383. TUpdaterPtr updater;
  384. std::string description;
  385. Bonus(BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype=-1);
  386. Bonus(BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype=-1, ValueType ValType = ADDITIVE_VALUE);
  387. Bonus();
  388. template <typename Handler> void serialize(Handler &h, const int version)
  389. {
  390. h & duration;
  391. h & type;
  392. h & subtype;
  393. h & source;
  394. h & val;
  395. h & sid;
  396. h & description;
  397. if(version >= 783)
  398. {
  399. h & additionalInfo;
  400. }
  401. else
  402. {
  403. additionalInfo.resize(1, -1);
  404. h & additionalInfo[0];
  405. }
  406. h & turnsRemain;
  407. h & valType;
  408. if(version >= 784)
  409. {
  410. h & stacking;
  411. }
  412. h & effectRange;
  413. h & limiter;
  414. h & propagator;
  415. if(version >= 781)
  416. {
  417. h & updater;
  418. }
  419. }
  420. template <typename Ptr>
  421. static bool compareByAdditionalInfo(const Ptr& a, const Ptr& b)
  422. {
  423. return a->additionalInfo < b->additionalInfo;
  424. }
  425. static bool NDays(const Bonus *hb)
  426. {
  427. return hb->duration & Bonus::N_DAYS;
  428. }
  429. static bool NTurns(const Bonus *hb)
  430. {
  431. return hb->duration & Bonus::N_TURNS;
  432. }
  433. static bool OneDay(const Bonus *hb)
  434. {
  435. return hb->duration & Bonus::ONE_DAY;
  436. }
  437. static bool OneWeek(const Bonus *hb)
  438. {
  439. return hb->duration & Bonus::ONE_WEEK;
  440. }
  441. static bool OneBattle(const Bonus *hb)
  442. {
  443. return hb->duration & Bonus::ONE_BATTLE;
  444. }
  445. static bool Permanent(const Bonus *hb)
  446. {
  447. return hb->duration & Bonus::PERMANENT;
  448. }
  449. static bool UntilGetsTurn(const Bonus *hb)
  450. {
  451. return hb->duration & Bonus::STACK_GETS_TURN;
  452. }
  453. static bool UntilAttack(const Bonus *hb)
  454. {
  455. return hb->duration & Bonus::UNTIL_ATTACK;
  456. }
  457. static bool UntilBeingAttacked(const Bonus *hb)
  458. {
  459. return hb->duration & Bonus::UNTIL_BEING_ATTACKED;
  460. }
  461. static bool UntilCommanderKilled(const Bonus *hb)
  462. {
  463. return hb->duration & Bonus::COMMANDER_KILLED;
  464. }
  465. inline bool operator == (const BonusType & cf) const
  466. {
  467. return type == cf;
  468. }
  469. inline void operator += (const ui32 Val) //no return
  470. {
  471. val += Val;
  472. }
  473. STRONG_INLINE static ui32 getSid32(ui32 high, ui32 low)
  474. {
  475. return (high << 16) + low;
  476. }
  477. std::string Description() const;
  478. JsonNode toJsonNode() const;
  479. std::string nameForBonus() const; // generate suitable name for bonus - e.g. for storing in json struct
  480. std::shared_ptr<Bonus> addLimiter(TLimiterPtr Limiter); //returns this for convenient chain-calls
  481. std::shared_ptr<Bonus> addPropagator(TPropagatorPtr Propagator); //returns this for convenient chain-calls
  482. std::shared_ptr<Bonus> addUpdater(TUpdaterPtr Updater); //returns this for convenient chain-calls
  483. };
  484. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus);
  485. class DLL_LINKAGE BonusList
  486. {
  487. public:
  488. typedef std::vector<std::shared_ptr<Bonus>> TInternalContainer;
  489. private:
  490. TInternalContainer bonuses;
  491. bool belongsToTree;
  492. void changed();
  493. public:
  494. typedef TInternalContainer::const_reference const_reference;
  495. typedef TInternalContainer::value_type value_type;
  496. typedef TInternalContainer::const_iterator const_iterator;
  497. typedef TInternalContainer::iterator iterator;
  498. BonusList(bool BelongsToTree = false);
  499. BonusList(const BonusList &bonusList);
  500. BonusList(BonusList && other);
  501. BonusList& operator=(const BonusList &bonusList);
  502. // wrapper functions of the STL vector container
  503. TInternalContainer::size_type size() const { return bonuses.size(); }
  504. void push_back(std::shared_ptr<Bonus> x);
  505. TInternalContainer::iterator erase (const int position);
  506. void clear();
  507. bool empty() const { return bonuses.empty(); }
  508. void resize(TInternalContainer::size_type sz, std::shared_ptr<Bonus> c = nullptr );
  509. STRONG_INLINE std::shared_ptr<Bonus> &operator[] (TInternalContainer::size_type n) { return bonuses[n]; }
  510. STRONG_INLINE const std::shared_ptr<Bonus> &operator[] (TInternalContainer::size_type n) const { return bonuses[n]; }
  511. std::shared_ptr<Bonus> &back() { return bonuses.back(); }
  512. std::shared_ptr<Bonus> &front() { return bonuses.front(); }
  513. const std::shared_ptr<Bonus> &back() const { return bonuses.back(); }
  514. const std::shared_ptr<Bonus> &front() const { return bonuses.front(); }
  515. // There should be no non-const access to provide solid,robust bonus caching
  516. TInternalContainer::const_iterator begin() const { return bonuses.begin(); }
  517. TInternalContainer::const_iterator end() const { return bonuses.end(); }
  518. TInternalContainer::size_type operator-=(std::shared_ptr<Bonus> const &i);
  519. // BonusList functions
  520. void stackBonuses();
  521. int totalValue() const;
  522. void getBonuses(BonusList &out, const CSelector &selector, const CSelector &limit) const;
  523. void getAllBonuses(BonusList &out) const;
  524. void getBonuses(BonusList & out, const CSelector &selector) const;
  525. //special find functions
  526. std::shared_ptr<Bonus> getFirst(const CSelector &select);
  527. std::shared_ptr<const Bonus> getFirst(const CSelector &select) const;
  528. int valOfBonuses(const CSelector &select) const;
  529. // conversion / output
  530. JsonNode toJsonNode() const;
  531. // remove_if implementation for STL vector types
  532. template <class Predicate>
  533. void remove_if(Predicate pred)
  534. {
  535. BonusList newList;
  536. for (ui32 i = 0; i < bonuses.size(); i++)
  537. {
  538. auto b = bonuses[i];
  539. if (!pred(b.get()))
  540. newList.push_back(b);
  541. }
  542. bonuses.clear();
  543. bonuses.resize(newList.size());
  544. std::copy(newList.begin(), newList.end(), bonuses.begin());
  545. }
  546. template <class InputIterator>
  547. void insert(const int position, InputIterator first, InputIterator last);
  548. void insert(TInternalContainer::iterator position, TInternalContainer::size_type n, std::shared_ptr<Bonus> const &x);
  549. template <typename Handler>
  550. void serialize(Handler &h, const int version)
  551. {
  552. h & static_cast<TInternalContainer&>(bonuses);
  553. }
  554. // C++ for range support
  555. auto begin () -> decltype (bonuses.begin())
  556. {
  557. return bonuses.begin();
  558. }
  559. auto end () -> decltype (bonuses.end())
  560. {
  561. return bonuses.end();
  562. }
  563. };
  564. // Extensions for BOOST_FOREACH to enable iterating of BonusList objects
  565. // Don't touch/call this functions
  566. inline BonusList::iterator range_begin(BonusList & x)
  567. {
  568. return x.begin();
  569. }
  570. inline BonusList::iterator range_end(BonusList & x)
  571. {
  572. return x.end();
  573. }
  574. inline BonusList::const_iterator range_begin(BonusList const &x)
  575. {
  576. return x.begin();
  577. }
  578. inline BonusList::const_iterator range_end(BonusList const &x)
  579. {
  580. return x.end();
  581. }
  582. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList);
  583. struct BonusLimitationContext
  584. {
  585. std::shared_ptr<const Bonus> b;
  586. const CBonusSystemNode & node;
  587. const BonusList & alreadyAccepted;
  588. const BonusList & stillUndecided;
  589. };
  590. class DLL_LINKAGE ILimiter
  591. {
  592. public:
  593. enum EDecision {ACCEPT, DISCARD, NOT_SURE};
  594. virtual ~ILimiter();
  595. virtual int limit(const BonusLimitationContext &context) const; //0 - accept bonus; 1 - drop bonus; 2 - delay (drops eventually)
  596. virtual std::string toString() const;
  597. virtual JsonNode toJsonNode() const;
  598. template <typename Handler> void serialize(Handler &h, const int version)
  599. {
  600. }
  601. };
  602. class DLL_LINKAGE IBonusBearer
  603. {
  604. private:
  605. static CSelector anaffectedByMoraleSelector;
  606. CCheckProxy anaffectedByMorale;
  607. static CSelector moraleSelector;
  608. CTotalsProxy moraleValue;
  609. static CSelector luckSelector;
  610. CTotalsProxy luckValue;
  611. static CSelector selfMoraleSelector;
  612. CCheckProxy selfMorale;
  613. static CSelector selfLuckSelector;
  614. CCheckProxy selfLuck;
  615. public:
  616. //new bonusing node interface
  617. // * selector is predicate that tests if HeroBonus matches our criteria
  618. // * root is node on which call was made (nullptr will be replaced with this)
  619. //interface
  620. IBonusBearer();
  621. virtual TConstBonusListPtr getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root = nullptr, const std::string &cachingStr = "") const = 0;
  622. int valOfBonuses(const CSelector &selector, const std::string &cachingStr = "") const;
  623. bool hasBonus(const CSelector &selector, const std::string &cachingStr = "") const;
  624. bool hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr = "") const;
  625. TConstBonusListPtr getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr = "") const;
  626. TConstBonusListPtr getBonuses(const CSelector &selector, const std::string &cachingStr = "") const;
  627. std::shared_ptr<const Bonus> getBonus(const CSelector &selector) const; //returns any bonus visible on node that matches (or nullptr if none matches)
  628. //legacy interface
  629. int valOfBonuses(Bonus::BonusType type, const CSelector &selector) const;
  630. int valOfBonuses(Bonus::BonusType type, int subtype = -1) const; //subtype -> subtype of bonus, if -1 then anyt;
  631. bool hasBonusOfType(Bonus::BonusType type, int subtype = -1) const;//determines if hero has a bonus of given type (and optionally subtype)
  632. bool hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const;
  633. //various hlp functions for non-trivial values
  634. //used for stacks and creatures only
  635. virtual int getMinDamage(bool ranged) const;
  636. virtual int getMaxDamage(bool ranged) const;
  637. virtual int getAttack(bool ranged) const;
  638. virtual int getDefense(bool ranged) const;
  639. int MoraleVal() const; //range [-3, +3]
  640. int LuckVal() const; //range [-3, +3]
  641. /**
  642. Returns total value of all morale bonuses and sets bonusList as a pointer to the list of selected bonuses.
  643. @param bonusList is the out param it's list of all selected bonuses
  644. @return total value of all morale in the range [-3, +3] and 0 otherwise
  645. */
  646. int MoraleValAndBonusList(TConstBonusListPtr & bonusList) const;
  647. int LuckValAndBonusList(TConstBonusListPtr & bonusList) const;
  648. ui32 MaxHealth() const; //get max HP of stack with all modifiers
  649. bool isLiving() const; //non-undead, non-non living or alive
  650. virtual si32 magicResistance() const;
  651. ui32 Speed(int turn = 0, bool useBind = false) const; //get speed of creature with all modificators
  652. si32 manaLimit() const; //maximum mana value for this hero (basically 10*knowledge)
  653. int getPrimSkillLevel(PrimarySkill::PrimarySkill id) const;
  654. virtual int64_t getTreeVersion() const = 0;
  655. };
  656. class DLL_LINKAGE CBonusSystemNode : public virtual IBonusBearer, public boost::noncopyable
  657. {
  658. public:
  659. enum ENodeTypes
  660. {
  661. NONE = -1,
  662. UNKNOWN, STACK_INSTANCE, STACK_BATTLE, SPECIALTY, ARTIFACT, CREATURE, ARTIFACT_INSTANCE, HERO, PLAYER, TEAM,
  663. TOWN_AND_VISITOR, BATTLE, COMMANDER, GLOBAL_EFFECTS, ALL_CREATURES
  664. };
  665. private:
  666. BonusList bonuses; //wielded bonuses (local or up-propagated here)
  667. BonusList exportedBonuses; //bonuses coming from this node (wielded or propagated away)
  668. TNodesVector parents; //parents -> we inherit bonuses from them, we may attach our bonuses to them
  669. TNodesVector children;
  670. ENodeTypes nodeType;
  671. std::string description;
  672. bool isHypotheticNode;
  673. static const bool cachingEnabled;
  674. mutable BonusList cachedBonuses;
  675. mutable int64_t cachedLast;
  676. static std::atomic<int32_t> treeChanged;
  677. // Setting a value to cachingStr before getting any bonuses caches the result for later requests.
  678. // This string needs to be unique, that's why it has to be setted in the following manner:
  679. // [property key]_[value] => only for selector
  680. mutable std::map<std::string, TBonusListPtr > cachedRequests;
  681. mutable boost::mutex sync;
  682. void getBonusesRec(BonusList &out, const CSelector &selector, const CSelector &limit) const;
  683. void getAllBonusesRec(BonusList &out) const;
  684. TConstBonusListPtr getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root = nullptr) const;
  685. std::shared_ptr<Bonus> update(const std::shared_ptr<Bonus> & b) const;
  686. public:
  687. explicit CBonusSystemNode();
  688. explicit CBonusSystemNode(bool isHypotetic);
  689. explicit CBonusSystemNode(ENodeTypes NodeType);
  690. CBonusSystemNode(CBonusSystemNode && other);
  691. virtual ~CBonusSystemNode();
  692. void limitBonuses(const BonusList &allBonuses, BonusList &out) const; //out will bo populed with bonuses that are not limited here
  693. TBonusListPtr limitBonuses(const BonusList &allBonuses) const; //same as above, returns out by val for convienence
  694. TConstBonusListPtr getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root = nullptr, const std::string &cachingStr = "") const override;
  695. void getParents(TCNodes &out) const; //retrieves list of parent nodes (nodes to inherit bonuses from),
  696. std::shared_ptr<const Bonus> getBonusLocalFirst(const CSelector &selector) const;
  697. //non-const interface
  698. void getParents(TNodes &out); //retrieves list of parent nodes (nodes to inherit bonuses from)
  699. void getRedParents(TNodes &out); //retrieves list of red parent nodes (nodes bonuses propagate from)
  700. void getRedAncestors(TNodes &out);
  701. void getRedChildren(TNodes &out);
  702. void getRedDescendants(TNodes &out);
  703. std::shared_ptr<Bonus> getBonusLocalFirst(const CSelector &selector);
  704. void attachTo(CBonusSystemNode *parent);
  705. void detachFrom(CBonusSystemNode *parent);
  706. void detachFromAll();
  707. virtual void addNewBonus(const std::shared_ptr<Bonus>& b);
  708. void accumulateBonus(const std::shared_ptr<Bonus>& b); //add value of bonus with same type/subtype or create new
  709. void newChildAttached(CBonusSystemNode *child);
  710. void childDetached(CBonusSystemNode *child);
  711. void propagateBonus(std::shared_ptr<Bonus> b);
  712. void unpropagateBonus(std::shared_ptr<Bonus> b);
  713. void removeBonus(const std::shared_ptr<Bonus>& b);
  714. void removeBonuses(const CSelector & selector);
  715. void removeBonusesRecursive(const CSelector & s);
  716. void newRedDescendant(CBonusSystemNode *descendant); //propagation needed
  717. void removedRedDescendant(CBonusSystemNode *descendant); //de-propagation needed
  718. bool isIndependentNode() const; //node is independent when it has no parents nor children
  719. bool actsAsBonusSourceOnly() const;
  720. ///updates count of remaining turns and removes outdated bonuses by selector
  721. void reduceBonusDurations(const CSelector &s);
  722. virtual std::string bonusToString(const std::shared_ptr<Bonus>& bonus, bool description) const {return "";}; //description or bonus name
  723. virtual std::string nodeName() const;
  724. bool isHypothetic() const { return isHypotheticNode; }
  725. void deserializationFix();
  726. void exportBonus(std::shared_ptr<Bonus> b);
  727. void exportBonuses();
  728. const BonusList &getBonusList() const;
  729. BonusList & getExportedBonusList();
  730. const BonusList & getExportedBonusList() const;
  731. CBonusSystemNode::ENodeTypes getNodeType() const;
  732. void setNodeType(CBonusSystemNode::ENodeTypes type);
  733. const TNodesVector &getParentNodes() const;
  734. const TNodesVector &getChildrenNodes() const;
  735. const std::string &getDescription() const;
  736. void setDescription(const std::string &description);
  737. static void treeHasChanged();
  738. int64_t getTreeVersion() const override;
  739. template <typename Handler> void serialize(Handler &h, const int version)
  740. {
  741. // h & bonuses;
  742. h & nodeType;
  743. h & exportedBonuses;
  744. h & description;
  745. BONUS_TREE_DESERIALIZATION_FIX
  746. //h & parents & children;
  747. }
  748. friend class CBonusProxy;
  749. };
  750. class DLL_LINKAGE IPropagator
  751. {
  752. public:
  753. virtual ~IPropagator();
  754. virtual bool shouldBeAttached(CBonusSystemNode *dest);
  755. virtual CBonusSystemNode::ENodeTypes getPropagatorType() const;
  756. template <typename Handler> void serialize(Handler &h, const int version)
  757. {}
  758. };
  759. class DLL_LINKAGE CPropagatorNodeType : public IPropagator
  760. {
  761. CBonusSystemNode::ENodeTypes nodeType;
  762. public:
  763. CPropagatorNodeType();
  764. CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType);
  765. bool shouldBeAttached(CBonusSystemNode *dest) override;
  766. CBonusSystemNode::ENodeTypes getPropagatorType() const override;
  767. template <typename Handler> void serialize(Handler &h, const int version)
  768. {
  769. h & nodeType;
  770. }
  771. };
  772. namespace NBonus
  773. {
  774. //set of methods that may be safely called with nullptr objs
  775. DLL_LINKAGE int valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype = -1); //subtype -> subtype of bonus, if -1 then any
  776. DLL_LINKAGE bool hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype = -1);//determines if hero has a bonus of given type (and optionally subtype)
  777. }
  778. template<typename T>
  779. class CSelectFieldEqual
  780. {
  781. T Bonus::*ptr;
  782. public:
  783. CSelectFieldEqual(T Bonus::*Ptr)
  784. : ptr(Ptr)
  785. {
  786. }
  787. CSelector operator()(const T &valueToCompareAgainst) const
  788. {
  789. auto ptr2 = ptr; //We need a COPY because we don't want to reference this (might be outlived by lambda)
  790. return [ptr2, valueToCompareAgainst](const Bonus *bonus)
  791. {
  792. return bonus->*ptr2 == valueToCompareAgainst;
  793. };
  794. }
  795. };
  796. template<typename T> //can be same, needed for subtype field
  797. class CSelectFieldEqualOrEvery
  798. {
  799. T Bonus::*ptr;
  800. T val;
  801. public:
  802. CSelectFieldEqualOrEvery(T Bonus::*Ptr, const T &Val)
  803. : ptr(Ptr), val(Val)
  804. {
  805. }
  806. bool operator()(const Bonus *bonus) const
  807. {
  808. return (bonus->*ptr == val) || (bonus->*ptr == static_cast<T>(Bonus::EVERY_TYPE));
  809. }
  810. CSelectFieldEqualOrEvery& operator()(const T &setVal)
  811. {
  812. val = setVal;
  813. return *this;
  814. }
  815. };
  816. class DLL_LINKAGE CWillLastTurns
  817. {
  818. public:
  819. int turnsRequested;
  820. bool operator()(const Bonus *bonus) const
  821. {
  822. return turnsRequested <= 0 //every present effect will last zero (or "less") turns
  823. || !Bonus::NTurns(bonus) //so do every not expriing after N-turns effect
  824. || bonus->turnsRemain > turnsRequested;
  825. }
  826. CWillLastTurns& operator()(const int &setVal)
  827. {
  828. turnsRequested = setVal;
  829. return *this;
  830. }
  831. };
  832. class DLL_LINKAGE CWillLastDays
  833. {
  834. public:
  835. int daysRequested;
  836. bool operator()(const Bonus *bonus) const
  837. {
  838. if(daysRequested <= 0 || Bonus::Permanent(bonus) || Bonus::OneBattle(bonus))
  839. return true;
  840. else if(Bonus::OneDay(bonus))
  841. return false;
  842. else if(Bonus::NDays(bonus) || Bonus::OneWeek(bonus))
  843. {
  844. return bonus->turnsRemain > daysRequested;
  845. }
  846. return false; // TODO: ONE_WEEK need support for turnsRemain, but for now we'll exclude all unhandled durations
  847. }
  848. CWillLastDays& operator()(const int &setVal)
  849. {
  850. daysRequested = setVal;
  851. return *this;
  852. }
  853. };
  854. class DLL_LINKAGE AggregateLimiter : public ILimiter
  855. {
  856. protected:
  857. std::vector<TLimiterPtr> limiters;
  858. virtual const std::string & getAggregator() const = 0;
  859. public:
  860. void add(TLimiterPtr limiter);
  861. JsonNode toJsonNode() const override;
  862. template <typename Handler> void serialize(Handler & h, const int version)
  863. {
  864. h & static_cast<ILimiter&>(*this);
  865. if(version >= 786)
  866. {
  867. h & limiters;
  868. }
  869. }
  870. };
  871. class DLL_LINKAGE AllOfLimiter : public AggregateLimiter
  872. {
  873. protected:
  874. const std::string & getAggregator() const override;
  875. public:
  876. static const std::string aggregator;
  877. int limit(const BonusLimitationContext & context) const override;
  878. };
  879. class DLL_LINKAGE AnyOfLimiter : public AggregateLimiter
  880. {
  881. protected:
  882. const std::string & getAggregator() const override;
  883. public:
  884. static const std::string aggregator;
  885. int limit(const BonusLimitationContext & context) const override;
  886. };
  887. class DLL_LINKAGE NoneOfLimiter : public AggregateLimiter
  888. {
  889. protected:
  890. const std::string & getAggregator() const override;
  891. public:
  892. static const std::string aggregator;
  893. int limit(const BonusLimitationContext & context) const override;
  894. };
  895. class DLL_LINKAGE CCreatureTypeLimiter : public ILimiter //affect only stacks of given creature (and optionally it's upgrades)
  896. {
  897. public:
  898. const CCreature *creature;
  899. bool includeUpgrades;
  900. CCreatureTypeLimiter();
  901. CCreatureTypeLimiter(const CCreature & creature_, bool IncludeUpgrades = true);
  902. void setCreature (CreatureID id);
  903. int limit(const BonusLimitationContext &context) const override;
  904. virtual std::string toString() const override;
  905. virtual JsonNode toJsonNode() const override;
  906. template <typename Handler> void serialize(Handler &h, const int version)
  907. {
  908. h & static_cast<ILimiter&>(*this);
  909. h & creature;
  910. h & includeUpgrades;
  911. }
  912. };
  913. class DLL_LINKAGE HasAnotherBonusLimiter : public ILimiter //applies only to nodes that have another bonus working
  914. {
  915. public:
  916. Bonus::BonusType type;
  917. TBonusSubtype subtype;
  918. bool isSubtypeRelevant; //check for subtype only if this is true
  919. HasAnotherBonusLimiter(Bonus::BonusType bonus = Bonus::NONE);
  920. HasAnotherBonusLimiter(Bonus::BonusType bonus, TBonusSubtype _subtype);
  921. int limit(const BonusLimitationContext &context) const override;
  922. virtual std::string toString() const override;
  923. virtual JsonNode toJsonNode() const override;
  924. template <typename Handler> void serialize(Handler &h, const int version)
  925. {
  926. h & static_cast<ILimiter&>(*this);
  927. h & type;
  928. h & subtype;
  929. h & isSubtypeRelevant;
  930. }
  931. };
  932. class DLL_LINKAGE CreatureTerrainLimiter : public ILimiter //applies only to creatures that are on specified terrain, default native terrain
  933. {
  934. public:
  935. int terrainType;
  936. CreatureTerrainLimiter();
  937. CreatureTerrainLimiter(int TerrainType);
  938. int limit(const BonusLimitationContext &context) const override;
  939. virtual std::string toString() const override;
  940. virtual JsonNode toJsonNode() const override;
  941. template <typename Handler> void serialize(Handler &h, const int version)
  942. {
  943. h & static_cast<ILimiter&>(*this);
  944. h & terrainType;
  945. }
  946. };
  947. class DLL_LINKAGE CreatureFactionLimiter : public ILimiter //applies only to creatures of given faction
  948. {
  949. public:
  950. TFaction faction;
  951. CreatureFactionLimiter();
  952. CreatureFactionLimiter(TFaction faction);
  953. int limit(const BonusLimitationContext &context) const override;
  954. virtual std::string toString() const override;
  955. virtual JsonNode toJsonNode() const override;
  956. template <typename Handler> void serialize(Handler &h, const int version)
  957. {
  958. h & static_cast<ILimiter&>(*this);
  959. h & faction;
  960. }
  961. };
  962. class DLL_LINKAGE CreatureAlignmentLimiter : public ILimiter //applies only to creatures of given alignment
  963. {
  964. public:
  965. si8 alignment;
  966. CreatureAlignmentLimiter();
  967. CreatureAlignmentLimiter(si8 Alignment);
  968. int limit(const BonusLimitationContext &context) const override;
  969. virtual std::string toString() const override;
  970. virtual JsonNode toJsonNode() const override;
  971. template <typename Handler> void serialize(Handler &h, const int version)
  972. {
  973. h & static_cast<ILimiter&>(*this);
  974. h & alignment;
  975. }
  976. };
  977. class DLL_LINKAGE StackOwnerLimiter : public ILimiter //applies only to creatures of given alignment
  978. {
  979. public:
  980. PlayerColor owner;
  981. StackOwnerLimiter();
  982. StackOwnerLimiter(PlayerColor Owner);
  983. int limit(const BonusLimitationContext &context) const override;
  984. template <typename Handler> void serialize(Handler &h, const int version)
  985. {
  986. h & static_cast<ILimiter&>(*this);
  987. h & owner;
  988. }
  989. };
  990. class DLL_LINKAGE RankRangeLimiter : public ILimiter //applies to creatures with min <= Rank <= max
  991. {
  992. public:
  993. ui8 minRank, maxRank;
  994. RankRangeLimiter();
  995. RankRangeLimiter(ui8 Min, ui8 Max = 255);
  996. int limit(const BonusLimitationContext &context) const override;
  997. template <typename Handler> void serialize(Handler &h, const int version)
  998. {
  999. h & static_cast<ILimiter&>(*this);
  1000. h & minRank;
  1001. h & maxRank;
  1002. }
  1003. };
  1004. namespace Selector
  1005. {
  1006. extern DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type();
  1007. extern DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype();
  1008. extern DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info();
  1009. extern DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType();
  1010. extern DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange();
  1011. extern DLL_LINKAGE CWillLastTurns turns;
  1012. extern DLL_LINKAGE CWillLastDays days;
  1013. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype);
  1014. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, CAddInfo info);
  1015. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID);
  1016. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source);
  1017. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType);
  1018. /**
  1019. * Selects all bonuses
  1020. * Usage example: Selector::all.And(<functor>).And(<functor>)...)
  1021. */
  1022. extern DLL_LINKAGE CSelector all;
  1023. /**
  1024. * Selects nothing
  1025. * Usage example: Selector::none.Or(<functor>).Or(<functor>)...)
  1026. */
  1027. extern DLL_LINKAGE CSelector none;
  1028. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type);
  1029. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype);
  1030. }
  1031. extern DLL_LINKAGE const std::map<std::string, Bonus::BonusType> bonusNameMap;
  1032. extern DLL_LINKAGE const std::map<std::string, Bonus::ValueType> bonusValueMap;
  1033. extern DLL_LINKAGE const std::map<std::string, Bonus::BonusSource> bonusSourceMap;
  1034. extern DLL_LINKAGE const std::map<std::string, ui16> bonusDurationMap;
  1035. extern DLL_LINKAGE const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect;
  1036. extern DLL_LINKAGE const std::map<std::string, TLimiterPtr> bonusLimiterMap;
  1037. extern DLL_LINKAGE const std::map<std::string, TPropagatorPtr> bonusPropagatorMap;
  1038. extern DLL_LINKAGE const std::map<std::string, TUpdaterPtr> bonusUpdaterMap;
  1039. // BonusList template that requires full interface of CBonusSystemNode
  1040. template <class InputIterator>
  1041. void BonusList::insert(const int position, InputIterator first, InputIterator last)
  1042. {
  1043. bonuses.insert(bonuses.begin() + position, first, last);
  1044. changed();
  1045. }
  1046. // observers for updating bonuses based on certain events (e.g. hero gaining level)
  1047. class DLL_LINKAGE IUpdater
  1048. {
  1049. public:
  1050. virtual ~IUpdater();
  1051. virtual std::shared_ptr<Bonus> update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const;
  1052. virtual std::string toString() const;
  1053. virtual JsonNode toJsonNode() const;
  1054. template <typename Handler> void serialize(Handler & h, const int version)
  1055. {
  1056. }
  1057. };
  1058. class DLL_LINKAGE GrowsWithLevelUpdater : public IUpdater
  1059. {
  1060. public:
  1061. int valPer20;
  1062. int stepSize;
  1063. GrowsWithLevelUpdater();
  1064. GrowsWithLevelUpdater(int valPer20, int stepSize = 1);
  1065. template <typename Handler> void serialize(Handler & h, const int version)
  1066. {
  1067. h & static_cast<IUpdater &>(*this);
  1068. h & valPer20;
  1069. h & stepSize;
  1070. }
  1071. std::shared_ptr<Bonus> update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const override;
  1072. virtual std::string toString() const override;
  1073. virtual JsonNode toJsonNode() const override;
  1074. };
  1075. class DLL_LINKAGE TimesHeroLevelUpdater : public IUpdater
  1076. {
  1077. public:
  1078. TimesHeroLevelUpdater();
  1079. template <typename Handler> void serialize(Handler & h, const int version)
  1080. {
  1081. h & static_cast<IUpdater &>(*this);
  1082. }
  1083. std::shared_ptr<Bonus> update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const override;
  1084. virtual std::string toString() const override;
  1085. virtual JsonNode toJsonNode() const override;
  1086. };
  1087. class DLL_LINKAGE TimesStackLevelUpdater : public IUpdater
  1088. {
  1089. public:
  1090. TimesStackLevelUpdater();
  1091. template <typename Handler> void serialize(Handler & h, const int version)
  1092. {
  1093. h & static_cast<IUpdater &>(*this);
  1094. }
  1095. std::shared_ptr<Bonus> update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const override;
  1096. virtual std::string toString() const override;
  1097. virtual JsonNode toJsonNode() const override;
  1098. };