HeroBonus.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. #pragma once
  2. #include "../global.h"
  3. #include <string>
  4. #include <set>
  5. #include <boost/function.hpp>
  6. #include <boost/shared_ptr.hpp>
  7. #include <boost/range.hpp>
  8. #include <boost/thread/mutex.hpp>
  9. /*
  10. * HeroBonus.h, part of VCMI engine
  11. *
  12. * Authors: listed in file AUTHORS in main folder
  13. *
  14. * License: GNU General Public License v2.0 or later
  15. * Full text of license available in license.txt file, in main folder
  16. *
  17. */
  18. class CCreature;
  19. class CSpell;
  20. struct Bonus;
  21. class CBonusSystemNode;
  22. class ILimiter;
  23. class IPropagator;
  24. class BonusList;
  25. typedef boost::shared_ptr<BonusList> TBonusListPtr;
  26. typedef std::vector<std::pair<int,std::string> > TModDescr; //modifiers values and their descriptions
  27. typedef std::set<CBonusSystemNode*> TNodes;
  28. typedef std::set<const CBonusSystemNode*> TCNodes;
  29. typedef std::vector<CBonusSystemNode *> TNodesVector;
  30. typedef boost::function<bool(const Bonus*)> CSelector;
  31. namespace PrimarySkill
  32. {
  33. enum { ATTACK, DEFENSE, SPELL_POWER, KNOWLEDGE};
  34. }
  35. #define BONUS_LIST \
  36. BONUS_NAME(NONE) \
  37. BONUS_NAME(MOVEMENT) /*both water/land*/ \
  38. BONUS_NAME(LAND_MOVEMENT) \
  39. BONUS_NAME(SEA_MOVEMENT) \
  40. BONUS_NAME(MORALE) \
  41. BONUS_NAME(LUCK) \
  42. BONUS_NAME(PRIMARY_SKILL) /*uses subtype to pick skill; additional info if set: 1 - only melee, 2 - only distance*/ \
  43. BONUS_NAME(SIGHT_RADIOUS) \
  44. BONUS_NAME(MANA_REGENERATION) /*points per turn apart from normal (1 + mysticism)*/ \
  45. BONUS_NAME(FULL_MANA_REGENERATION) /*all mana points are replenished every day*/ \
  46. BONUS_NAME(NONEVIL_ALIGNMENT_MIX) /*good and neutral creatures can be mixed without morale penalty*/ \
  47. BONUS_NAME(SECONDARY_SKILL_PREMY) /*%*/ \
  48. BONUS_NAME(SURRENDER_DISCOUNT) /*%*/ \
  49. BONUS_NAME(STACKS_SPEED) /*additional info - percent of speed bonus applied after direct bonuses; >0 - added, <0 - subtracted to this part*/ \
  50. BONUS_NAME(FLYING_MOVEMENT) /*subtype 1 - without penalty, 2 - with penalty*/ \
  51. BONUS_NAME(SPELL_DURATION) \
  52. BONUS_NAME(AIR_SPELL_DMG_PREMY) \
  53. BONUS_NAME(EARTH_SPELL_DMG_PREMY) \
  54. BONUS_NAME(FIRE_SPELL_DMG_PREMY) \
  55. BONUS_NAME(WATER_SPELL_DMG_PREMY) \
  56. BONUS_NAME(WATER_WALKING) /*subtype 1 - without penalty, 2 - with penalty*/ \
  57. BONUS_NAME(NEGATE_ALL_NATURAL_IMMUNITIES) \
  58. BONUS_NAME(STACK_HEALTH) \
  59. BONUS_NAME(BLOCK_MORALE) \
  60. BONUS_NAME(BLOCK_LUCK) \
  61. BONUS_NAME(FIRE_SPELLS) \
  62. BONUS_NAME(AIR_SPELLS) \
  63. BONUS_NAME(WATER_SPELLS) \
  64. BONUS_NAME(EARTH_SPELLS) \
  65. BONUS_NAME(GENERATE_RESOURCE) /*daily value, uses subtype (resource type)*/ \
  66. BONUS_NAME(CREATURE_GROWTH) /*for legion artifacts: value - week growth bonus, subtype - monster level if aplicable*/ \
  67. BONUS_NAME(WHIRLPOOL_PROTECTION) /*hero won't lose army when teleporting through whirlpool*/ \
  68. BONUS_NAME(SPELL) /*hero knows spell, val - skill level (0 - 3), subtype - spell id*/ \
  69. BONUS_NAME(SPELLS_OF_LEVEL) /*hero knows all spells of given level, val - skill level; subtype - level*/ \
  70. BONUS_NAME(ENEMY_CANT_ESCAPE) /*for shackles of war*/ \
  71. 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*/ \
  72. BONUS_NAME(FREE_SHOOTING) /*stacks can shoot even if otherwise blocked (sharpshooter's bow effect)*/ \
  73. BONUS_NAME(OPENING_BATTLE_SPELL) /*casts a spell at expert level at beginning of battle, val - spell power, subtype - spell id*/ \
  74. BONUS_NAME(IMPROVED_NECROMANCY) /*allows Necropolis units other than skeletons to be raised by necromancy*/ \
  75. BONUS_NAME(CREATURE_GROWTH_PERCENT) /*increases growth of all units in all towns, val - percentage*/ \
  76. BONUS_NAME(FREE_SHIP_BOARDING) /*movement points preserved with ship boarding and landing*/ \
  77. BONUS_NAME(NO_TYPE) \
  78. BONUS_NAME(FLYING) \
  79. BONUS_NAME(SHOOTER) \
  80. BONUS_NAME(CHARGE_IMMUNITY) \
  81. BONUS_NAME(ADDITIONAL_ATTACK) \
  82. BONUS_NAME(UNLIMITED_RETALIATIONS) \
  83. BONUS_NAME(NO_MELEE_PENALTY) \
  84. BONUS_NAME(JOUSTING) /*for champions*/ \
  85. BONUS_NAME(HATE) /*eg. angels hate devils, subtype - ID of hated creature, val - damage bonus percent */ \
  86. BONUS_NAME(KING1) \
  87. BONUS_NAME(KING2) \
  88. BONUS_NAME(KING3) \
  89. BONUS_NAME(MAGIC_RESISTANCE) /*in % (value)*/ \
  90. BONUS_NAME(CHANGES_SPELL_COST_FOR_ALLY) /*in mana points (value) , eg. mage*/ \
  91. BONUS_NAME(CHANGES_SPELL_COST_FOR_ENEMY) /*in mana points (value) , eg. pegasus */ \
  92. BONUS_NAME(SPELL_AFTER_ATTACK) /* subtype - spell id, value - chance %, additional info % 1000 - level, (additional info)/1000 -> [0 - all attacks, 1 - shot only, 2 - melee only*/ \
  93. BONUS_NAME(SPELL_BEFORE_ATTACK) /* subtype - spell id, value - chance %, additional info % 1000 - level, (additional info)/1000 -> [0 - all attacks, 1 - shot only, 2 - melee only*/ \
  94. BONUS_NAME(SPELL_RESISTANCE_AURA) /*eg. unicorns, value - resistance bonus in % for adjacent creatures*/ \
  95. BONUS_NAME(LEVEL_SPELL_IMMUNITY) /*creature is immune to all spell with level below or equal to value of this bonus*/ \
  96. BONUS_NAME(TWO_HEX_ATTACK_BREATH) /*eg. dragons*/ \
  97. BONUS_NAME(SPELL_DAMAGE_REDUCTION) /*eg. golems; value - reduction in %, subtype - spell school; -1 - all, 0 - air, 1 - fire, 2 - water, 3 - earth*/ \
  98. BONUS_NAME(NO_WALL_PENALTY) \
  99. BONUS_NAME(NON_LIVING) /*eg. gargoyle*/ \
  100. BONUS_NAME(RANDOM_SPELLCASTER) /*eg. master genie, For Genie spells, subtype - spell id */ \
  101. BONUS_NAME(BLOCKS_RETALIATION) /*eg. naga*/ \
  102. BONUS_NAME(SPELL_IMMUNITY) /*subid - spell id*/ \
  103. BONUS_NAME(MANA_CHANNELING) /*value in %, eg. familiar*/ \
  104. BONUS_NAME(SPELL_LIKE_ATTACK) /*subtype - spell, value - spell level; range is taken from spell, but damage from creature; eg. magog*/ \
  105. BONUS_NAME(THREE_HEADED_ATTACK) /*eg. cerberus*/ \
  106. BONUS_NAME(DAEMON_SUMMONING) /*pit lord, subtype - type of creatures, val - hp per unit*/ \
  107. BONUS_NAME(FIRE_IMMUNITY) /*subtype 0 - all, 1 - all except positive, 2 - only damage spells*/ \
  108. BONUS_NAME(WATER_IMMUNITY) \
  109. BONUS_NAME(EARTH_IMMUNITY) \
  110. BONUS_NAME(AIR_IMMUNITY) \
  111. BONUS_NAME(FIRE_SHIELD) \
  112. BONUS_NAME(UNDEAD) \
  113. BONUS_NAME(HP_REGENERATION) /*creature regenerates val HP every new round*/ \
  114. BONUS_NAME(FULL_HP_REGENERATION) /*first creature regenerates all HP every new round; subtype 0 - animation 4 (trolllike), 1 - animation 47 (wightlike)*/ \
  115. BONUS_NAME(MANA_DRAIN) /*value - spell points per turn*/ \
  116. BONUS_NAME(LIFE_DRAIN) \
  117. BONUS_NAME(DOUBLE_DAMAGE_CHANCE) /*value in %, eg. dread knight*/ \
  118. BONUS_NAME(RETURN_AFTER_STRIKE) \
  119. BONUS_NAME(SELF_MORALE) /*eg. minotaur*/ \
  120. BONUS_NAME(SPELLCASTER) /*subtype - spell id, value - level of school. use SPECIFIC_SPELL_POWER, CREATURE_SPELL_POWER or CREATURE_ENCHANT_POWER for calculating the power*/ \
  121. BONUS_NAME(CATAPULT) \
  122. BONUS_NAME(ENEMY_DEFENCE_REDUCTION) /*in % (value) eg. behemots*/ \
  123. BONUS_NAME(GENERAL_DAMAGE_REDUCTION) /* shield / air shield effect */ \
  124. BONUS_NAME(GENERAL_ATTACK_REDUCTION) /*eg. while stoned or blinded - in %, subtype: -1 - any damage, 0 - melee damage, 1 - ranged damage*/ \
  125. BONUS_NAME(DEFENSIVE_STANCE) /* val - bonus to defense while defending */ \
  126. BONUS_NAME(ATTACKS_ALL_ADJACENT) /*eg. hydra*/ \
  127. BONUS_NAME(MORE_DAMAGE_FROM_SPELL) /*value - damage increase in %, subtype - spell id*/ \
  128. BONUS_NAME(FEAR) \
  129. BONUS_NAME(FEARLESS) \
  130. BONUS_NAME(NO_DISTANCE_PENALTY) \
  131. BONUS_NAME(NO_OBSTACLES_PENALTY) \
  132. BONUS_NAME(SELF_LUCK) /*halfling*/ \
  133. BONUS_NAME(ENCHANTER)/* for Enchanter spells, subtype - spell id */ \
  134. BONUS_NAME(HEALER) \
  135. BONUS_NAME(SIEGE_WEAPON) \
  136. BONUS_NAME(HYPNOTIZED) \
  137. BONUS_NAME(ADDITIONAL_RETALIATION) /*value - number of additional retaliations*/ \
  138. BONUS_NAME(MAGIC_MIRROR) /* value - chance of redirecting in %*/ \
  139. 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]*/ \
  140. 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 %*/ \
  141. BONUS_NAME(ATTACKS_NEAREST_CREATURE) /*while in berserk*/ \
  142. BONUS_NAME(IN_FRENZY) /*value - level*/ \
  143. BONUS_NAME(SLAYER) /*value - level*/ \
  144. BONUS_NAME(FORGETFULL) /*forgetfulness spell effect, value - level*/ \
  145. BONUS_NAME(NOT_ACTIVE) \
  146. BONUS_NAME(NO_LUCK) /*eg. when fighting on cursed ground*/ \
  147. BONUS_NAME(NO_MORALE) /*eg. when fighting on cursed ground*/ \
  148. BONUS_NAME(DARKNESS) /*val = radius */ \
  149. BONUS_NAME(SPECIAL_SECONDARY_SKILL) /*val = id, additionalInfo = value per level in percent*/ \
  150. BONUS_NAME(SPECIAL_SPELL_LEV) /*val = id, additionalInfo = value per level in percent*/\
  151. BONUS_NAME(SPELL_DAMAGE) /*val = value*/\
  152. BONUS_NAME(SPECIFIC_SPELL_DAMAGE) /*subtype = id of spell, val = value*/\
  153. BONUS_NAME(SPECIAL_BLESS_DAMAGE) /*val = spell (bless), additionalInfo = value per level in percent*/\
  154. BONUS_NAME(MAXED_SPELL) /*val = id*/\
  155. BONUS_NAME(SPECIAL_PECULIAR_ENCHANT) /*blesses and curses with id = val dependent on unit's level, subtype = 0 or 1 for Coronius*/\
  156. BONUS_NAME(SPECIAL_UPGRADE) /*val = base, additionalInfo = target */\
  157. BONUS_NAME(DRAGON_NATURE) \
  158. BONUS_NAME(CREATURE_DAMAGE)/*subtype 0 = both, 1 = min, 2 = max*/\
  159. BONUS_NAME(EXP_MULTIPLIER)/* val - percent of additional exp gained by stack/commander (base value 100)*/\
  160. BONUS_NAME(SHOTS)\
  161. BONUS_NAME(DEATH_STARE) /*subtype 0 - gorgon, 1 - commander*/\
  162. BONUS_NAME(POISON) /*val - max health penalty from poison possible*/\
  163. BONUS_NAME(BIND_EFFECT) /*doesn't do anything particular, works as a marker)*/\
  164. BONUS_NAME(ACID_BREATH) /*additional val damage per creature after attack, additional info - chance in percent*/\
  165. BONUS_NAME(RECEPTIVE) /*accepts friendly spells even with immunity*/\
  166. BONUS_NAME(DIRECT_DAMAGE_IMMUNITY) /*direct damage spells, that is*/\
  167. BONUS_NAME(CASTS) /*how many times creature can cast activated spell*/ \
  168. BONUS_NAME(SPECIFIC_SPELL_POWER) /* value used for Thunderbolt and Resurrection casted by units, subtype - spell id */\
  169. BONUS_NAME(CREATURE_SPELL_POWER) /* value per unit, divided by 100 (so faerie Dragons have 800)*/ \
  170. BONUS_NAME(CREATURE_ENCHANT_POWER) /* total duration of spells casted by creature */ \
  171. BONUS_NAME(REBIRTH) /* val - percent of life restored, subtype = 0 - regular, 1 - at least one unit (sacred Phoenix) */
  172. /// Struct for handling bonuses of several types. Can be transferred to any hero
  173. struct DLL_EXPORT Bonus
  174. {
  175. enum BonusType
  176. {
  177. #define BONUS_NAME(x) x,
  178. BONUS_LIST
  179. #undef BONUS_NAME
  180. };
  181. enum BonusDuration //when bonus is automatically removed
  182. {
  183. PERMANENT = 1,
  184. ONE_BATTLE = 2, //at the end of battle
  185. ONE_DAY = 4, //at the end of day
  186. ONE_WEEK = 8, //at the end of week (bonus lasts till the end of week, thats NOT 7 days
  187. N_TURNS = 16, //used during battles, after battle bonus is always removed
  188. N_DAYS = 32,
  189. UNITL_BEING_ATTACKED = 64,/*removed after attack and counterattacks are performed*/
  190. UNTIL_ATTACK = 128, /*removed after attack and counterattacks are performed*/
  191. STACK_GETS_TURN = 256 /*removed when stack gets its turn - used for defensive stance*/
  192. };
  193. enum BonusSource
  194. {
  195. ARTIFACT,
  196. ARTIFACT_INSTANCE,
  197. OBJECT,
  198. CREATURE_ABILITY,
  199. TERRAIN_NATIVE,
  200. TERRAIN_OVERLAY,
  201. SPELL_EFFECT,
  202. TOWN_STRUCTURE,
  203. HERO_BASE_SKILL,
  204. SECONDARY_SKILL,
  205. HERO_SPECIAL,
  206. ARMY,
  207. CAMPAIGN_BONUS,
  208. SPECIAL_WEEK,
  209. STACK_EXPERIENCE,
  210. OTHER /*used for defensive stance and default value of spell level limit*/
  211. };
  212. enum LimitEffect
  213. {
  214. NO_LIMIT = 0,
  215. ONLY_DISTANCE_FIGHT=1, ONLY_MELEE_FIGHT, //used to mark bonuses for attack/defense primary skills from spells like Precision (distance only)
  216. ONLY_ENEMY_ARMY
  217. };
  218. enum ValueType
  219. {
  220. ADDITIVE_VALUE,
  221. BASE_NUMBER,
  222. PERCENT_TO_ALL,
  223. PERCENT_TO_BASE,
  224. INDEPENDENT_MAX, //used for SPELL bonus
  225. INDEPENDENT_MIN //used for SECONDARY_SKILL_PREMY bonus
  226. };
  227. ui16 duration; //uses BonusDuration values
  228. si16 turnsRemain; //used if duration is N_TURNS or N_DAYS
  229. TBonusType type; //uses BonusType values - says to what is this bonus - 1 byte
  230. TBonusSubtype subtype; //-1 if not applicable - 4 bytes
  231. ui8 source;//source type" uses BonusSource values - what gave that bonus
  232. si32 val;
  233. ui32 sid; //source id: id of object/artifact/spell
  234. ui8 valType; //by ValueType enum
  235. si32 additionalInfo;
  236. ui8 effectRange; //if not NO_LIMIT, bonus will be omitted by default
  237. boost::shared_ptr<ILimiter> limiter;
  238. boost::shared_ptr<IPropagator> propagator;
  239. std::string description;
  240. Bonus(ui16 Dur, ui8 Type, ui8 Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype=-1);
  241. Bonus(ui16 Dur, ui8 Type, ui8 Src, si32 Val, ui32 ID, si32 Subtype=-1, ui8 ValType = ADDITIVE_VALUE);
  242. Bonus();
  243. ~Bonus();
  244. // //comparison
  245. // bool operator==(const HeroBonus &other)
  246. // {
  247. // return &other == this;
  248. // //TODO: what is best logic for that?
  249. // }
  250. // bool operator<(const HeroBonus &other)
  251. // {
  252. // return &other < this;
  253. // //TODO: what is best logic for that?
  254. // }
  255. template <typename Handler> void serialize(Handler &h, const int version)
  256. {
  257. h & duration & type & subtype & source & val & sid & description & additionalInfo & turnsRemain & valType & effectRange & limiter & propagator;
  258. }
  259. static bool compareByAdditionalInfo(const Bonus *a, const Bonus *b)
  260. {
  261. return a->additionalInfo < b->additionalInfo;
  262. }
  263. static bool OneDay(const Bonus *hb)
  264. {
  265. return hb->duration & Bonus::ONE_DAY;
  266. }
  267. static bool OneWeek(const Bonus *hb)
  268. {
  269. return hb->duration & Bonus::ONE_WEEK;
  270. }
  271. static bool OneBattle(const Bonus *hb)
  272. {
  273. return hb->duration & Bonus::ONE_BATTLE;
  274. }
  275. static bool UntilGetsTurn(const Bonus *hb)
  276. {
  277. return hb->duration & Bonus::STACK_GETS_TURN;
  278. }
  279. static bool UntilAttack(const Bonus *hb)
  280. {
  281. return hb->duration & Bonus::UNTIL_ATTACK;
  282. }
  283. static bool UntilBeingAttacked(const Bonus *hb)
  284. {
  285. return hb->duration & Bonus::UNITL_BEING_ATTACKED;
  286. }
  287. static bool IsFrom(const Bonus &hb, ui8 source, ui32 id) //if id==0xffffff then id doesn't matter
  288. {
  289. return hb.source==source && (id==0xffffff || hb.sid==id);
  290. }
  291. inline bool operator == (const BonusType & cf) const
  292. {
  293. return type == cf;
  294. }
  295. inline void ChangeBonusVal (const ui32 newVal)
  296. {
  297. val = newVal;
  298. }
  299. inline void operator += (const ui32 Val) //no return
  300. {
  301. val += Val;
  302. }
  303. const CSpell * sourceSpell() const;
  304. std::string Description() const;
  305. Bonus *addLimiter(ILimiter *Limiter); //returns this for convenient chain-calls
  306. Bonus *addPropagator(IPropagator *Propagator); //returns this for convenient chain-calls
  307. Bonus *addLimiter(boost::shared_ptr<ILimiter> Limiter); //returns this for convenient chain-calls
  308. Bonus *addPropagator(boost::shared_ptr<IPropagator> Propagator); //returns this for convenient chain-calls
  309. };
  310. DLL_EXPORT std::ostream & operator<<(std::ostream &out, const Bonus &bonus);
  311. class DLL_EXPORT BonusList
  312. {
  313. private:
  314. std::vector<Bonus*> bonuses;
  315. bool belongsToTree;
  316. public:
  317. BonusList(bool BelongsToTree = false);
  318. BonusList(const BonusList &bonusList);
  319. BonusList& operator=(const BonusList &bonusList);
  320. // wrapper functions of the STL vector container
  321. std::vector<Bonus*>::size_type size() const { return bonuses.size(); }
  322. void push_back(Bonus* const &x);
  323. std::vector<Bonus*>::iterator erase (const int position);
  324. void clear();
  325. void resize(std::vector<Bonus*>::size_type sz, Bonus* c = NULL );
  326. void insert(std::vector<Bonus*>::iterator position, std::vector<Bonus*>::size_type n, Bonus* const &x);
  327. Bonus *const &operator[] (std::vector<Bonus*>::size_type n) { return bonuses[n]; }
  328. Bonus *const &operator[] (std::vector<Bonus*>::size_type n) const { return bonuses[n]; }
  329. Bonus *const &back() { return bonuses.back(); }
  330. Bonus *const &front() { return bonuses.front(); }
  331. Bonus *const &back() const { return bonuses.back(); }
  332. Bonus *const &front() const { return bonuses.front(); }
  333. // There should be no non-const access to provide solid,robust bonus caching
  334. std::vector<Bonus*>::const_iterator begin() const { return bonuses.begin(); }
  335. std::vector<Bonus*>::const_iterator end() const { return bonuses.end(); }
  336. std::vector<Bonus*>::size_type operator-=(Bonus* const &i);
  337. // BonusList functions
  338. int totalValue() const; //subtype -> subtype of bonus, if -1 then any
  339. void getBonuses(TBonusListPtr out, const CSelector &selector, const CSelector &limit, const bool caching = false) const;
  340. void getModifiersWDescr(TModDescr &out) const;
  341. void getBonuses(TBonusListPtr out, const CSelector &selector) const;
  342. //special find functions
  343. Bonus *getFirst(const CSelector &select);
  344. const Bonus *getFirst(const CSelector &select) const;
  345. int valOfBonuses(const CSelector &select) const;
  346. void limit(const CBonusSystemNode &node); //erases bonuses using limitor
  347. void eliminateDuplicates();
  348. // remove_if implementation for STL vector types
  349. template <class Predicate>
  350. void remove_if(Predicate pred)
  351. {
  352. BonusList newList;
  353. for (unsigned int i = 0; i < bonuses.size(); i++)
  354. {
  355. Bonus *b = bonuses[i];
  356. if (!pred(b))
  357. newList.push_back(b);
  358. }
  359. bonuses.clear();
  360. bonuses.resize(newList.size());
  361. std::copy(newList.begin(), newList.end(), bonuses.begin());
  362. }
  363. template <class InputIterator>
  364. void insert(const int position, InputIterator first, InputIterator last);
  365. template <typename Handler> void serialize(Handler &h, const int version)
  366. {
  367. h & static_cast<std::vector<Bonus*>&>(bonuses);
  368. }
  369. friend inline std::vector<Bonus*>::iterator range_begin(BonusList & x);
  370. friend inline std::vector<Bonus*>::iterator range_end(BonusList & x);
  371. };
  372. // Extensions for BOOST_FOREACH to enable iterating of BonusList objects
  373. // Don't touch/call this functions
  374. inline std::vector<Bonus*>::iterator range_begin(BonusList & x)
  375. {
  376. return x.bonuses.begin();
  377. }
  378. inline std::vector<Bonus*>::iterator range_end(BonusList & x)
  379. {
  380. return x.bonuses.end();
  381. }
  382. inline std::vector<Bonus*>::const_iterator range_begin(BonusList const &x)
  383. {
  384. return x.begin();
  385. }
  386. inline std::vector<Bonus*>::const_iterator range_end(BonusList const &x)
  387. {
  388. return x.end();
  389. }
  390. DLL_EXPORT std::ostream & operator<<(std::ostream &out, const BonusList &bonusList);
  391. class DLL_EXPORT IPropagator
  392. {
  393. public:
  394. virtual ~IPropagator();
  395. virtual bool shouldBeAttached(CBonusSystemNode *dest);
  396. //virtual CBonusSystemNode *getDestNode(CBonusSystemNode *source, CBonusSystemNode *redParent, CBonusSystemNode *redChild); //called when red relation between parent-childrem is established / removed
  397. template <typename Handler> void serialize(Handler &h, const int version)
  398. {}
  399. };
  400. class DLL_EXPORT CPropagatorNodeType : public IPropagator
  401. {
  402. ui8 nodeType;
  403. public:
  404. CPropagatorNodeType();
  405. CPropagatorNodeType(ui8 NodeType);
  406. bool shouldBeAttached(CBonusSystemNode *dest);
  407. //CBonusSystemNode *getDestNode(CBonusSystemNode *source, CBonusSystemNode *redParent, CBonusSystemNode *redChild) OVERRIDE;
  408. template <typename Handler> void serialize(Handler &h, const int version)
  409. {
  410. h & nodeType;
  411. }
  412. };
  413. class DLL_EXPORT ILimiter
  414. {
  415. public:
  416. virtual ~ILimiter();
  417. virtual bool limit(const Bonus *b, const CBonusSystemNode &node) const; //return true to drop the bonus
  418. template <typename Handler> void serialize(Handler &h, const int version)
  419. {}
  420. };
  421. class DLL_EXPORT IBonusBearer
  422. {
  423. public:
  424. //new bonusing node interface
  425. // * selector is predicate that tests if HeroBonus matches our criteria
  426. // * root is node on which call was made (NULL will be replaced with this)
  427. //interface
  428. virtual const TBonusListPtr getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root = NULL, const std::string &cachingStr = "") const = 0;
  429. void getModifiersWDescr(TModDescr &out, const CSelector &selector, const std::string &cachingStr = "") const; //out: pairs<modifier value, modifier description>
  430. int getBonusesCount(const CSelector &selector, const std::string &cachingStr = "") const;
  431. int valOfBonuses(const CSelector &selector, const std::string &cachingStr = "") const;
  432. bool hasBonus(const CSelector &selector, const std::string &cachingStr = "") const;
  433. const TBonusListPtr getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr = "") const;
  434. const TBonusListPtr getBonuses(const CSelector &selector, const std::string &cachingStr = "") const;
  435. //legacy interface
  436. int valOfBonuses(Bonus::BonusType type, const CSelector &selector) const;
  437. int valOfBonuses(Bonus::BonusType type, int subtype = -1) const; //subtype -> subtype of bonus, if -1 then anyt;
  438. bool hasBonusOfType(Bonus::BonusType type, int subtype = -1) const;//determines if hero has a bonus of given type (and optionally subtype)
  439. bool hasBonusFrom(ui8 source, ui32 sourceID) const;
  440. void getModifiersWDescr( TModDescr &out, Bonus::BonusType type, int subtype = -1 ) const; //out: pairs<modifier value, modifier description>
  441. int getBonusesCount(int from, int id) const;
  442. //various hlp functions for non-trivial values
  443. ui32 getMinDamage() const; //used for stacks and creatures only
  444. ui32 getMaxDamage() const;
  445. int MoraleVal() const; //range [-3, +3]
  446. int LuckVal() const; //range [-3, +3]
  447. si32 Attack() const; //get attack of stack with all modificators
  448. si32 Defense(bool withFrenzy = true) const; //get defense of stack with all modificators
  449. ui16 MaxHealth() const; //get max HP of stack with all modifiers
  450. bool isLiving() const; //non-undead, non-non living or alive
  451. virtual si32 magicResistance() const;
  452. si32 manaLimit() const; //maximum mana value for this hero (basically 10*knowledge)
  453. int getPrimSkillLevel(int id) const; //0-attack, 1-defence, 2-spell power, 3-knowledge
  454. const TBonusListPtr getSpellBonuses() const;
  455. };
  456. class DLL_EXPORT CBonusSystemNode : public IBonusBearer
  457. {
  458. private:
  459. BonusList bonuses; //wielded bonuses (local or up-propagated here)
  460. BonusList exportedBonuses; //bonuses coming from this node (wielded or propagated away)
  461. TNodesVector parents; //parents -> we inherit bonuses from them, we may attach our bonuses to them
  462. TNodesVector children;
  463. ui8 nodeType;
  464. std::string description;
  465. static const bool cachingEnabled;
  466. mutable BonusList cachedBonuses;
  467. mutable int cachedLast;
  468. static int treeChanged;
  469. // Setting a value to cachingStr before getting any bonuses caches the result for later requests.
  470. // This string needs to be unique, that's why it has to be setted in the following manner:
  471. // [property key]_[value] => only for selector
  472. mutable std::map<std::string, TBonusListPtr > cachedRequests;
  473. void getAllBonusesRec(TBonusListPtr out, const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root = NULL, const bool caching = false) const;
  474. public:
  475. explicit CBonusSystemNode();
  476. virtual ~CBonusSystemNode();
  477. const TBonusListPtr getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root = NULL, const std::string &cachingStr = "") const;
  478. void getParents(TCNodes &out) const; //retrieves list of parent nodes (nodes to inherit bonuses from),
  479. const Bonus *getBonus(const CSelector &selector) const;
  480. //non-const interface
  481. void getParents(TNodes &out); //retrieves list of parent nodes (nodes to inherit bonuses from)
  482. void getRedParents(TNodes &out); //retrieves list of red parent nodes (nodes bonuses propagate from)
  483. void getRedAncestors(TNodes &out);
  484. void getRedChildren(TNodes &out);
  485. void getRedDescendants(TNodes &out);
  486. Bonus *getBonus(const CSelector &selector);
  487. void attachTo(CBonusSystemNode *parent);
  488. void detachFrom(CBonusSystemNode *parent);
  489. void detachFromAll();
  490. void addNewBonus(Bonus *b); //b will be deleted with destruction of node
  491. void newChildAttached(CBonusSystemNode *child);
  492. void childDetached(CBonusSystemNode *child);
  493. void propagateBonus(Bonus * b);
  494. void unpropagateBonus(Bonus * b);
  495. //void addNewBonus(const Bonus &b); //b will copied
  496. void removeBonus(Bonus *b);
  497. void newRedDescendant(CBonusSystemNode *descendant); //propagation needed
  498. void removedRedDescendant(CBonusSystemNode *descendant); //de-propagation needed
  499. void battleTurnPassed(); //updates count of remaining turns and removed outdated bonuses
  500. bool isIndependentNode() const; //node is independent when it has no parents nor children
  501. bool actsAsBonusSourceOnly() const;
  502. bool isLimitedOnUs(Bonus *b) const; //if bonus should be removed from list acquired from this node
  503. void popBonuses(const CSelector &s);
  504. virtual std::string bonusToString(Bonus *bonus, bool description) const {return "";}; //description or bonus name
  505. virtual std::string nodeName() const;
  506. void deserializationFix();
  507. void exportBonus(Bonus * b);
  508. void exportBonuses();
  509. static void incrementTreeChangedNum();
  510. BonusList &getBonusList();
  511. const BonusList &getBonusList() const;
  512. BonusList &getExportedBonusList();
  513. const ui8 getNodeType() const;
  514. void setNodeType(ui8 type);
  515. const TNodesVector &getParentNodes() const;
  516. const TNodesVector &getChildrenNodes() const;
  517. const std::string &getDescription() const;
  518. void setDescription(const std::string &description);
  519. template <typename Handler> void serialize(Handler &h, const int version)
  520. {
  521. h & /*bonuses & */nodeType;
  522. h & exportedBonuses;
  523. h & description;
  524. BONUS_TREE_DESERIALIZATION_FIX
  525. //h & parents & children;
  526. }
  527. enum ENodeTypes
  528. {
  529. UNKNOWN, STACK_INSTANCE, STACK_BATTLE, SPECIALITY, ARTIFACT, CREATURE, ARTIFACT_INSTANCE, HERO, PLAYER, TEAM, TOWN_AND_VISITOR
  530. };
  531. };
  532. namespace NBonus
  533. {
  534. //set of methods that may be safely called with NULL objs
  535. DLL_EXPORT int valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype = -1); //subtype -> subtype of bonus, if -1 then any
  536. DLL_EXPORT bool hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype = -1);//determines if hero has a bonus of given type (and optionally subtype)
  537. //DLL_EXPORT const HeroBonus * get(const CBonusSystemNode *obj, int from, int id );
  538. DLL_EXPORT void getModifiersWDescr(const CBonusSystemNode *obj, TModDescr &out, Bonus::BonusType type, int subtype = -1 ); //out: pairs<modifier value, modifier description>
  539. DLL_EXPORT int getCount(const CBonusSystemNode *obj, int from, int id);
  540. };
  541. /// generates HeroBonus from given data
  542. inline Bonus makeFeatureVal(Bonus::BonusType type, ui8 duration, si16 subtype, si32 value, Bonus::BonusSource source, ui16 turnsRemain = 0, si32 additionalInfo = 0)
  543. {
  544. Bonus sf;
  545. sf.type = type;
  546. sf.duration = duration;
  547. sf.source = source;
  548. sf.turnsRemain = turnsRemain;
  549. sf.subtype = subtype;
  550. sf.val = value;
  551. sf.additionalInfo = additionalInfo;
  552. return sf;
  553. }
  554. //generates HeroBonus from given data
  555. inline Bonus * makeFeature(Bonus::BonusType type, ui8 duration, si16 subtype, si32 value, Bonus::BonusSource source, ui16 turnsRemain = 0, si32 additionalInfo = 0)
  556. {
  557. return new Bonus(makeFeatureVal(type, duration, subtype, value, source, turnsRemain, additionalInfo));
  558. }
  559. class DLL_EXPORT CSelectorsConjunction
  560. {
  561. const CSelector first, second;
  562. public:
  563. CSelectorsConjunction(const CSelector &First, const CSelector &Second)
  564. :first(First), second(Second)
  565. {
  566. }
  567. bool operator()(const Bonus *bonus) const
  568. {
  569. return first(bonus) && second(bonus);
  570. }
  571. };
  572. CSelector DLL_EXPORT operator&&(const CSelector &first, const CSelector &second);
  573. class DLL_EXPORT CSelectorsAlternative
  574. {
  575. const CSelector first, second;
  576. public:
  577. CSelectorsAlternative(const CSelector &First, const CSelector &Second)
  578. :first(First), second(Second)
  579. {
  580. }
  581. bool operator()(const Bonus *bonus) const
  582. {
  583. return first(bonus) || second(bonus);
  584. }
  585. };
  586. CSelector DLL_EXPORT operator||(const CSelector &first, const CSelector &second);
  587. template<typename T>
  588. class CSelectFieldEqual
  589. {
  590. T Bonus::*ptr;
  591. T val;
  592. public:
  593. CSelectFieldEqual(T Bonus::*Ptr, const T &Val)
  594. : ptr(Ptr), val(Val)
  595. {
  596. }
  597. bool operator()(const Bonus *bonus) const
  598. {
  599. return bonus->*ptr == val;
  600. }
  601. CSelectFieldEqual& operator()(const T &setVal)
  602. {
  603. val = setVal;
  604. return *this;
  605. }
  606. };
  607. class DLL_EXPORT CWillLastTurns
  608. {
  609. public:
  610. int turnsRequested;
  611. bool operator()(const Bonus *bonus) const
  612. {
  613. return turnsRequested <= 0 //every present effect will last zero (or "less") turns
  614. || !(bonus->duration & Bonus::N_TURNS) //so do every not expriing after N-turns effect
  615. || bonus->turnsRemain > turnsRequested;
  616. }
  617. CWillLastTurns& operator()(const int &setVal)
  618. {
  619. turnsRequested = setVal;
  620. return *this;
  621. }
  622. };
  623. class DLL_EXPORT CCreatureTypeLimiter : public ILimiter //affect only stacks of given creature (and optionally it's upgrades)
  624. {
  625. public:
  626. const CCreature *creature;
  627. ui8 includeUpgrades;
  628. CCreatureTypeLimiter();
  629. CCreatureTypeLimiter(const CCreature &Creature, ui8 IncludeUpgrades = true);
  630. bool limit(const Bonus *b, const CBonusSystemNode &node) const OVERRIDE;
  631. template <typename Handler> void serialize(Handler &h, const int version)
  632. {
  633. h & creature & includeUpgrades;
  634. }
  635. };
  636. class DLL_EXPORT HasAnotherBonusLimiter : public ILimiter //applies only to nodes that have another bonus working
  637. {
  638. public:
  639. TBonusType type;
  640. TBonusSubtype subtype;
  641. ui8 isSubtypeRelevant; //check for subtype only if this is true
  642. HasAnotherBonusLimiter(TBonusType bonus = Bonus::NONE);
  643. HasAnotherBonusLimiter(TBonusType bonus, TBonusSubtype _subtype);
  644. bool limit(const Bonus *b, const CBonusSystemNode &node) const OVERRIDE;
  645. template <typename Handler> void serialize(Handler &h, const int version)
  646. {
  647. h & type & subtype & isSubtypeRelevant;
  648. }
  649. };
  650. class DLL_EXPORT CreatureNativeTerrainLimiter : public ILimiter //applies only to creatures that are on their native terrain
  651. {
  652. public:
  653. si8 terrainType;
  654. CreatureNativeTerrainLimiter();
  655. CreatureNativeTerrainLimiter(int TerrainType);
  656. bool limit(const Bonus *b, const CBonusSystemNode &node) const OVERRIDE;
  657. template <typename Handler> void serialize(Handler &h, const int version)
  658. {
  659. h & terrainType;
  660. }
  661. };
  662. class DLL_EXPORT CreatureFactionLimiter : public ILimiter //applies only to creatures of given faction
  663. {
  664. public:
  665. si8 faction;
  666. CreatureFactionLimiter();
  667. CreatureFactionLimiter(int TerrainType);
  668. bool limit(const Bonus *b, const CBonusSystemNode &node) const OVERRIDE;
  669. template <typename Handler> void serialize(Handler &h, const int version)
  670. {
  671. h & faction;
  672. }
  673. };
  674. class DLL_EXPORT CreatureAlignmentLimiter : public ILimiter //applies only to creatures of given alignment
  675. {
  676. public:
  677. si8 alignment;
  678. CreatureAlignmentLimiter();
  679. CreatureAlignmentLimiter(si8 Alignment);
  680. bool limit(const Bonus *b, const CBonusSystemNode &node) const OVERRIDE;
  681. template <typename Handler> void serialize(Handler &h, const int version)
  682. {
  683. h & alignment;
  684. }
  685. };
  686. class DLL_EXPORT StackOwnerLimiter : public ILimiter //applies only to creatures of given alignment
  687. {
  688. public:
  689. ui8 owner;
  690. StackOwnerLimiter();
  691. StackOwnerLimiter(ui8 Owner);
  692. bool limit(const Bonus *b, const CBonusSystemNode &node) const OVERRIDE;
  693. template <typename Handler> void serialize(Handler &h, const int version)
  694. {
  695. h & owner;
  696. }
  697. };
  698. class DLL_EXPORT RankRangeLimiter : public ILimiter //applies to creatures with min <= Rank <= max
  699. {
  700. public:
  701. ui8 minRank, maxRank;
  702. RankRangeLimiter();
  703. RankRangeLimiter(ui8 Min, ui8 Max = 255);
  704. bool limit(const Bonus *b, const CBonusSystemNode &node) const OVERRIDE;
  705. template <typename Handler> void serialize(Handler &h, const int version)
  706. {
  707. h & minRank & maxRank;
  708. }
  709. };
  710. const CCreature *retrieveCreature(const CBonusSystemNode *node);
  711. namespace Selector
  712. {
  713. extern DLL_EXPORT CSelectFieldEqual<TBonusType> type;
  714. extern DLL_EXPORT CSelectFieldEqual<TBonusSubtype> subtype;
  715. extern DLL_EXPORT CSelectFieldEqual<si32> info;
  716. extern DLL_EXPORT CSelectFieldEqual<ui16> duration;
  717. extern DLL_EXPORT CSelectFieldEqual<ui8> sourceType;
  718. extern DLL_EXPORT CSelectFieldEqual<ui8> effectRange;
  719. extern DLL_EXPORT CWillLastTurns turns;
  720. CSelector DLL_EXPORT typeSubtype(TBonusType Type, TBonusSubtype Subtype);
  721. CSelector DLL_EXPORT typeSubtypeInfo(TBonusType type, TBonusSubtype subtype, si32 info);
  722. CSelector DLL_EXPORT source(ui8 source, ui32 sourceID);
  723. CSelector DLL_EXPORT durationType(ui16 duration);
  724. CSelector DLL_EXPORT sourceTypeSel(ui8 source);
  725. bool DLL_EXPORT matchesType(const CSelector &sel, TBonusType type);
  726. bool DLL_EXPORT matchesTypeSubtype(const CSelector &sel, TBonusType type, TBonusSubtype subtype);
  727. bool DLL_EXPORT positiveSpellEffects(const Bonus *b);
  728. }
  729. extern DLL_EXPORT const std::map<std::string, int> bonusNameMap;
  730. DLL_EXPORT std::string bonusTypeToString(int type);
  731. // BonusList template that requires full interface of CBonusSystemNode
  732. template <class InputIterator>
  733. void BonusList::insert(const int position, InputIterator first, InputIterator last)
  734. {
  735. bonuses.insert(bonuses.begin() + position, first, last);
  736. if (belongsToTree)
  737. CBonusSystemNode::incrementTreeChangedNum();
  738. }
  739. // Extensions for BOOST_FOREACH to enable iterating of BonusList objects
  740. namespace boost
  741. {
  742. template<>
  743. struct range_mutable_iterator<BonusList>
  744. {
  745. typedef std::vector<Bonus*>::iterator type;
  746. };
  747. template<>
  748. struct range_const_iterator<BonusList>
  749. {
  750. typedef std::vector<Bonus*>::const_iterator type;
  751. };
  752. }