HeroBonus.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  1. /*
  2. * HeroBonus.cpp, 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. #include "StdInc.h"
  11. #include "HeroBonus.h"
  12. #include "VCMI_Lib.h"
  13. #include "spells/CSpellHandler.h"
  14. #include "CCreatureHandler.h"
  15. #include "CCreatureSet.h"
  16. #include "CHeroHandler.h"
  17. #include "CGeneralTextHandler.h"
  18. #include "CSkillHandler.h"
  19. #include "CStack.h"
  20. #include "CArtHandler.h"
  21. #include "StringConstants.h"
  22. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  23. #define FOREACH_CPARENT(pname) TCNodes lparents; getParents(lparents); for(const CBonusSystemNode *pname : lparents)
  24. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  25. #define FOREACH_RED_PARENT(pname) TNodes lparents; getRedParents(lparents); for(CBonusSystemNode *pname : lparents)
  26. #define BONUS_NAME(x) { #x, Bonus::x },
  27. const std::map<std::string, Bonus::BonusType> bonusNameMap = { BONUS_LIST };
  28. #undef BONUS_NAME
  29. #define BONUS_VALUE(x) { #x, Bonus::x },
  30. const std::map<std::string, Bonus::ValueType> bonusValueMap = { BONUS_VALUE_LIST };
  31. #undef BONUS_VALUE
  32. #define BONUS_SOURCE(x) { #x, Bonus::x },
  33. const std::map<std::string, Bonus::BonusSource> bonusSourceMap = { BONUS_SOURCE_LIST };
  34. #undef BONUS_SOURCE
  35. #define BONUS_ITEM(x) { #x, Bonus::x },
  36. const std::map<std::string, ui16> bonusDurationMap =
  37. {
  38. BONUS_ITEM(PERMANENT)
  39. BONUS_ITEM(ONE_BATTLE)
  40. BONUS_ITEM(ONE_DAY)
  41. BONUS_ITEM(ONE_WEEK)
  42. BONUS_ITEM(N_TURNS)
  43. BONUS_ITEM(N_DAYS)
  44. BONUS_ITEM(UNTIL_BEING_ATTACKED)
  45. BONUS_ITEM(UNTIL_ATTACK)
  46. BONUS_ITEM(STACK_GETS_TURN)
  47. BONUS_ITEM(COMMANDER_KILLED)
  48. { "UNITL_BEING_ATTACKED", Bonus::UNTIL_BEING_ATTACKED }//typo, but used in some mods
  49. };
  50. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  51. {
  52. BONUS_ITEM(NO_LIMIT)
  53. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  54. BONUS_ITEM(ONLY_MELEE_FIGHT)
  55. BONUS_ITEM(ONLY_ENEMY_ARMY)
  56. };
  57. const std::map<std::string, TLimiterPtr> bonusLimiterMap =
  58. {
  59. {"SHOOTER_ONLY", std::make_shared<HasAnotherBonusLimiter>(Bonus::SHOOTER)},
  60. {"DRAGON_NATURE", std::make_shared<HasAnotherBonusLimiter>(Bonus::DRAGON_NATURE)},
  61. {"IS_UNDEAD", std::make_shared<HasAnotherBonusLimiter>(Bonus::UNDEAD)}
  62. };
  63. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  64. {
  65. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  66. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  67. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  68. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  69. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  70. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)}
  71. }; //untested
  72. const std::map<std::string, TUpdaterPtr> bonusUpdaterMap =
  73. {
  74. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>()},
  75. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>()}
  76. };
  77. ///CBonusProxy
  78. CBonusProxy::CBonusProxy(const IBonusBearer * Target, CSelector Selector)
  79. : cachedLast(0),
  80. target(Target),
  81. selector(Selector),
  82. data()
  83. {
  84. }
  85. CBonusProxy::CBonusProxy(const CBonusProxy & other)
  86. : cachedLast(other.cachedLast),
  87. target(other.target),
  88. selector(other.selector),
  89. data(other.data)
  90. {
  91. }
  92. CBonusProxy::CBonusProxy(CBonusProxy && other)
  93. : cachedLast(0),
  94. target(other.target),
  95. selector(),
  96. data()
  97. {
  98. std::swap(cachedLast, other.cachedLast);
  99. std::swap(selector, other.selector);
  100. std::swap(data, other.data);
  101. }
  102. CBonusProxy & CBonusProxy::operator=(const CBonusProxy & other)
  103. {
  104. cachedLast = other.cachedLast;
  105. selector = other.selector;
  106. data = other.data;
  107. return *this;
  108. }
  109. CBonusProxy & CBonusProxy::operator=(CBonusProxy && other)
  110. {
  111. std::swap(cachedLast, other.cachedLast);
  112. std::swap(selector, other.selector);
  113. std::swap(data, other.data);
  114. return *this;
  115. }
  116. TBonusListPtr CBonusProxy::get() const
  117. {
  118. if(target->getTreeVersion() != cachedLast || !data)
  119. {
  120. //TODO: support limiters
  121. data = target->getAllBonuses(selector, Selector::all);
  122. data->eliminateDuplicates();
  123. cachedLast = target->getTreeVersion();
  124. }
  125. return data;
  126. }
  127. const BonusList * CBonusProxy::operator->() const
  128. {
  129. return get().get();
  130. }
  131. std::atomic<int32_t> CBonusSystemNode::treeChanged(1);
  132. const bool CBonusSystemNode::cachingEnabled = true;
  133. BonusList::BonusList(bool BelongsToTree) : belongsToTree(BelongsToTree)
  134. {
  135. }
  136. BonusList::BonusList(const BonusList &bonusList)
  137. {
  138. bonuses.resize(bonusList.size());
  139. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  140. belongsToTree = false;
  141. }
  142. BonusList::BonusList(BonusList&& other):
  143. belongsToTree(false)
  144. {
  145. std::swap(belongsToTree, other.belongsToTree);
  146. std::swap(bonuses, other.bonuses);
  147. }
  148. BonusList& BonusList::operator=(const BonusList &bonusList)
  149. {
  150. bonuses.resize(bonusList.size());
  151. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  152. belongsToTree = false;
  153. return *this;
  154. }
  155. void BonusList::changed()
  156. {
  157. if(belongsToTree)
  158. CBonusSystemNode::treeHasChanged();
  159. }
  160. int BonusList::totalValue() const
  161. {
  162. int base = 0;
  163. int percentToBase = 0;
  164. int percentToAll = 0;
  165. int additive = 0;
  166. int indepMax = 0;
  167. bool hasIndepMax = false;
  168. int indepMin = 0;
  169. bool hasIndepMin = false;
  170. for (auto& b : bonuses)
  171. {
  172. switch(b->valType)
  173. {
  174. case Bonus::BASE_NUMBER:
  175. base += b->val;
  176. break;
  177. case Bonus::PERCENT_TO_ALL:
  178. percentToAll += b->val;
  179. break;
  180. case Bonus::PERCENT_TO_BASE:
  181. percentToBase += b->val;
  182. break;
  183. case Bonus::ADDITIVE_VALUE:
  184. additive += b->val;
  185. break;
  186. case Bonus::INDEPENDENT_MAX:
  187. if (!hasIndepMax)
  188. {
  189. indepMax = b->val;
  190. hasIndepMax = true;
  191. }
  192. else
  193. {
  194. vstd::amax(indepMax, b->val);
  195. }
  196. break;
  197. case Bonus::INDEPENDENT_MIN:
  198. if (!hasIndepMin)
  199. {
  200. indepMin = b->val;
  201. hasIndepMin = true;
  202. }
  203. else
  204. {
  205. vstd::amin(indepMin, b->val);
  206. }
  207. break;
  208. }
  209. }
  210. int modifiedBase = base + (base * percentToBase) / 100;
  211. modifiedBase += additive;
  212. int valFirst = (modifiedBase * (100 + percentToAll)) / 100;
  213. if(hasIndepMin && hasIndepMax)
  214. assert(indepMin < indepMax);
  215. const int notIndepBonuses = boost::count_if(bonuses, [](const std::shared_ptr<Bonus>& b)
  216. {
  217. return b->valType != Bonus::INDEPENDENT_MAX && b->valType != Bonus::INDEPENDENT_MIN;
  218. });
  219. if (hasIndepMax)
  220. {
  221. if(notIndepBonuses)
  222. vstd::amax(valFirst, indepMax);
  223. else
  224. valFirst = indepMax;
  225. }
  226. if (hasIndepMin)
  227. {
  228. if(notIndepBonuses)
  229. vstd::amin(valFirst, indepMin);
  230. else
  231. valFirst = indepMin;
  232. }
  233. return valFirst;
  234. }
  235. std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &select)
  236. {
  237. for (auto & b : bonuses)
  238. {
  239. if(select(b.get()))
  240. return b;
  241. }
  242. return nullptr;
  243. }
  244. const std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &selector) const
  245. {
  246. for (auto & b : bonuses)
  247. {
  248. if(selector(b.get()))
  249. return b;
  250. }
  251. return nullptr;
  252. }
  253. void BonusList::getBonuses(BonusList & out, const CSelector &selector) const
  254. {
  255. getBonuses(out, selector, nullptr);
  256. }
  257. void BonusList::getBonuses(BonusList & out, const CSelector &selector, const CSelector &limit) const
  258. {
  259. for (auto & b : bonuses)
  260. {
  261. //add matching bonuses that matches limit predicate or have NO_LIMIT if no given predicate
  262. if(selector(b.get()) && ((!limit && b->effectRange == Bonus::NO_LIMIT) || ((bool)limit && limit(b.get()))))
  263. out.push_back(b);
  264. }
  265. }
  266. void BonusList::getAllBonuses(BonusList &out) const
  267. {
  268. for(auto & b : bonuses)
  269. out.push_back(b);
  270. }
  271. int BonusList::valOfBonuses(const CSelector &select) const
  272. {
  273. BonusList ret;
  274. CSelector limit = nullptr;
  275. getBonuses(ret, select, limit);
  276. ret.eliminateDuplicates();
  277. return ret.totalValue();
  278. }
  279. void BonusList::eliminateDuplicates()
  280. {
  281. sort( bonuses.begin(), bonuses.end() );
  282. bonuses.erase( unique( bonuses.begin(), bonuses.end() ), bonuses.end() );
  283. }
  284. void BonusList::push_back(std::shared_ptr<Bonus> x)
  285. {
  286. bonuses.push_back(x);
  287. changed();
  288. }
  289. BonusList::TInternalContainer::iterator BonusList::erase(const int position)
  290. {
  291. changed();
  292. return bonuses.erase(bonuses.begin() + position);
  293. }
  294. void BonusList::clear()
  295. {
  296. bonuses.clear();
  297. changed();
  298. }
  299. std::vector<BonusList*>::size_type BonusList::operator-=(std::shared_ptr<Bonus> const &i)
  300. {
  301. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  302. if(itr == bonuses.end())
  303. return false;
  304. bonuses.erase(itr);
  305. changed();
  306. return true;
  307. }
  308. void BonusList::resize(BonusList::TInternalContainer::size_type sz, std::shared_ptr<Bonus> c )
  309. {
  310. bonuses.resize(sz, c);
  311. changed();
  312. }
  313. void BonusList::insert(BonusList::TInternalContainer::iterator position, BonusList::TInternalContainer::size_type n, std::shared_ptr<Bonus> const &x)
  314. {
  315. bonuses.insert(position, n, x);
  316. changed();
  317. }
  318. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  319. {
  320. return valOfBonuses(Selector::type(type).And(selector));
  321. }
  322. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype) const
  323. {
  324. std::stringstream cachingStr;
  325. cachingStr << "type_" << type << "s_" << subtype;
  326. CSelector s = Selector::type(type);
  327. if(subtype != -1)
  328. s = s.And(Selector::subtype(subtype));
  329. return valOfBonuses(s, cachingStr.str());
  330. }
  331. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  332. {
  333. CSelector limit = nullptr;
  334. TBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  335. return hlp->totalValue();
  336. }
  337. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  338. {
  339. return getBonuses(selector, cachingStr)->size() > 0;
  340. }
  341. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  342. {
  343. return getBonuses(selector, limit, cachingStr)->size() > 0;
  344. }
  345. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  346. {
  347. std::stringstream cachingStr;
  348. cachingStr << "type_" << type << "s_" << subtype;
  349. CSelector s = Selector::type(type);
  350. if(subtype != -1)
  351. s = s.And(Selector::subtype(subtype));
  352. return hasBonus(s, cachingStr.str());
  353. }
  354. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  355. {
  356. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  357. }
  358. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  359. {
  360. return getAllBonuses(selector, limit, nullptr, cachingStr);
  361. }
  362. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  363. {
  364. std::stringstream cachingStr;
  365. cachingStr << "source_" << source << "id_" << sourceID;
  366. return hasBonus(Selector::source(source,sourceID), cachingStr.str());
  367. }
  368. int IBonusBearer::MoraleVal() const
  369. {
  370. if(hasBonusOfType(Bonus::NON_LIVING) || hasBonusOfType(Bonus::UNDEAD) ||
  371. hasBonusOfType(Bonus::NO_MORALE) || hasBonusOfType(Bonus::SIEGE_WEAPON))
  372. return 0;
  373. int ret = valOfBonuses(Bonus::MORALE);
  374. if(hasBonusOfType(Bonus::SELF_MORALE)) //eg. minotaur
  375. vstd::amax(ret, +1);
  376. return vstd::abetween(ret, -3, +3);
  377. }
  378. int IBonusBearer::LuckVal() const
  379. {
  380. if(hasBonusOfType(Bonus::NO_LUCK))
  381. return 0;
  382. int ret = valOfBonuses(Bonus::LUCK);
  383. if(hasBonusOfType(Bonus::SELF_LUCK)) //eg. halfling
  384. vstd::amax(ret, +1);
  385. return vstd::abetween(ret, -3, +3);
  386. }
  387. ui32 IBonusBearer::MaxHealth() const
  388. {
  389. const std::string cachingStr = "type_STACK_HEALTH";
  390. static const auto selector = Selector::type(Bonus::STACK_HEALTH);
  391. auto value = valOfBonuses(selector, cachingStr);
  392. return std::max(1, value); //never 0
  393. }
  394. int IBonusBearer::getAttack(bool ranged) const
  395. {
  396. const std::string cachingStr = "type_PRIMARY_SKILLs_ATTACK";
  397. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  398. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  399. }
  400. int IBonusBearer::getDefence(bool ranged) const
  401. {
  402. const std::string cachingStr = "type_PRIMARY_SKILLs_DEFENSE";
  403. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  404. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  405. }
  406. int IBonusBearer::getMinDamage(bool ranged) const
  407. {
  408. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_1";
  409. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1));
  410. return valOfBonuses(selector, cachingStr);
  411. }
  412. int IBonusBearer::getMaxDamage(bool ranged) const
  413. {
  414. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_2";
  415. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2));
  416. return valOfBonuses(selector, cachingStr);
  417. }
  418. si32 IBonusBearer::manaLimit() const
  419. {
  420. return si32(getPrimSkillLevel(PrimarySkill::KNOWLEDGE)
  421. * (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::INTELLIGENCE))
  422. / 10.0);
  423. }
  424. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  425. {
  426. int ret = valOfBonuses(Bonus::PRIMARY_SKILL, id);
  427. vstd::amax(ret, id/2); //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  428. return ret;
  429. }
  430. si32 IBonusBearer::magicResistance() const
  431. {
  432. return valOfBonuses(Bonus::MAGIC_RESISTANCE);
  433. }
  434. ui32 IBonusBearer::Speed(int turn, bool useBind) const
  435. {
  436. //war machines cannot move
  437. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON).And(Selector::turns(turn))))
  438. {
  439. return 0;
  440. }
  441. //bind effect check - doesn't influence stack initiative
  442. if(useBind && hasBonus(Selector::type(Bonus::BIND_EFFECT).And(Selector::turns(turn))))
  443. {
  444. return 0;
  445. }
  446. return valOfBonuses(Selector::type(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  447. }
  448. bool IBonusBearer::isLiving() const //TODO: theoreticaly there exists "LIVING" bonus in stack experience documentation
  449. {
  450. std::stringstream cachingStr;
  451. cachingStr << "type_" << Bonus::UNDEAD << "s_-1Otype_" << Bonus::NON_LIVING << "s_-11type_" << Bonus::SIEGE_WEAPON; //I don't really get what string labels mean?
  452. return !hasBonus(Selector::type(Bonus::UNDEAD)
  453. .Or(Selector::type(Bonus::NON_LIVING))
  454. .Or(Selector::type(Bonus::SIEGE_WEAPON)), cachingStr.str());
  455. }
  456. const std::shared_ptr<Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  457. {
  458. auto bonuses = getAllBonuses(selector, Selector::all);
  459. return bonuses->getFirst(Selector::all);
  460. }
  461. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector &selector)
  462. {
  463. auto ret = bonuses.getFirst(selector);
  464. if(ret)
  465. return ret;
  466. FOREACH_PARENT(pname)
  467. {
  468. ret = pname->getBonusLocalFirst(selector);
  469. if (ret)
  470. return ret;
  471. }
  472. return nullptr;
  473. }
  474. const std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst( const CSelector &selector ) const
  475. {
  476. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  477. }
  478. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  479. {
  480. for (auto & elem : parents)
  481. {
  482. const CBonusSystemNode *parent = elem;
  483. out.insert(parent);
  484. }
  485. }
  486. void CBonusSystemNode::getParents(TNodes &out)
  487. {
  488. for (auto & elem : parents)
  489. {
  490. const CBonusSystemNode *parent = elem;
  491. out.insert(const_cast<CBonusSystemNode*>(parent));
  492. }
  493. }
  494. void CBonusSystemNode::getBonusesRec(BonusList &out, const CSelector &selector, const CSelector &limit) const
  495. {
  496. BonusList beforeUpdate;
  497. FOREACH_CPARENT(p)
  498. {
  499. p->getBonusesRec(beforeUpdate, selector, limit);
  500. }
  501. bonuses.getBonuses(beforeUpdate, selector, limit);
  502. for(auto b : beforeUpdate)
  503. out.push_back(update(b));
  504. }
  505. void CBonusSystemNode::getAllBonusesRec(BonusList &out) const
  506. {
  507. BonusList beforeUpdate;
  508. FOREACH_CPARENT(p)
  509. {
  510. p->getAllBonusesRec(beforeUpdate);
  511. }
  512. bonuses.getAllBonuses(beforeUpdate);
  513. for(auto b : beforeUpdate)
  514. out.push_back(update(b));
  515. }
  516. const TBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  517. {
  518. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  519. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  520. {
  521. // Exclusive access for one thread
  522. static boost::mutex m;
  523. boost::mutex::scoped_lock lock(m);
  524. // If the bonus system tree changes(state of a single node or the relations to each other) then
  525. // cache all bonus objects. Selector objects doesn't matter.
  526. if (cachedLast != treeChanged)
  527. {
  528. cachedBonuses.clear();
  529. cachedRequests.clear();
  530. BonusList allBonuses;
  531. getAllBonusesRec(allBonuses);
  532. allBonuses.eliminateDuplicates();
  533. limitBonuses(allBonuses, cachedBonuses);
  534. cachedLast = treeChanged;
  535. }
  536. // If a bonus system request comes with a caching string then look up in the map if there are any
  537. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  538. if (cachingStr != "")
  539. {
  540. auto it = cachedRequests.find(cachingStr);
  541. if(it != cachedRequests.end())
  542. {
  543. //Cached list contains bonuses for our query with applied limiters
  544. return it->second;
  545. }
  546. }
  547. //We still don't have the bonuses (didn't returned them from cache)
  548. //Perform bonus selection
  549. auto ret = std::make_shared<BonusList>();
  550. cachedBonuses.getBonuses(*ret, selector, limit);
  551. // Save the results in the cache
  552. if(cachingStr != "")
  553. cachedRequests[cachingStr] = ret;
  554. return ret;
  555. }
  556. else
  557. {
  558. return getAllBonusesWithoutCaching(selector, limit, root);
  559. }
  560. }
  561. const TBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  562. {
  563. auto ret = std::make_shared<BonusList>();
  564. // Get bonus results without caching enabled.
  565. BonusList beforeLimiting, afterLimiting;
  566. getAllBonusesRec(beforeLimiting);
  567. beforeLimiting.eliminateDuplicates();
  568. if(!root || root == this)
  569. {
  570. limitBonuses(beforeLimiting, afterLimiting);
  571. afterLimiting.getBonuses(*ret, selector, limit);
  572. }
  573. else if(root)
  574. {
  575. //We want to limit our query against an external node. We get all its bonuses,
  576. // add the ones we're considering and see if they're cut out by limiters
  577. BonusList rootBonuses, limitedRootBonuses;
  578. getAllBonusesRec(rootBonuses);
  579. for(auto b : beforeLimiting)
  580. rootBonuses.push_back(b);
  581. rootBonuses.eliminateDuplicates();
  582. root->limitBonuses(rootBonuses, limitedRootBonuses);
  583. for(auto b : beforeLimiting)
  584. if(vstd::contains(limitedRootBonuses, b))
  585. afterLimiting.push_back(b);
  586. afterLimiting.getBonuses(*ret, selector, limit);
  587. }
  588. return ret;
  589. }
  590. const std::shared_ptr<Bonus> CBonusSystemNode::update(const std::shared_ptr<Bonus> b) const
  591. {
  592. if(b->updater)
  593. return b->updater->update(b, *this);
  594. return b;
  595. }
  596. CBonusSystemNode::CBonusSystemNode()
  597. : bonuses(true),
  598. exportedBonuses(true),
  599. nodeType(UNKNOWN),
  600. cachedLast(0)
  601. {
  602. }
  603. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType)
  604. : bonuses(true),
  605. exportedBonuses(true),
  606. nodeType(NodeType),
  607. cachedLast(0)
  608. {
  609. }
  610. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other):
  611. bonuses(std::move(other.bonuses)),
  612. exportedBonuses(std::move(other.exportedBonuses)),
  613. nodeType(other.nodeType),
  614. description(other.description),
  615. cachedLast(0)
  616. {
  617. std::swap(parents, other.parents);
  618. std::swap(children, other.children);
  619. //fixing bonus tree without recalculation
  620. for(CBonusSystemNode * n : parents)
  621. {
  622. n->children -= &other;
  623. n->children.push_back(this);
  624. }
  625. for(CBonusSystemNode * n : children)
  626. {
  627. n->parents -= &other;
  628. n->parents.push_back(this);
  629. }
  630. //cache ignored
  631. //cachedBonuses
  632. //cachedRequests
  633. }
  634. CBonusSystemNode::~CBonusSystemNode()
  635. {
  636. detachFromAll();
  637. if(children.size())
  638. {
  639. while(children.size())
  640. children.front()->detachFrom(this);
  641. }
  642. }
  643. void CBonusSystemNode::attachTo(CBonusSystemNode *parent)
  644. {
  645. assert(!vstd::contains(parents, parent));
  646. parents.push_back(parent);
  647. if(parent->actsAsBonusSourceOnly())
  648. parent->newRedDescendant(this);
  649. else
  650. newRedDescendant(parent);
  651. parent->newChildAttached(this);
  652. CBonusSystemNode::treeHasChanged();
  653. }
  654. void CBonusSystemNode::detachFrom(CBonusSystemNode *parent)
  655. {
  656. assert(vstd::contains(parents, parent));
  657. if(parent->actsAsBonusSourceOnly())
  658. parent->removedRedDescendant(this);
  659. else
  660. removedRedDescendant(parent);
  661. parents -= parent;
  662. parent->childDetached(this);
  663. CBonusSystemNode::treeHasChanged();
  664. }
  665. void CBonusSystemNode::popBonuses(const CSelector &s)
  666. {
  667. BonusList bl;
  668. exportedBonuses.getBonuses(bl, s, Selector::all);
  669. for(auto b : bl)
  670. removeBonus(b);
  671. for(CBonusSystemNode *child : children)
  672. child->popBonuses(s);
  673. }
  674. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  675. {
  676. BonusList bl;
  677. exportedBonuses.getBonuses(bl, s, Selector::all);
  678. for(auto b : bl)
  679. {
  680. b->turnsRemain--;
  681. if(b->turnsRemain <= 0)
  682. removeBonus(b);
  683. }
  684. for(CBonusSystemNode *child : children)
  685. child->reduceBonusDurations(s);
  686. }
  687. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  688. {
  689. //turnsRemain shouldn't be zero for following durations
  690. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  691. {
  692. assert(b->turnsRemain);
  693. }
  694. assert(!vstd::contains(exportedBonuses, b));
  695. exportedBonuses.push_back(b);
  696. exportBonus(b);
  697. CBonusSystemNode::treeHasChanged();
  698. }
  699. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  700. {
  701. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  702. if(bonus)
  703. bonus->val += b->val;
  704. else
  705. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  706. }
  707. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  708. {
  709. exportedBonuses -= b;
  710. if(b->propagator)
  711. unpropagateBonus(b);
  712. else
  713. bonuses -= b;
  714. CBonusSystemNode::treeHasChanged();
  715. }
  716. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  717. {
  718. switch(nodeType)
  719. {
  720. case CREATURE:
  721. case ARTIFACT:
  722. case ARTIFACT_INSTANCE:
  723. return true;
  724. default:
  725. return false;
  726. }
  727. }
  728. void CBonusSystemNode::propagateBonus(std::shared_ptr<Bonus> b)
  729. {
  730. if(b->propagator->shouldBeAttached(this))
  731. {
  732. bonuses.push_back(b);
  733. logBonus->trace("#$# %s #propagated to# %s", b->Description(), nodeName());
  734. }
  735. FOREACH_RED_CHILD(child)
  736. child->propagateBonus(b);
  737. }
  738. void CBonusSystemNode::unpropagateBonus(std::shared_ptr<Bonus> b)
  739. {
  740. if(b->propagator->shouldBeAttached(this))
  741. {
  742. bonuses -= b;
  743. while(vstd::contains(bonuses, b))
  744. {
  745. logBonus->error("Bonus was duplicated (%s) at %s", b->Description(), nodeName());
  746. bonuses -= b;
  747. }
  748. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  749. }
  750. FOREACH_RED_CHILD(child)
  751. child->unpropagateBonus(b);
  752. }
  753. void CBonusSystemNode::newChildAttached(CBonusSystemNode *child)
  754. {
  755. assert(!vstd::contains(children, child));
  756. children.push_back(child);
  757. }
  758. void CBonusSystemNode::childDetached(CBonusSystemNode *child)
  759. {
  760. if (vstd::contains(children, child))
  761. children -= child;
  762. else
  763. {
  764. logBonus->error("Error! %s #cannot be detached from# %s", child->nodeName(), nodeName());
  765. throw std::runtime_error("internal error");
  766. }
  767. }
  768. void CBonusSystemNode::detachFromAll()
  769. {
  770. while(parents.size())
  771. detachFrom(parents.front());
  772. }
  773. bool CBonusSystemNode::isIndependentNode() const
  774. {
  775. return parents.empty() && children.empty();
  776. }
  777. std::string CBonusSystemNode::nodeName() const
  778. {
  779. return description.size()
  780. ? description
  781. : std::string("Bonus system node of type ") + typeid(*this).name();
  782. }
  783. void CBonusSystemNode::deserializationFix()
  784. {
  785. exportBonuses();
  786. }
  787. void CBonusSystemNode::getRedParents(TNodes &out)
  788. {
  789. FOREACH_PARENT(pname)
  790. {
  791. if(pname->actsAsBonusSourceOnly())
  792. {
  793. out.insert(pname);
  794. }
  795. }
  796. if(!actsAsBonusSourceOnly())
  797. {
  798. for(CBonusSystemNode *child : children)
  799. {
  800. out.insert(child);
  801. }
  802. }
  803. }
  804. void CBonusSystemNode::getRedChildren(TNodes &out)
  805. {
  806. FOREACH_PARENT(pname)
  807. {
  808. if(!pname->actsAsBonusSourceOnly())
  809. {
  810. out.insert(pname);
  811. }
  812. }
  813. if(actsAsBonusSourceOnly())
  814. {
  815. for(CBonusSystemNode *child : children)
  816. {
  817. out.insert(child);
  818. }
  819. }
  820. }
  821. void CBonusSystemNode::newRedDescendant(CBonusSystemNode *descendant)
  822. {
  823. for(auto b : exportedBonuses)
  824. if(b->propagator)
  825. descendant->propagateBonus(b);
  826. FOREACH_RED_PARENT(parent)
  827. parent->newRedDescendant(descendant);
  828. }
  829. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode *descendant)
  830. {
  831. for(auto b : exportedBonuses)
  832. if(b->propagator)
  833. descendant->unpropagateBonus(b);
  834. FOREACH_RED_PARENT(parent)
  835. parent->removedRedDescendant(descendant);
  836. }
  837. void CBonusSystemNode::getRedAncestors(TNodes &out)
  838. {
  839. getRedParents(out);
  840. FOREACH_RED_PARENT(p)
  841. p->getRedAncestors(out);
  842. }
  843. void CBonusSystemNode::getRedDescendants(TNodes &out)
  844. {
  845. getRedChildren(out);
  846. FOREACH_RED_CHILD(c)
  847. c->getRedChildren(out);
  848. }
  849. void CBonusSystemNode::exportBonus(std::shared_ptr<Bonus> b)
  850. {
  851. if(b->propagator)
  852. propagateBonus(b);
  853. else
  854. bonuses.push_back(b);
  855. CBonusSystemNode::treeHasChanged();
  856. }
  857. void CBonusSystemNode::exportBonuses()
  858. {
  859. for(auto b : exportedBonuses)
  860. exportBonus(b);
  861. }
  862. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  863. {
  864. return nodeType;
  865. }
  866. const BonusList& CBonusSystemNode::getBonusList() const
  867. {
  868. return bonuses;
  869. }
  870. const TNodesVector& CBonusSystemNode::getParentNodes() const
  871. {
  872. return parents;
  873. }
  874. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  875. {
  876. return children;
  877. }
  878. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  879. {
  880. nodeType = type;
  881. }
  882. BonusList& CBonusSystemNode::getExportedBonusList()
  883. {
  884. return exportedBonuses;
  885. }
  886. const std::string& CBonusSystemNode::getDescription() const
  887. {
  888. return description;
  889. }
  890. void CBonusSystemNode::setDescription(const std::string &description)
  891. {
  892. this->description = description;
  893. }
  894. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  895. {
  896. assert(&allBonuses != &out); //todo should it work in-place?
  897. BonusList undecided = allBonuses,
  898. &accepted = out;
  899. while(true)
  900. {
  901. int undecidedCount = undecided.size();
  902. for(int i = 0; i < undecided.size(); i++)
  903. {
  904. auto b = undecided[i];
  905. BonusLimitationContext context = {b, *this, out};
  906. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  907. if(decision == ILimiter::DISCARD)
  908. {
  909. undecided.erase(i);
  910. i--; continue;
  911. }
  912. else if(decision == ILimiter::ACCEPT)
  913. {
  914. accepted.push_back(b);
  915. undecided.erase(i);
  916. i--; continue;
  917. }
  918. else
  919. assert(decision == ILimiter::NOT_SURE);
  920. }
  921. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  922. return;
  923. }
  924. }
  925. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  926. {
  927. auto ret = std::make_shared<BonusList>();
  928. limitBonuses(allBonuses, *ret);
  929. return ret;
  930. }
  931. void CBonusSystemNode::treeHasChanged()
  932. {
  933. treeChanged++;
  934. }
  935. int64_t CBonusSystemNode::getTreeVersion() const
  936. {
  937. int64_t ret = treeChanged;
  938. return ret << 32;
  939. }
  940. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  941. {
  942. if(obj)
  943. return obj->valOfBonuses(type, subtype);
  944. return 0;
  945. }
  946. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  947. {
  948. if(obj)
  949. return obj->hasBonusOfType(type, subtype);
  950. return false;
  951. }
  952. std::string Bonus::Description() const
  953. {
  954. std::ostringstream str;
  955. if(description.empty())
  956. switch(source)
  957. {
  958. case ARTIFACT:
  959. str << VLC->arth->artifacts[sid]->Name();
  960. break;
  961. case SPELL_EFFECT:
  962. str << SpellID(sid).toSpell()->name;
  963. break;
  964. case CREATURE_ABILITY:
  965. str << VLC->creh->creatures[sid]->namePl;
  966. break;
  967. case SECONDARY_SKILL:
  968. str << VLC->skillh->skillName(sid);
  969. break;
  970. default:
  971. //todo: handle all possible sources
  972. str << "Unknown";
  973. break;
  974. }
  975. else
  976. str << description;
  977. if(val != 0)
  978. str << " " << std::showpos << val;
  979. return str.str();
  980. }
  981. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  982. {
  983. switch(type)
  984. {
  985. case Bonus::PRIMARY_SKILL:
  986. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  987. case Bonus::SECONDARY_SKILL_PREMY:
  988. return JsonUtils::stringNode("skill." + NSecondarySkill::names[subtype]);
  989. case Bonus::SPECIAL_SPELL_LEV:
  990. case Bonus::SPECIFIC_SPELL_DAMAGE:
  991. case Bonus::SPECIAL_BLESS_DAMAGE:
  992. case Bonus::MAXED_SPELL:
  993. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  994. return JsonUtils::stringNode("spell." + (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier);
  995. case Bonus::SPECIAL_UPGRADE:
  996. return JsonUtils::stringNode("creature." + CreatureID::encode(subtype));
  997. case Bonus::GENERATE_RESOURCE:
  998. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  999. default:
  1000. return JsonUtils::intNode(subtype);
  1001. }
  1002. }
  1003. JsonNode additionalInfoToJson(Bonus::BonusType type, int addInfo)
  1004. {
  1005. switch(type)
  1006. {
  1007. case Bonus::SPECIAL_UPGRADE:
  1008. return JsonUtils::stringNode("creature." + CreatureID::encode(addInfo));
  1009. default:
  1010. return JsonUtils::intNode(addInfo);
  1011. }
  1012. }
  1013. JsonNode Bonus::toJsonNode() const
  1014. {
  1015. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1016. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1017. if(subtype != -1)
  1018. root["subtype"] = subtypeToJson(type, subtype);
  1019. if(additionalInfo != -1)
  1020. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1021. if(val != 0)
  1022. root["val"].Integer() = val;
  1023. if(valType != ADDITIVE_VALUE)
  1024. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1025. if(limiter)
  1026. root["limiters"].Vector().push_back(limiter->toJsonNode());
  1027. if(updater)
  1028. root["updater"] = updater->toJsonNode();
  1029. return root;
  1030. }
  1031. std::string Bonus::nameForBonus() const
  1032. {
  1033. switch(type)
  1034. {
  1035. case Bonus::PRIMARY_SKILL:
  1036. return PrimarySkill::names[subtype];
  1037. case Bonus::SECONDARY_SKILL_PREMY:
  1038. return NSecondarySkill::names[subtype];
  1039. case Bonus::SPECIAL_SPELL_LEV:
  1040. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1041. case Bonus::SPECIAL_BLESS_DAMAGE:
  1042. case Bonus::MAXED_SPELL:
  1043. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1044. return (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier;
  1045. case Bonus::SPECIAL_UPGRADE:
  1046. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo);
  1047. case Bonus::GENERATE_RESOURCE:
  1048. return GameConstants::RESOURCE_NAMES[subtype];
  1049. case Bonus::STACKS_SPEED:
  1050. return "speed";
  1051. default:
  1052. return vstd::findKey(bonusNameMap, type);
  1053. }
  1054. }
  1055. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype)
  1056. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  1057. {
  1058. additionalInfo = -1;
  1059. turnsRemain = 0;
  1060. valType = ADDITIVE_VALUE;
  1061. effectRange = NO_LIMIT;
  1062. boost::algorithm::trim(description);
  1063. }
  1064. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType)
  1065. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  1066. {
  1067. additionalInfo = -1;
  1068. turnsRemain = 0;
  1069. effectRange = NO_LIMIT;
  1070. }
  1071. Bonus::Bonus()
  1072. {
  1073. duration = PERMANENT;
  1074. turnsRemain = 0;
  1075. type = NONE;
  1076. subtype = -1;
  1077. additionalInfo = -1;
  1078. valType = ADDITIVE_VALUE;
  1079. effectRange = NO_LIMIT;
  1080. val = 0;
  1081. source = OTHER;
  1082. sid = 0;
  1083. }
  1084. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  1085. {
  1086. propagator = Propagator;
  1087. return this->shared_from_this();
  1088. }
  1089. namespace Selector
  1090. {
  1091. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> type(&Bonus::type);
  1092. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> subtype(&Bonus::subtype);
  1093. DLL_LINKAGE CSelectFieldEqual<si32> info(&Bonus::additionalInfo);
  1094. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> sourceType(&Bonus::source);
  1095. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> effectRange(&Bonus::effectRange);
  1096. DLL_LINKAGE CWillLastTurns turns;
  1097. DLL_LINKAGE CWillLastDays days;
  1098. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1099. {
  1100. return type(Type).And(subtype(Subtype));
  1101. }
  1102. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, si32 info)
  1103. {
  1104. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1105. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1106. .And(CSelectFieldEqual<si32>(&Bonus::additionalInfo)(info));
  1107. }
  1108. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1109. {
  1110. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1111. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1112. }
  1113. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1114. {
  1115. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1116. }
  1117. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1118. {
  1119. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1120. }
  1121. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1122. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1123. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1124. {
  1125. Bonus dummy;
  1126. dummy.type = type;
  1127. return sel(&dummy);
  1128. }
  1129. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1130. {
  1131. Bonus dummy;
  1132. dummy.type = type;
  1133. dummy.subtype = subtype;
  1134. return sel(&dummy);
  1135. }
  1136. }
  1137. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  1138. {
  1139. switch(node->getNodeType())
  1140. {
  1141. case CBonusSystemNode::STACK_BATTLE:
  1142. return static_cast<const CStack*>(node);
  1143. default:
  1144. return nullptr;
  1145. }
  1146. }
  1147. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  1148. {
  1149. switch(node->getNodeType())
  1150. {
  1151. case CBonusSystemNode::STACK_INSTANCE:
  1152. return (static_cast<const CStackInstance *>(node));
  1153. case CBonusSystemNode::STACK_BATTLE:
  1154. return (static_cast<const CStack*>(node))->base;
  1155. default:
  1156. return nullptr;
  1157. }
  1158. }
  1159. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1160. {
  1161. switch(node->getNodeType())
  1162. {
  1163. case CBonusSystemNode::CREATURE:
  1164. return (static_cast<const CCreature *>(node));
  1165. case CBonusSystemNode::STACK_BATTLE:
  1166. return (static_cast<const CStack*>(node))->type;
  1167. default:
  1168. const CStackInstance * csi = retrieveStackInstance(node);
  1169. if(csi)
  1170. return csi->type;
  1171. return nullptr;
  1172. }
  1173. }
  1174. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1175. {
  1176. for (ui32 i = 0; i < bonusList.size(); i++)
  1177. {
  1178. auto b = bonusList[i];
  1179. out << "Bonus " << i << "\n" << *b << std::endl;
  1180. }
  1181. return out;
  1182. }
  1183. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1184. {
  1185. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1186. if(i->second == bonus.type)
  1187. out << "\tType: " << i->first << " \t";
  1188. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1189. printField(val);
  1190. printField(subtype);
  1191. printField(duration);
  1192. printField(source);
  1193. printField(sid);
  1194. printField(additionalInfo);
  1195. printField(turnsRemain);
  1196. printField(valType);
  1197. printField(effectRange);
  1198. #undef printField
  1199. if(bonus.limiter)
  1200. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1201. if(bonus.updater)
  1202. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1203. return out;
  1204. }
  1205. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1206. {
  1207. if (limiter)
  1208. {
  1209. //If we already have limiter list, retrieve it
  1210. auto limiterList = std::dynamic_pointer_cast<LimiterList>(limiter);
  1211. if(!limiterList)
  1212. {
  1213. //Create a new limiter list with old limiter and the new one will be pushed later
  1214. limiterList = std::make_shared<LimiterList>();
  1215. limiterList->add(limiter);
  1216. limiter = limiterList;
  1217. }
  1218. limiterList->add(Limiter);
  1219. }
  1220. else
  1221. {
  1222. limiter = Limiter;
  1223. }
  1224. return this->shared_from_this();
  1225. }
  1226. ILimiter::~ILimiter()
  1227. {
  1228. }
  1229. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1230. {
  1231. return false;
  1232. }
  1233. std::string ILimiter::toString() const
  1234. {
  1235. return typeid(*this).name();
  1236. }
  1237. JsonNode ILimiter::toJsonNode() const
  1238. {
  1239. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1240. root["type"].String() = toString();
  1241. return root;
  1242. }
  1243. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1244. {
  1245. const CCreature *c = retrieveCreature(&context.node);
  1246. if(!c)
  1247. return true;
  1248. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1249. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1250. }
  1251. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature &Creature, bool IncludeUpgrades)
  1252. :creature(&Creature), includeUpgrades(IncludeUpgrades)
  1253. {
  1254. }
  1255. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1256. {
  1257. creature = nullptr;
  1258. includeUpgrades = false;
  1259. }
  1260. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1261. {
  1262. creature = VLC->creh->creatures[id];
  1263. }
  1264. std::string CCreatureTypeLimiter::toString() const
  1265. {
  1266. char buf[100];
  1267. sprintf(buf, "CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)",
  1268. creature->identifier.c_str(),
  1269. (includeUpgrades ? "true" : "false"));
  1270. return std::string(buf);
  1271. }
  1272. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1273. {
  1274. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1275. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1276. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->identifier));
  1277. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1278. return root;
  1279. }
  1280. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1281. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1282. {
  1283. }
  1284. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1285. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1286. {
  1287. }
  1288. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1289. {
  1290. CSelector mySelector = isSubtypeRelevant
  1291. ? Selector::typeSubtype(type, subtype)
  1292. : Selector::type(type);
  1293. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1294. if(context.alreadyAccepted.getFirst(mySelector))
  1295. return ACCEPT;
  1296. //do not accept for now but it may change if more bonuses gets included
  1297. return NOT_SURE;
  1298. }
  1299. std::string HasAnotherBonusLimiter::toString() const
  1300. {
  1301. char buf[100];
  1302. std::string typeName = vstd::findKey(bonusNameMap, type);
  1303. if(isSubtypeRelevant)
  1304. sprintf(buf, "HasAnotherBonusLimiter(type=%s, subtype=%d)", typeName.c_str(), subtype);
  1305. else
  1306. sprintf(buf, "HasAnotherBonusLimiter(type=%s)", typeName.c_str());
  1307. return std::string(buf);
  1308. }
  1309. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  1310. {
  1311. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1312. std::string typeName = vstd::findKey(bonusNameMap, type);
  1313. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  1314. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  1315. if(isSubtypeRelevant)
  1316. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  1317. return root;
  1318. }
  1319. IPropagator::~IPropagator()
  1320. {
  1321. }
  1322. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1323. {
  1324. return false;
  1325. }
  1326. CPropagatorNodeType::CPropagatorNodeType()
  1327. :nodeType(0)
  1328. {
  1329. }
  1330. CPropagatorNodeType::CPropagatorNodeType(int NodeType)
  1331. : nodeType(NodeType)
  1332. {
  1333. }
  1334. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1335. {
  1336. return nodeType == dest->getNodeType();
  1337. }
  1338. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter(int TerrainType)
  1339. : terrainType(TerrainType)
  1340. {
  1341. }
  1342. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter()
  1343. : terrainType(-1)
  1344. {
  1345. }
  1346. int CreatureNativeTerrainLimiter::limit(const BonusLimitationContext &context) const
  1347. {
  1348. const CCreature *c = retrieveCreature(&context.node);
  1349. return !c || !c->isItNativeTerrain(terrainType); //drop bonus for non-creatures or non-native residents
  1350. //TODO neutral creatues
  1351. }
  1352. CreatureFactionLimiter::CreatureFactionLimiter(int Faction)
  1353. : faction(Faction)
  1354. {
  1355. }
  1356. CreatureFactionLimiter::CreatureFactionLimiter()
  1357. : faction(-1)
  1358. {
  1359. }
  1360. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1361. {
  1362. const CCreature *c = retrieveCreature(&context.node);
  1363. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1364. }
  1365. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1366. : alignment(-1)
  1367. {
  1368. }
  1369. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1370. : alignment(Alignment)
  1371. {
  1372. }
  1373. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1374. {
  1375. const CCreature *c = retrieveCreature(&context.node);
  1376. if(!c)
  1377. return true;
  1378. switch(alignment)
  1379. {
  1380. case EAlignment::GOOD:
  1381. return !c->isGood(); //if not good -> return true (drop bonus)
  1382. case EAlignment::NEUTRAL:
  1383. return c->isEvil() || c->isGood();
  1384. case EAlignment::EVIL:
  1385. return !c->isEvil();
  1386. default:
  1387. logBonus->warn("Warning: illegal alignment in limiter!");
  1388. return true;
  1389. }
  1390. }
  1391. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1392. :minRank(Min), maxRank(Max)
  1393. {
  1394. }
  1395. RankRangeLimiter::RankRangeLimiter()
  1396. {
  1397. minRank = maxRank = -1;
  1398. }
  1399. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1400. {
  1401. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1402. if(csi)
  1403. {
  1404. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1405. return true;
  1406. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1407. }
  1408. return true;
  1409. }
  1410. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1411. {
  1412. const CStack * s = retrieveStackBattle(&context.node);
  1413. if(s)
  1414. return s->owner != owner;
  1415. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1416. if(csi && csi->armyObj)
  1417. return csi->armyObj->tempOwner != owner;
  1418. return true;
  1419. }
  1420. StackOwnerLimiter::StackOwnerLimiter()
  1421. : owner(-1)
  1422. {
  1423. }
  1424. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1425. : owner(Owner)
  1426. {
  1427. }
  1428. int LimiterList::limit( const BonusLimitationContext &context ) const
  1429. {
  1430. bool wasntSure = false;
  1431. for(auto limiter : limiters)
  1432. {
  1433. auto result = limiter->limit(context);
  1434. if(result == ILimiter::DISCARD)
  1435. return result;
  1436. if(result == ILimiter::NOT_SURE)
  1437. wasntSure = true;
  1438. }
  1439. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1440. }
  1441. void LimiterList::add( TLimiterPtr limiter )
  1442. {
  1443. limiters.push_back(limiter);
  1444. }
  1445. // Updaters
  1446. std::shared_ptr<Bonus> Bonus::addUpdater(TUpdaterPtr Updater)
  1447. {
  1448. updater = Updater;
  1449. return this->shared_from_this();
  1450. }
  1451. IUpdater::~IUpdater()
  1452. {
  1453. }
  1454. const std::shared_ptr<Bonus> IUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1455. {
  1456. return b;
  1457. }
  1458. std::string IUpdater::toString() const
  1459. {
  1460. return typeid(*this).name();
  1461. }
  1462. JsonNode IUpdater::toJsonNode() const
  1463. {
  1464. return JsonNode(JsonNode::JsonType::DATA_NULL);
  1465. }
  1466. GrowsWithLevelUpdater::GrowsWithLevelUpdater() : valPer20(0), stepSize(1)
  1467. {
  1468. }
  1469. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  1470. {
  1471. }
  1472. const std::shared_ptr<Bonus> GrowsWithLevelUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1473. {
  1474. if(context.getNodeType() == CBonusSystemNode::HERO)
  1475. {
  1476. int level = static_cast<const CGHeroInstance &>(context).level;
  1477. int steps = stepSize ? level / stepSize : level;
  1478. //rounding follows format for HMM3 creature specialty bonus
  1479. int newVal = (valPer20 * steps + 19) / 20;
  1480. //return copy of bonus with updated val
  1481. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1482. newBonus->val = newVal;
  1483. return newBonus;
  1484. }
  1485. return b;
  1486. }
  1487. std::string GrowsWithLevelUpdater::toString() const
  1488. {
  1489. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  1490. }
  1491. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  1492. {
  1493. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1494. root["type"].String() = "GROWS_WITH_LEVEL";
  1495. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  1496. if(stepSize > 1)
  1497. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  1498. return root;
  1499. }
  1500. TimesHeroLevelUpdater::TimesHeroLevelUpdater()
  1501. {
  1502. }
  1503. const std::shared_ptr<Bonus> TimesHeroLevelUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1504. {
  1505. if(context.getNodeType() == CBonusSystemNode::HERO)
  1506. {
  1507. int level = static_cast<const CGHeroInstance &>(context).level;
  1508. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1509. newBonus->val *= level;
  1510. return newBonus;
  1511. }
  1512. return b;
  1513. }
  1514. std::string TimesHeroLevelUpdater::toString() const
  1515. {
  1516. return "TimesHeroLevelUpdater";
  1517. }
  1518. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  1519. {
  1520. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  1521. }
  1522. TimesStackLevelUpdater::TimesStackLevelUpdater()
  1523. {
  1524. }
  1525. const std::shared_ptr<Bonus> TimesStackLevelUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1526. {
  1527. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  1528. {
  1529. int level = static_cast<const CStackInstance &>(context).getLevel();
  1530. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1531. newBonus->val *= level;
  1532. return newBonus;
  1533. }
  1534. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  1535. {
  1536. const CStack & stack = static_cast<const CStack &>(context);
  1537. //only update if stack doesn't have an instance (summons, war machines)
  1538. //otherwise we'd end up multiplying twice
  1539. if(stack.base == nullptr)
  1540. {
  1541. int level = stack.type->level;
  1542. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1543. newBonus->val *= level;
  1544. return newBonus;
  1545. }
  1546. }
  1547. return b;
  1548. }
  1549. std::string TimesStackLevelUpdater::toString() const
  1550. {
  1551. return "TimesStackLevelUpdater";
  1552. }
  1553. JsonNode TimesStackLevelUpdater::toJsonNode() const
  1554. {
  1555. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  1556. }