HeroBonus.cpp 65 KB

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