HeroBonus.cpp 53 KB

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