HeroBonus.cpp 64 KB

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