HeroBonus.h 49 KB

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