HeroBonus.h 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  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. #include "Terrain.h"
  14. class CCreature;
  15. struct Bonus;
  16. class IBonusBearer;
  17. class CBonusSystemNode;
  18. class ILimiter;
  19. class IPropagator;
  20. class IUpdater;
  21. class BonusList;
  22. typedef std::shared_ptr<BonusList> TBonusListPtr;
  23. typedef std::shared_ptr<const BonusList> TConstBonusListPtr;
  24. typedef std::shared_ptr<ILimiter> TLimiterPtr;
  25. typedef std::shared_ptr<IPropagator> TPropagatorPtr;
  26. typedef std::shared_ptr<IUpdater> TUpdaterPtr;
  27. typedef std::set<CBonusSystemNode*> TNodes;
  28. typedef std::set<const CBonusSystemNode*> TCNodes;
  29. typedef std::vector<CBonusSystemNode *> TNodesVector;
  30. class CSelector : std::function<bool(const Bonus*)>
  31. {
  32. typedef std::function<bool(const Bonus*)> TBase;
  33. public:
  34. CSelector() {}
  35. template<typename T>
  36. CSelector(const T &t, //SFINAE trick -> include this c-tor in overload resolution only if parameter is class
  37. //(includes functors, lambdas) or function. Without that VC is going mad about ambiguities.
  38. typename std::enable_if < boost::mpl::or_ < std::is_class<T>, std::is_function<T >> ::value>::type *dummy = nullptr)
  39. : TBase(t)
  40. {}
  41. CSelector(std::nullptr_t)
  42. {}
  43. CSelector And(CSelector rhs) const
  44. {
  45. //lambda may likely outlive "this" (it can be even a temporary) => we copy the OBJECT (not pointer)
  46. auto thisCopy = *this;
  47. return [thisCopy, rhs](const Bonus *b) mutable { return thisCopy(b) && rhs(b); };
  48. }
  49. CSelector Or(CSelector rhs) const
  50. {
  51. auto thisCopy = *this;
  52. return [thisCopy, rhs](const Bonus *b) mutable { return thisCopy(b) || rhs(b); };
  53. }
  54. bool operator()(const Bonus *b) const
  55. {
  56. return TBase::operator()(b);
  57. }
  58. operator bool() const
  59. {
  60. return !!static_cast<const TBase&>(*this);
  61. }
  62. };
  63. class DLL_LINKAGE CBonusProxy
  64. {
  65. public:
  66. CBonusProxy(const IBonusBearer * Target, CSelector Selector);
  67. CBonusProxy(const CBonusProxy & other);
  68. CBonusProxy(CBonusProxy && other);
  69. CBonusProxy & operator=(CBonusProxy && other);
  70. CBonusProxy & operator=(const CBonusProxy & other);
  71. const BonusList * operator->() const;
  72. TConstBonusListPtr getBonusList() const;
  73. protected:
  74. CSelector selector;
  75. const IBonusBearer * target;
  76. mutable int64_t bonusListCachedLast;
  77. mutable TConstBonusListPtr bonusList[2];
  78. mutable int currentBonusListIndex;
  79. mutable boost::mutex swapGuard;
  80. void swapBonusList(TConstBonusListPtr other) const;
  81. };
  82. class DLL_LINKAGE CTotalsProxy : public CBonusProxy
  83. {
  84. public:
  85. CTotalsProxy(const IBonusBearer * Target, CSelector Selector, int InitialValue);
  86. CTotalsProxy(const CTotalsProxy & other);
  87. CTotalsProxy(CTotalsProxy && other) = delete;
  88. CTotalsProxy & operator=(const CTotalsProxy & other);
  89. CTotalsProxy & operator=(CTotalsProxy && other) = delete;
  90. int getMeleeValue() const;
  91. int getRangedValue() const;
  92. int getValue() const;
  93. /**
  94. Returns total value of all selected bonuses and sets bonusList as a pointer to the list of selected bonuses
  95. @param bonusList is the out list of all selected bonuses
  96. @return total value of all selected bonuses and 0 otherwise
  97. */
  98. int getValueAndList(TConstBonusListPtr & bonusList) const;
  99. private:
  100. int initialValue;
  101. mutable int64_t valueCachedLast;
  102. mutable int value;
  103. mutable int64_t meleeCachedLast;
  104. mutable int meleeValue;
  105. mutable int64_t rangedCachedLast;
  106. mutable int rangedValue;
  107. };
  108. class DLL_LINKAGE CCheckProxy
  109. {
  110. public:
  111. CCheckProxy(const IBonusBearer * Target, CSelector Selector);
  112. CCheckProxy(const CCheckProxy & other);
  113. CCheckProxy& operator= (const CCheckProxy & other) = default;
  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. TUpdaterPtr propagationUpdater;
  385. std::string description;
  386. Bonus(BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype=-1);
  387. Bonus(BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype=-1, ValueType ValType = ADDITIVE_VALUE);
  388. Bonus();
  389. template <typename Handler> void serialize(Handler &h, const int version)
  390. {
  391. h & duration;
  392. h & type;
  393. h & subtype;
  394. h & source;
  395. h & val;
  396. h & sid;
  397. h & description;
  398. h & additionalInfo;
  399. h & turnsRemain;
  400. h & valType;
  401. h & stacking;
  402. h & effectRange;
  403. h & limiter;
  404. h & propagator;
  405. h & updater;
  406. h & propagationUpdater;
  407. }
  408. template <typename Ptr>
  409. static bool compareByAdditionalInfo(const Ptr& a, const Ptr& b)
  410. {
  411. return a->additionalInfo < b->additionalInfo;
  412. }
  413. static bool NDays(const Bonus *hb)
  414. {
  415. return hb->duration & Bonus::N_DAYS;
  416. }
  417. static bool NTurns(const Bonus *hb)
  418. {
  419. return hb->duration & Bonus::N_TURNS;
  420. }
  421. static bool OneDay(const Bonus *hb)
  422. {
  423. return hb->duration & Bonus::ONE_DAY;
  424. }
  425. static bool OneWeek(const Bonus *hb)
  426. {
  427. return hb->duration & Bonus::ONE_WEEK;
  428. }
  429. static bool OneBattle(const Bonus *hb)
  430. {
  431. return hb->duration & Bonus::ONE_BATTLE;
  432. }
  433. static bool Permanent(const Bonus *hb)
  434. {
  435. return hb->duration & Bonus::PERMANENT;
  436. }
  437. static bool UntilGetsTurn(const Bonus *hb)
  438. {
  439. return hb->duration & Bonus::STACK_GETS_TURN;
  440. }
  441. static bool UntilAttack(const Bonus *hb)
  442. {
  443. return hb->duration & Bonus::UNTIL_ATTACK;
  444. }
  445. static bool UntilBeingAttacked(const Bonus *hb)
  446. {
  447. return hb->duration & Bonus::UNTIL_BEING_ATTACKED;
  448. }
  449. static bool UntilCommanderKilled(const Bonus *hb)
  450. {
  451. return hb->duration & Bonus::COMMANDER_KILLED;
  452. }
  453. inline bool operator == (const BonusType & cf) const
  454. {
  455. return type == cf;
  456. }
  457. inline void operator += (const ui32 Val) //no return
  458. {
  459. val += Val;
  460. }
  461. STRONG_INLINE static ui32 getSid32(ui32 high, ui32 low)
  462. {
  463. return (high << 16) + low;
  464. }
  465. std::string Description() const;
  466. JsonNode toJsonNode() const;
  467. std::string nameForBonus() const; // generate suitable name for bonus - e.g. for storing in json struct
  468. std::shared_ptr<Bonus> addLimiter(TLimiterPtr Limiter); //returns this for convenient chain-calls
  469. std::shared_ptr<Bonus> addPropagator(TPropagatorPtr Propagator); //returns this for convenient chain-calls
  470. std::shared_ptr<Bonus> addUpdater(TUpdaterPtr Updater); //returns this for convenient chain-calls
  471. void updateOppositeBonuses();
  472. };
  473. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus);
  474. class DLL_LINKAGE BonusList
  475. {
  476. public:
  477. typedef std::vector<std::shared_ptr<Bonus>> TInternalContainer;
  478. private:
  479. TInternalContainer bonuses;
  480. bool belongsToTree;
  481. void changed();
  482. public:
  483. typedef TInternalContainer::const_reference const_reference;
  484. typedef TInternalContainer::value_type value_type;
  485. typedef TInternalContainer::const_iterator const_iterator;
  486. typedef TInternalContainer::iterator iterator;
  487. BonusList(bool BelongsToTree = false);
  488. BonusList(const BonusList &bonusList);
  489. BonusList(BonusList && other);
  490. BonusList& operator=(const BonusList &bonusList);
  491. // wrapper functions of the STL vector container
  492. TInternalContainer::size_type size() const { return bonuses.size(); }
  493. void push_back(std::shared_ptr<Bonus> x);
  494. TInternalContainer::iterator erase (const int position);
  495. void clear();
  496. bool empty() const { return bonuses.empty(); }
  497. void resize(TInternalContainer::size_type sz, std::shared_ptr<Bonus> c = nullptr );
  498. STRONG_INLINE std::shared_ptr<Bonus> &operator[] (TInternalContainer::size_type n) { return bonuses[n]; }
  499. STRONG_INLINE const std::shared_ptr<Bonus> &operator[] (TInternalContainer::size_type n) const { return bonuses[n]; }
  500. std::shared_ptr<Bonus> &back() { return bonuses.back(); }
  501. std::shared_ptr<Bonus> &front() { return bonuses.front(); }
  502. const std::shared_ptr<Bonus> &back() const { return bonuses.back(); }
  503. const std::shared_ptr<Bonus> &front() const { return bonuses.front(); }
  504. // There should be no non-const access to provide solid,robust bonus caching
  505. TInternalContainer::const_iterator begin() const { return bonuses.begin(); }
  506. TInternalContainer::const_iterator end() const { return bonuses.end(); }
  507. TInternalContainer::size_type operator-=(std::shared_ptr<Bonus> const &i);
  508. // BonusList functions
  509. void stackBonuses();
  510. int totalValue() const;
  511. void getBonuses(BonusList &out, const CSelector &selector, const CSelector &limit) const;
  512. void getAllBonuses(BonusList &out) const;
  513. void getBonuses(BonusList & out, const CSelector &selector) const;
  514. //special find functions
  515. std::shared_ptr<Bonus> getFirst(const CSelector &select);
  516. std::shared_ptr<const Bonus> getFirst(const CSelector &select) const;
  517. int valOfBonuses(const CSelector &select) const;
  518. // conversion / output
  519. JsonNode toJsonNode() const;
  520. // remove_if implementation for STL vector types
  521. template <class Predicate>
  522. void remove_if(Predicate pred)
  523. {
  524. BonusList newList;
  525. for (ui32 i = 0; i < bonuses.size(); i++)
  526. {
  527. auto b = bonuses[i];
  528. if (!pred(b.get()))
  529. newList.push_back(b);
  530. }
  531. bonuses.clear();
  532. bonuses.resize(newList.size());
  533. std::copy(newList.begin(), newList.end(), bonuses.begin());
  534. }
  535. template <class InputIterator>
  536. void insert(const int position, InputIterator first, InputIterator last);
  537. void insert(TInternalContainer::iterator position, TInternalContainer::size_type n, std::shared_ptr<Bonus> const &x);
  538. template <typename Handler>
  539. void serialize(Handler &h, const int version)
  540. {
  541. h & static_cast<TInternalContainer&>(bonuses);
  542. }
  543. // C++ for range support
  544. auto begin () -> decltype (bonuses.begin())
  545. {
  546. return bonuses.begin();
  547. }
  548. auto end () -> decltype (bonuses.end())
  549. {
  550. return bonuses.end();
  551. }
  552. };
  553. // Extensions for BOOST_FOREACH to enable iterating of BonusList objects
  554. // Don't touch/call this functions
  555. inline BonusList::iterator range_begin(BonusList & x)
  556. {
  557. return x.begin();
  558. }
  559. inline BonusList::iterator range_end(BonusList & x)
  560. {
  561. return x.end();
  562. }
  563. inline BonusList::const_iterator range_begin(BonusList const &x)
  564. {
  565. return x.begin();
  566. }
  567. inline BonusList::const_iterator range_end(BonusList const &x)
  568. {
  569. return x.end();
  570. }
  571. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList);
  572. struct BonusLimitationContext
  573. {
  574. std::shared_ptr<const Bonus> b;
  575. const CBonusSystemNode & node;
  576. const BonusList & alreadyAccepted;
  577. const BonusList & stillUndecided;
  578. };
  579. class DLL_LINKAGE ILimiter
  580. {
  581. public:
  582. enum EDecision {ACCEPT, DISCARD, NOT_SURE};
  583. virtual ~ILimiter();
  584. virtual int limit(const BonusLimitationContext &context) const; //0 - accept bonus; 1 - drop bonus; 2 - delay (drops eventually)
  585. virtual std::string toString() const;
  586. virtual JsonNode toJsonNode() const;
  587. template <typename Handler> void serialize(Handler &h, const int version)
  588. {
  589. }
  590. };
  591. class DLL_LINKAGE IBonusBearer
  592. {
  593. private:
  594. static CSelector anaffectedByMoraleSelector;
  595. CCheckProxy anaffectedByMorale;
  596. static CSelector moraleSelector;
  597. CTotalsProxy moraleValue;
  598. static CSelector luckSelector;
  599. CTotalsProxy luckValue;
  600. static CSelector selfMoraleSelector;
  601. CCheckProxy selfMorale;
  602. static CSelector selfLuckSelector;
  603. CCheckProxy selfLuck;
  604. public:
  605. //new bonusing node interface
  606. // * selector is predicate that tests if HeroBonus matches our criteria
  607. // * root is node on which call was made (nullptr will be replaced with this)
  608. //interface
  609. IBonusBearer();
  610. virtual ~IBonusBearer() = default;
  611. virtual TConstBonusListPtr getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root = nullptr, const std::string &cachingStr = "") const = 0;
  612. int valOfBonuses(const CSelector &selector, const std::string &cachingStr = "") const;
  613. bool hasBonus(const CSelector &selector, const std::string &cachingStr = "") const;
  614. bool hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr = "") const;
  615. TConstBonusListPtr getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr = "") const;
  616. TConstBonusListPtr getBonuses(const CSelector &selector, const std::string &cachingStr = "") const;
  617. std::shared_ptr<const Bonus> getBonus(const CSelector &selector) const; //returns any bonus visible on node that matches (or nullptr if none matches)
  618. //legacy interface
  619. int valOfBonuses(Bonus::BonusType type, const CSelector &selector) const;
  620. int valOfBonuses(Bonus::BonusType type, int subtype = -1) const; //subtype -> subtype of bonus, if -1 then anyt;
  621. bool hasBonusOfType(Bonus::BonusType type, int subtype = -1) const;//determines if hero has a bonus of given type (and optionally subtype)
  622. bool hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const;
  623. //various hlp functions for non-trivial values
  624. //used for stacks and creatures only
  625. virtual int getMinDamage(bool ranged) const;
  626. virtual int getMaxDamage(bool ranged) const;
  627. virtual int getAttack(bool ranged) const;
  628. virtual int getDefense(bool ranged) const;
  629. int MoraleVal() const; //range [-3, +3]
  630. int LuckVal() const; //range [-3, +3]
  631. /**
  632. Returns total value of all morale bonuses and sets bonusList as a pointer to the list of selected bonuses.
  633. @param bonusList is the out param it's list of all selected bonuses
  634. @return total value of all morale in the range [-3, +3] and 0 otherwise
  635. */
  636. int MoraleValAndBonusList(TConstBonusListPtr & bonusList) const;
  637. int LuckValAndBonusList(TConstBonusListPtr & bonusList) const;
  638. ui32 MaxHealth() const; //get max HP of stack with all modifiers
  639. bool isLiving() const; //non-undead, non-non living or alive
  640. virtual si32 magicResistance() const;
  641. ui32 Speed(int turn = 0, bool useBind = false) const; //get speed of creature with all modificators
  642. si32 manaLimit() const; //maximum mana value for this hero (basically 10*knowledge)
  643. int getPrimSkillLevel(PrimarySkill::PrimarySkill id) const;
  644. virtual int64_t getTreeVersion() const = 0;
  645. };
  646. class DLL_LINKAGE CBonusSystemNode : public virtual IBonusBearer, public boost::noncopyable
  647. {
  648. public:
  649. enum ENodeTypes
  650. {
  651. NONE = -1,
  652. UNKNOWN, STACK_INSTANCE, STACK_BATTLE, SPECIALTY, ARTIFACT, CREATURE, ARTIFACT_INSTANCE, HERO, PLAYER, TEAM,
  653. TOWN_AND_VISITOR, BATTLE, COMMANDER, GLOBAL_EFFECTS, ALL_CREATURES, TOWN
  654. };
  655. private:
  656. BonusList bonuses; //wielded bonuses (local or up-propagated here)
  657. BonusList exportedBonuses; //bonuses coming from this node (wielded or propagated away)
  658. TNodesVector parents; //parents -> we inherit bonuses from them, we may attach our bonuses to them
  659. TNodesVector children;
  660. ENodeTypes nodeType;
  661. std::string description;
  662. bool isHypotheticNode;
  663. static const bool cachingEnabled;
  664. mutable BonusList cachedBonuses;
  665. mutable int64_t cachedLast;
  666. static std::atomic<int32_t> treeChanged;
  667. // Setting a value to cachingStr before getting any bonuses caches the result for later requests.
  668. // This string needs to be unique, that's why it has to be setted in the following manner:
  669. // [property key]_[value] => only for selector
  670. mutable std::map<std::string, TBonusListPtr > cachedRequests;
  671. mutable boost::mutex sync;
  672. void getAllBonusesRec(BonusList &out) const;
  673. TConstBonusListPtr getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root = nullptr) const;
  674. std::shared_ptr<Bonus> getUpdatedBonus(const std::shared_ptr<Bonus> & b, const TUpdaterPtr updater) const;
  675. public:
  676. explicit CBonusSystemNode();
  677. explicit CBonusSystemNode(bool isHypotetic);
  678. explicit CBonusSystemNode(ENodeTypes NodeType);
  679. CBonusSystemNode(CBonusSystemNode && other);
  680. virtual ~CBonusSystemNode();
  681. void limitBonuses(const BonusList &allBonuses, BonusList &out) const; //out will bo populed with bonuses that are not limited here
  682. TBonusListPtr limitBonuses(const BonusList &allBonuses) const; //same as above, returns out by val for convienence
  683. TConstBonusListPtr getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root = nullptr, const std::string &cachingStr = "") const override;
  684. void getParents(TCNodes &out) const; //retrieves list of parent nodes (nodes to inherit bonuses from),
  685. std::shared_ptr<const Bonus> getBonusLocalFirst(const CSelector & selector) const;
  686. //non-const interface
  687. void getParents(TNodes &out); //retrieves list of parent nodes (nodes to inherit bonuses from)
  688. void getRedParents(TNodes &out); //retrieves list of red parent nodes (nodes bonuses propagate from)
  689. void getRedAncestors(TNodes &out);
  690. void getRedChildren(TNodes &out);
  691. void getRedDescendants(TNodes &out);
  692. void getAllParents(TCNodes & out) const;
  693. static PlayerColor retrieveNodeOwner(const CBonusSystemNode * node);
  694. std::shared_ptr<Bonus> getBonusLocalFirst(const CSelector & selector);
  695. void attachTo(CBonusSystemNode *parent);
  696. void detachFrom(CBonusSystemNode *parent);
  697. void detachFromAll();
  698. virtual void addNewBonus(const std::shared_ptr<Bonus>& b);
  699. void accumulateBonus(const std::shared_ptr<Bonus>& b); //add value of bonus with same type/subtype or create new
  700. void newChildAttached(CBonusSystemNode *child);
  701. void childDetached(CBonusSystemNode *child);
  702. void propagateBonus(std::shared_ptr<Bonus> b, const CBonusSystemNode & source);
  703. void unpropagateBonus(std::shared_ptr<Bonus> b);
  704. void removeBonus(const std::shared_ptr<Bonus>& b);
  705. void removeBonuses(const CSelector & selector);
  706. void removeBonusesRecursive(const CSelector & s);
  707. void newRedDescendant(CBonusSystemNode *descendant); //propagation needed
  708. void removedRedDescendant(CBonusSystemNode *descendant); //de-propagation needed
  709. bool isIndependentNode() const; //node is independent when it has no parents nor children
  710. bool actsAsBonusSourceOnly() const;
  711. ///updates count of remaining turns and removes outdated bonuses by selector
  712. void reduceBonusDurations(const CSelector &s);
  713. virtual std::string bonusToString(const std::shared_ptr<Bonus>& bonus, bool description) const {return "";}; //description or bonus name
  714. virtual std::string nodeName() const;
  715. virtual std::string nodeShortInfo() const;
  716. bool isHypothetic() const { return isHypotheticNode; }
  717. void deserializationFix();
  718. void exportBonus(std::shared_ptr<Bonus> b);
  719. void exportBonuses();
  720. const BonusList &getBonusList() const;
  721. BonusList & getExportedBonusList();
  722. const BonusList & getExportedBonusList() const;
  723. CBonusSystemNode::ENodeTypes getNodeType() const;
  724. void setNodeType(CBonusSystemNode::ENodeTypes type);
  725. const TNodesVector &getParentNodes() const;
  726. const TNodesVector &getChildrenNodes() const;
  727. const std::string &getDescription() const;
  728. void setDescription(const std::string &description);
  729. static void treeHasChanged();
  730. int64_t getTreeVersion() const override;
  731. virtual PlayerColor getOwner() const
  732. {
  733. return PlayerColor::NEUTRAL;
  734. }
  735. template <typename Handler> void serialize(Handler &h, const int version)
  736. {
  737. // h & bonuses;
  738. h & nodeType;
  739. h & exportedBonuses;
  740. h & description;
  741. BONUS_TREE_DESERIALIZATION_FIX
  742. //h & parents & children;
  743. }
  744. friend class CBonusProxy;
  745. };
  746. class DLL_LINKAGE IPropagator
  747. {
  748. public:
  749. virtual ~IPropagator();
  750. virtual bool shouldBeAttached(CBonusSystemNode *dest);
  751. virtual CBonusSystemNode::ENodeTypes getPropagatorType() const;
  752. template <typename Handler> void serialize(Handler &h, const int version)
  753. {}
  754. };
  755. class DLL_LINKAGE CPropagatorNodeType : public IPropagator
  756. {
  757. CBonusSystemNode::ENodeTypes nodeType;
  758. public:
  759. CPropagatorNodeType();
  760. CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType);
  761. bool shouldBeAttached(CBonusSystemNode *dest) override;
  762. CBonusSystemNode::ENodeTypes getPropagatorType() const override;
  763. template <typename Handler> void serialize(Handler &h, const int version)
  764. {
  765. h & nodeType;
  766. }
  767. };
  768. namespace NBonus
  769. {
  770. //set of methods that may be safely called with nullptr objs
  771. DLL_LINKAGE int valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype = -1); //subtype -> subtype of bonus, if -1 then any
  772. 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)
  773. }
  774. template<typename T>
  775. class CSelectFieldEqual
  776. {
  777. T Bonus::*ptr;
  778. public:
  779. CSelectFieldEqual(T Bonus::*Ptr)
  780. : ptr(Ptr)
  781. {
  782. }
  783. CSelector operator()(const T &valueToCompareAgainst) const
  784. {
  785. auto ptr2 = ptr; //We need a COPY because we don't want to reference this (might be outlived by lambda)
  786. return [ptr2, valueToCompareAgainst](const Bonus *bonus)
  787. {
  788. return bonus->*ptr2 == valueToCompareAgainst;
  789. };
  790. }
  791. };
  792. template<typename T> //can be same, needed for subtype field
  793. class CSelectFieldEqualOrEvery
  794. {
  795. T Bonus::*ptr;
  796. T val;
  797. public:
  798. CSelectFieldEqualOrEvery(T Bonus::*Ptr, const T &Val)
  799. : ptr(Ptr), val(Val)
  800. {
  801. }
  802. bool operator()(const Bonus *bonus) const
  803. {
  804. return (bonus->*ptr == val) || (bonus->*ptr == static_cast<T>(Bonus::EVERY_TYPE));
  805. }
  806. CSelectFieldEqualOrEvery& operator()(const T &setVal)
  807. {
  808. val = setVal;
  809. return *this;
  810. }
  811. };
  812. class DLL_LINKAGE CWillLastTurns
  813. {
  814. public:
  815. int turnsRequested;
  816. bool operator()(const Bonus *bonus) const
  817. {
  818. return turnsRequested <= 0 //every present effect will last zero (or "less") turns
  819. || !Bonus::NTurns(bonus) //so do every not expriing after N-turns effect
  820. || bonus->turnsRemain > turnsRequested;
  821. }
  822. CWillLastTurns& operator()(const int &setVal)
  823. {
  824. turnsRequested = setVal;
  825. return *this;
  826. }
  827. };
  828. class DLL_LINKAGE CWillLastDays
  829. {
  830. public:
  831. int daysRequested;
  832. bool operator()(const Bonus *bonus) const
  833. {
  834. if(daysRequested <= 0 || Bonus::Permanent(bonus) || Bonus::OneBattle(bonus))
  835. return true;
  836. else if(Bonus::OneDay(bonus))
  837. return false;
  838. else if(Bonus::NDays(bonus) || Bonus::OneWeek(bonus))
  839. {
  840. return bonus->turnsRemain > daysRequested;
  841. }
  842. return false; // TODO: ONE_WEEK need support for turnsRemain, but for now we'll exclude all unhandled durations
  843. }
  844. CWillLastDays& operator()(const int &setVal)
  845. {
  846. daysRequested = setVal;
  847. return *this;
  848. }
  849. };
  850. class DLL_LINKAGE AggregateLimiter : public ILimiter
  851. {
  852. protected:
  853. std::vector<TLimiterPtr> limiters;
  854. virtual const std::string & getAggregator() const = 0;
  855. public:
  856. void add(TLimiterPtr limiter);
  857. JsonNode toJsonNode() const override;
  858. template <typename Handler> void serialize(Handler & h, const int version)
  859. {
  860. h & static_cast<ILimiter&>(*this);
  861. h & limiters;
  862. }
  863. };
  864. class DLL_LINKAGE AllOfLimiter : public AggregateLimiter
  865. {
  866. protected:
  867. const std::string & getAggregator() const override;
  868. public:
  869. static const std::string aggregator;
  870. int limit(const BonusLimitationContext & context) const override;
  871. };
  872. class DLL_LINKAGE AnyOfLimiter : public AggregateLimiter
  873. {
  874. protected:
  875. const std::string & getAggregator() const override;
  876. public:
  877. static const std::string aggregator;
  878. int limit(const BonusLimitationContext & context) const override;
  879. };
  880. class DLL_LINKAGE NoneOfLimiter : public AggregateLimiter
  881. {
  882. protected:
  883. const std::string & getAggregator() const override;
  884. public:
  885. static const std::string aggregator;
  886. int limit(const BonusLimitationContext & context) const override;
  887. };
  888. class DLL_LINKAGE CCreatureTypeLimiter : public ILimiter //affect only stacks of given creature (and optionally it's upgrades)
  889. {
  890. public:
  891. const CCreature *creature;
  892. bool includeUpgrades;
  893. CCreatureTypeLimiter();
  894. CCreatureTypeLimiter(const CCreature & creature_, bool IncludeUpgrades = true);
  895. void setCreature (CreatureID id);
  896. int limit(const BonusLimitationContext &context) const override;
  897. virtual std::string toString() const override;
  898. virtual JsonNode toJsonNode() const override;
  899. template <typename Handler> void serialize(Handler &h, const int version)
  900. {
  901. h & static_cast<ILimiter&>(*this);
  902. h & creature;
  903. h & includeUpgrades;
  904. }
  905. };
  906. class DLL_LINKAGE HasAnotherBonusLimiter : public ILimiter //applies only to nodes that have another bonus working
  907. {
  908. public:
  909. Bonus::BonusType type;
  910. TBonusSubtype subtype;
  911. bool isSubtypeRelevant; //check for subtype only if this is true
  912. HasAnotherBonusLimiter(Bonus::BonusType bonus = Bonus::NONE);
  913. HasAnotherBonusLimiter(Bonus::BonusType bonus, TBonusSubtype _subtype);
  914. int limit(const BonusLimitationContext &context) const override;
  915. virtual std::string toString() const override;
  916. virtual JsonNode toJsonNode() const override;
  917. template <typename Handler> void serialize(Handler &h, const int version)
  918. {
  919. h & static_cast<ILimiter&>(*this);
  920. h & type;
  921. h & subtype;
  922. h & isSubtypeRelevant;
  923. }
  924. };
  925. class DLL_LINKAGE CreatureTerrainLimiter : public ILimiter //applies only to creatures that are on specified terrain, default native terrain
  926. {
  927. public:
  928. Terrain terrainType;
  929. CreatureTerrainLimiter();
  930. CreatureTerrainLimiter(const Terrain& terrain);
  931. int limit(const BonusLimitationContext &context) const override;
  932. virtual std::string toString() const override;
  933. virtual JsonNode toJsonNode() const override;
  934. template <typename Handler> void serialize(Handler &h, const int version)
  935. {
  936. h & static_cast<ILimiter&>(*this);
  937. h & terrainType;
  938. }
  939. };
  940. class DLL_LINKAGE CreatureFactionLimiter : public ILimiter //applies only to creatures of given faction
  941. {
  942. public:
  943. TFaction faction;
  944. CreatureFactionLimiter();
  945. CreatureFactionLimiter(TFaction faction);
  946. int limit(const BonusLimitationContext &context) const override;
  947. virtual std::string toString() const override;
  948. virtual JsonNode toJsonNode() const override;
  949. template <typename Handler> void serialize(Handler &h, const int version)
  950. {
  951. h & static_cast<ILimiter&>(*this);
  952. h & faction;
  953. }
  954. };
  955. class DLL_LINKAGE CreatureAlignmentLimiter : public ILimiter //applies only to creatures of given alignment
  956. {
  957. public:
  958. si8 alignment;
  959. CreatureAlignmentLimiter();
  960. CreatureAlignmentLimiter(si8 Alignment);
  961. int limit(const BonusLimitationContext &context) const override;
  962. virtual std::string toString() const override;
  963. virtual JsonNode toJsonNode() const override;
  964. template <typename Handler> void serialize(Handler &h, const int version)
  965. {
  966. h & static_cast<ILimiter&>(*this);
  967. h & alignment;
  968. }
  969. };
  970. class DLL_LINKAGE StackOwnerLimiter : public ILimiter //applies only to creatures of given alignment
  971. {
  972. public:
  973. PlayerColor owner;
  974. StackOwnerLimiter();
  975. StackOwnerLimiter(PlayerColor Owner);
  976. int limit(const BonusLimitationContext &context) const override;
  977. template <typename Handler> void serialize(Handler &h, const int version)
  978. {
  979. h & static_cast<ILimiter&>(*this);
  980. h & owner;
  981. }
  982. };
  983. class DLL_LINKAGE OppositeSideLimiter : public ILimiter //applies only to creatures of enemy army during combat
  984. {
  985. public:
  986. PlayerColor owner;
  987. OppositeSideLimiter();
  988. OppositeSideLimiter(PlayerColor Owner);
  989. int limit(const BonusLimitationContext &context) const override;
  990. template <typename Handler> void serialize(Handler &h, const int version)
  991. {
  992. h & static_cast<ILimiter&>(*this);
  993. h & owner;
  994. }
  995. };
  996. class DLL_LINKAGE RankRangeLimiter : public ILimiter //applies to creatures with min <= Rank <= max
  997. {
  998. public:
  999. ui8 minRank, maxRank;
  1000. RankRangeLimiter();
  1001. RankRangeLimiter(ui8 Min, ui8 Max = 255);
  1002. int limit(const BonusLimitationContext &context) const override;
  1003. template <typename Handler> void serialize(Handler &h, const int version)
  1004. {
  1005. h & static_cast<ILimiter&>(*this);
  1006. h & minRank;
  1007. h & maxRank;
  1008. }
  1009. };
  1010. namespace Selector
  1011. {
  1012. extern DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type();
  1013. extern DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype();
  1014. extern DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info();
  1015. extern DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType();
  1016. extern DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange();
  1017. extern DLL_LINKAGE CWillLastTurns turns;
  1018. extern DLL_LINKAGE CWillLastDays days;
  1019. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype);
  1020. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, CAddInfo info);
  1021. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID);
  1022. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source);
  1023. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType);
  1024. /**
  1025. * Selects all bonuses
  1026. * Usage example: Selector::all.And(<functor>).And(<functor>)...)
  1027. */
  1028. extern DLL_LINKAGE CSelector all;
  1029. /**
  1030. * Selects nothing
  1031. * Usage example: Selector::none.Or(<functor>).Or(<functor>)...)
  1032. */
  1033. extern DLL_LINKAGE CSelector none;
  1034. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type);
  1035. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype);
  1036. }
  1037. extern DLL_LINKAGE const std::map<std::string, Bonus::BonusType> bonusNameMap;
  1038. extern DLL_LINKAGE const std::map<std::string, Bonus::ValueType> bonusValueMap;
  1039. extern DLL_LINKAGE const std::map<std::string, Bonus::BonusSource> bonusSourceMap;
  1040. extern DLL_LINKAGE const std::map<std::string, ui16> bonusDurationMap;
  1041. extern DLL_LINKAGE const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect;
  1042. extern DLL_LINKAGE const std::map<std::string, TLimiterPtr> bonusLimiterMap;
  1043. extern DLL_LINKAGE const std::map<std::string, TPropagatorPtr> bonusPropagatorMap;
  1044. extern DLL_LINKAGE const std::map<std::string, TUpdaterPtr> bonusUpdaterMap;
  1045. // BonusList template that requires full interface of CBonusSystemNode
  1046. template <class InputIterator>
  1047. void BonusList::insert(const int position, InputIterator first, InputIterator last)
  1048. {
  1049. bonuses.insert(bonuses.begin() + position, first, last);
  1050. changed();
  1051. }
  1052. // observers for updating bonuses based on certain events (e.g. hero gaining level)
  1053. class DLL_LINKAGE IUpdater
  1054. {
  1055. public:
  1056. virtual ~IUpdater();
  1057. virtual std::shared_ptr<Bonus> createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const;
  1058. virtual std::string toString() const;
  1059. virtual JsonNode toJsonNode() const;
  1060. template <typename Handler> void serialize(Handler & h, const int version)
  1061. {
  1062. }
  1063. };
  1064. class DLL_LINKAGE GrowsWithLevelUpdater : public IUpdater
  1065. {
  1066. public:
  1067. int valPer20;
  1068. int stepSize;
  1069. GrowsWithLevelUpdater();
  1070. GrowsWithLevelUpdater(int valPer20, int stepSize = 1);
  1071. template <typename Handler> void serialize(Handler & h, const int version)
  1072. {
  1073. h & static_cast<IUpdater &>(*this);
  1074. h & valPer20;
  1075. h & stepSize;
  1076. }
  1077. std::shared_ptr<Bonus> createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const override;
  1078. virtual std::string toString() const override;
  1079. virtual JsonNode toJsonNode() const override;
  1080. };
  1081. class DLL_LINKAGE TimesHeroLevelUpdater : public IUpdater
  1082. {
  1083. public:
  1084. TimesHeroLevelUpdater();
  1085. template <typename Handler> void serialize(Handler & h, const int version)
  1086. {
  1087. h & static_cast<IUpdater &>(*this);
  1088. }
  1089. std::shared_ptr<Bonus> createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const override;
  1090. virtual std::string toString() const override;
  1091. virtual JsonNode toJsonNode() const override;
  1092. };
  1093. class DLL_LINKAGE TimesStackLevelUpdater : public IUpdater
  1094. {
  1095. public:
  1096. TimesStackLevelUpdater();
  1097. template <typename Handler> void serialize(Handler & h, const int version)
  1098. {
  1099. h & static_cast<IUpdater &>(*this);
  1100. }
  1101. std::shared_ptr<Bonus> createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const override;
  1102. virtual std::string toString() const override;
  1103. virtual JsonNode toJsonNode() const override;
  1104. };
  1105. class DLL_LINKAGE OwnerUpdater : public IUpdater
  1106. {
  1107. public:
  1108. OwnerUpdater();
  1109. template <typename Handler> void serialize(Handler& h, const int version)
  1110. {
  1111. h & static_cast<IUpdater &>(*this);
  1112. }
  1113. std::shared_ptr<Bonus> createUpdatedBonus(const std::shared_ptr<Bonus>& b, const CBonusSystemNode& context) const override;
  1114. virtual std::string toString() const override;
  1115. virtual JsonNode toJsonNode() const override;
  1116. };