HeroBonus.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575
  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. char cachingStr[20] = {};
  574. std::sprintf(cachingStr, "type_%ds_%d", (int)type, subtype);
  575. CSelector s = Selector::type()(type);
  576. if(subtype != -1)
  577. s = s.And(Selector::subtype()(subtype));
  578. return valOfBonuses(s, cachingStr);
  579. }
  580. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  581. {
  582. CSelector limit = nullptr;
  583. TConstBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  584. return hlp->totalValue();
  585. }
  586. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  587. {
  588. //TODO: We don't need to count all bonuses and could break on first matching
  589. return getBonuses(selector, cachingStr)->size() > 0;
  590. }
  591. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  592. {
  593. return getBonuses(selector, limit, cachingStr)->size() > 0;
  594. }
  595. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  596. {
  597. //This part is performance-ciritcal
  598. char cachingStr[20] = {};
  599. std::sprintf(cachingStr, "type_%ds_%d", (int)type, subtype);
  600. CSelector s = Selector::type()(type);
  601. if(subtype != -1)
  602. s = s.And(Selector::subtype()(subtype));
  603. return hasBonus(s, cachingStr);
  604. }
  605. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  606. {
  607. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  608. }
  609. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  610. {
  611. return getAllBonuses(selector, limit, nullptr, cachingStr);
  612. }
  613. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  614. {
  615. boost::format fmt("source_%did_%d");
  616. fmt % (int)source % sourceID;
  617. return hasBonus(Selector::source(source,sourceID), fmt.str());
  618. }
  619. int IBonusBearer::MoraleVal() const
  620. {
  621. if(anaffectedByMorale.getHasBonus())
  622. return 0;
  623. int ret = moraleValue.getValue();
  624. if(selfMorale.getHasBonus()) //eg. minotaur
  625. vstd::amax(ret, +1);
  626. return vstd::abetween(ret, -3, +3);
  627. }
  628. int IBonusBearer::LuckVal() const
  629. {
  630. if(hasBonusOfType(Bonus::NO_LUCK))
  631. return 0;
  632. int ret = luckValue.getValue();
  633. if(selfLuck.getHasBonus()) //eg. halfling
  634. vstd::amax(ret, +1);
  635. return vstd::abetween(ret, -3, +3);
  636. }
  637. int IBonusBearer::MoraleValAndBonusList(TConstBonusListPtr & bonusList) const
  638. {
  639. if(anaffectedByMorale.getHasBonus())
  640. {
  641. if(!bonusList->empty())
  642. bonusList = std::make_shared<const BonusList>();
  643. return 0;
  644. }
  645. int ret = moraleValue.getValueAndList(bonusList);
  646. if(selfMorale.getHasBonus()) //eg. minotaur
  647. vstd::amax(ret, +1);
  648. return vstd::abetween(ret, -3, +3);
  649. }
  650. int IBonusBearer::LuckValAndBonusList(TConstBonusListPtr & bonusList) const
  651. {
  652. if(hasBonusOfType(Bonus::NO_LUCK))
  653. {
  654. if(!bonusList->empty())
  655. bonusList = std::make_shared<const BonusList>();
  656. return 0;
  657. }
  658. int ret = luckValue.getValueAndList(bonusList);
  659. if(selfLuck.getHasBonus()) //eg. halfling
  660. vstd::amax(ret, +1);
  661. return vstd::abetween(ret, -3, +3);
  662. }
  663. ui32 IBonusBearer::MaxHealth() const
  664. {
  665. const std::string cachingStr = "type_STACK_HEALTH";
  666. static const auto selector = Selector::type()(Bonus::STACK_HEALTH);
  667. auto value = valOfBonuses(selector, cachingStr);
  668. return std::max(1, value); //never 0
  669. }
  670. int IBonusBearer::getAttack(bool ranged) const
  671. {
  672. const std::string cachingStr = "type_PRIMARY_SKILLs_ATTACK";
  673. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  674. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  675. }
  676. int IBonusBearer::getDefense(bool ranged) const
  677. {
  678. const std::string cachingStr = "type_PRIMARY_SKILLs_DEFENSE";
  679. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  680. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  681. }
  682. int IBonusBearer::getMinDamage(bool ranged) const
  683. {
  684. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_1";
  685. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1));
  686. return valOfBonuses(selector, cachingStr);
  687. }
  688. int IBonusBearer::getMaxDamage(bool ranged) const
  689. {
  690. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_2";
  691. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2));
  692. return valOfBonuses(selector, cachingStr);
  693. }
  694. si32 IBonusBearer::manaLimit() const
  695. {
  696. return si32(getPrimSkillLevel(PrimarySkill::KNOWLEDGE)
  697. * (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::INTELLIGENCE))
  698. / 10.0);
  699. }
  700. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  701. {
  702. static const CSelector selectorAllSkills = Selector::type()(Bonus::PRIMARY_SKILL);
  703. static const std::string keyAllSkills = "type_PRIMARY_SKILL";
  704. auto allSkills = getBonuses(selectorAllSkills, keyAllSkills);
  705. auto ret = allSkills->valOfBonuses(Selector::subtype()(id));
  706. auto minSkillValue = (id == PrimarySkill::SPELL_POWER || id == PrimarySkill::KNOWLEDGE) ? 1 : 0;
  707. vstd::amax(ret, minSkillValue); //otherwise, some artifacts may cause negative skill value effect
  708. return ret; //sp=0 works in old saves
  709. }
  710. si32 IBonusBearer::magicResistance() const
  711. {
  712. return valOfBonuses(Bonus::MAGIC_RESISTANCE);
  713. }
  714. ui32 IBonusBearer::Speed(int turn, bool useBind) const
  715. {
  716. //war machines cannot move
  717. if(hasBonus(Selector::type()(Bonus::SIEGE_WEAPON).And(Selector::turns(turn))))
  718. {
  719. return 0;
  720. }
  721. //bind effect check - doesn't influence stack initiative
  722. if(useBind && hasBonus(Selector::type()(Bonus::BIND_EFFECT).And(Selector::turns(turn))))
  723. {
  724. return 0;
  725. }
  726. return valOfBonuses(Selector::type()(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  727. }
  728. bool IBonusBearer::isLiving() const //TODO: theoreticaly there exists "LIVING" bonus in stack experience documentation
  729. {
  730. static const std::string cachingStr = "IBonusBearer::isLiving";
  731. static const CSelector selector = Selector::type()(Bonus::UNDEAD)
  732. .Or(Selector::type()(Bonus::NON_LIVING))
  733. .Or(Selector::type()(Bonus::GARGOYLE))
  734. .Or(Selector::type()(Bonus::SIEGE_WEAPON));
  735. return !hasBonus(selector, cachingStr);
  736. }
  737. std::shared_ptr<const Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  738. {
  739. auto bonuses = getAllBonuses(selector, Selector::all);
  740. return bonuses->getFirst(Selector::all);
  741. }
  742. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  743. {
  744. switch(node->getNodeType())
  745. {
  746. case CBonusSystemNode::STACK_BATTLE:
  747. return static_cast<const CStack*>(node);
  748. default:
  749. return nullptr;
  750. }
  751. }
  752. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  753. {
  754. switch(node->getNodeType())
  755. {
  756. case CBonusSystemNode::STACK_INSTANCE:
  757. return (static_cast<const CStackInstance *>(node));
  758. case CBonusSystemNode::STACK_BATTLE:
  759. return (static_cast<const CStack*>(node))->base;
  760. default:
  761. return nullptr;
  762. }
  763. }
  764. PlayerColor CBonusSystemNode::retrieveNodeOwner(const CBonusSystemNode * node)
  765. {
  766. return node ? node->getOwner() : PlayerColor::CANNOT_DETERMINE;
  767. }
  768. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector)
  769. {
  770. auto ret = bonuses.getFirst(selector);
  771. if(ret)
  772. return ret;
  773. FOREACH_PARENT(pname)
  774. {
  775. ret = pname->getBonusLocalFirst(selector);
  776. if (ret)
  777. return ret;
  778. }
  779. return nullptr;
  780. }
  781. std::shared_ptr<const Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector) const
  782. {
  783. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  784. }
  785. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  786. {
  787. for (auto & elem : parents)
  788. {
  789. const CBonusSystemNode *parent = elem;
  790. out.insert(parent);
  791. }
  792. }
  793. void CBonusSystemNode::getParents(TNodes &out)
  794. {
  795. for (auto & elem : parents)
  796. {
  797. const CBonusSystemNode *parent = elem;
  798. out.insert(const_cast<CBonusSystemNode*>(parent));
  799. }
  800. }
  801. void CBonusSystemNode::getAllParents(TCNodes & out) const //retrieves list of parent nodes (nodes to inherit bonuses from)
  802. {
  803. for(auto parent : parents)
  804. {
  805. out.insert(parent);
  806. parent->getAllParents(out);
  807. }
  808. }
  809. void CBonusSystemNode::getAllBonusesRec(BonusList &out) const
  810. {
  811. //out has been reserved sufficient capacity at getAllBonuses() call
  812. BonusList beforeUpdate;
  813. TCNodes lparents;
  814. getAllParents(lparents);
  815. if (lparents.size())
  816. {
  817. //estimate on how many bonuses are missing yet - must be positive
  818. beforeUpdate.reserve(std::max(out.capacity() - out.size(), bonuses.size()));
  819. }
  820. else
  821. {
  822. beforeUpdate.reserve(bonuses.size()); //at most all local bonuses
  823. }
  824. for (auto parent : lparents)
  825. {
  826. parent->getAllBonusesRec(beforeUpdate);
  827. }
  828. bonuses.getAllBonuses(beforeUpdate);
  829. for(const auto & b : beforeUpdate)
  830. {
  831. auto updated = b->updater
  832. ? getUpdatedBonus(b, b->updater)
  833. : b;
  834. //do not add bonus with same pointer
  835. if(!vstd::contains(out, updated))
  836. out.push_back(updated);
  837. }
  838. }
  839. TConstBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  840. {
  841. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  842. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  843. {
  844. // Exclusive access for one thread
  845. boost::lock_guard<boost::mutex> lock(sync);
  846. // If the bonus system tree changes(state of a single node or the relations to each other) then
  847. // cache all bonus objects. Selector objects doesn't matter.
  848. if (cachedLast != treeChanged)
  849. {
  850. BonusList allBonuses;
  851. allBonuses.reserve(cachedBonuses.capacity()); //we assume we'll get about the same number of bonuses
  852. cachedBonuses.clear();
  853. cachedRequests.clear();
  854. getAllBonusesRec(allBonuses);
  855. limitBonuses(allBonuses, cachedBonuses);
  856. cachedBonuses.stackBonuses();
  857. cachedLast = treeChanged;
  858. }
  859. // If a bonus system request comes with a caching string then look up in the map if there are any
  860. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  861. if(!cachingStr.empty())
  862. {
  863. auto it = cachedRequests.find(cachingStr);
  864. if(it != cachedRequests.end())
  865. {
  866. //Cached list contains bonuses for our query with applied limiters
  867. return it->second;
  868. }
  869. }
  870. //We still don't have the bonuses (didn't returned them from cache)
  871. //Perform bonus selection
  872. auto ret = std::make_shared<BonusList>();
  873. cachedBonuses.getBonuses(*ret, selector, limit);
  874. // Save the results in the cache
  875. if(!cachingStr.empty())
  876. cachedRequests[cachingStr] = ret;
  877. return ret;
  878. }
  879. else
  880. {
  881. return getAllBonusesWithoutCaching(selector, limit, root);
  882. }
  883. }
  884. TConstBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  885. {
  886. auto ret = std::make_shared<BonusList>();
  887. // Get bonus results without caching enabled.
  888. BonusList beforeLimiting, afterLimiting;
  889. getAllBonusesRec(beforeLimiting);
  890. if(!root || root == this)
  891. {
  892. limitBonuses(beforeLimiting, afterLimiting);
  893. }
  894. else if(root)
  895. {
  896. //We want to limit our query against an external node. We get all its bonuses,
  897. // add the ones we're considering and see if they're cut out by limiters
  898. BonusList rootBonuses, limitedRootBonuses;
  899. getAllBonusesRec(rootBonuses);
  900. for(auto b : beforeLimiting)
  901. rootBonuses.push_back(b);
  902. root->limitBonuses(rootBonuses, limitedRootBonuses);
  903. for(auto b : beforeLimiting)
  904. if(vstd::contains(limitedRootBonuses, b))
  905. afterLimiting.push_back(b);
  906. }
  907. afterLimiting.getBonuses(*ret, selector, limit);
  908. ret->stackBonuses();
  909. return ret;
  910. }
  911. std::shared_ptr<Bonus> CBonusSystemNode::getUpdatedBonus(const std::shared_ptr<Bonus> & b, const TUpdaterPtr updater) const
  912. {
  913. assert(updater);
  914. return updater->createUpdatedBonus(b, * this);
  915. }
  916. CBonusSystemNode::CBonusSystemNode()
  917. :CBonusSystemNode(false)
  918. {
  919. }
  920. CBonusSystemNode::CBonusSystemNode(bool isHypotetic)
  921. : bonuses(true),
  922. exportedBonuses(true),
  923. nodeType(UNKNOWN),
  924. cachedLast(0),
  925. sync(),
  926. isHypotheticNode(isHypotetic)
  927. {
  928. }
  929. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType)
  930. : bonuses(true),
  931. exportedBonuses(true),
  932. nodeType(NodeType),
  933. cachedLast(0),
  934. sync(),
  935. isHypotheticNode(false)
  936. {
  937. }
  938. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other):
  939. bonuses(std::move(other.bonuses)),
  940. exportedBonuses(std::move(other.exportedBonuses)),
  941. nodeType(other.nodeType),
  942. description(other.description),
  943. cachedLast(0),
  944. sync(),
  945. isHypotheticNode(other.isHypotheticNode)
  946. {
  947. std::swap(parents, other.parents);
  948. std::swap(children, other.children);
  949. //fixing bonus tree without recalculation
  950. if(!isHypothetic())
  951. {
  952. for(CBonusSystemNode * n : parents)
  953. {
  954. n->children -= &other;
  955. n->children.push_back(this);
  956. }
  957. }
  958. for(CBonusSystemNode * n : children)
  959. {
  960. n->parents -= &other;
  961. n->parents.push_back(this);
  962. }
  963. //cache ignored
  964. //cachedBonuses
  965. //cachedRequests
  966. }
  967. CBonusSystemNode::~CBonusSystemNode()
  968. {
  969. detachFromAll();
  970. if(children.size())
  971. {
  972. while(children.size())
  973. children.front()->detachFrom(*this);
  974. }
  975. }
  976. void CBonusSystemNode::attachTo(CBonusSystemNode & parent)
  977. {
  978. assert(!vstd::contains(parents, &parent));
  979. parents.push_back(&parent);
  980. if(!isHypothetic())
  981. {
  982. if(parent.actsAsBonusSourceOnly())
  983. parent.newRedDescendant(*this);
  984. else
  985. newRedDescendant(parent);
  986. parent.newChildAttached(*this);
  987. }
  988. CBonusSystemNode::treeHasChanged();
  989. }
  990. void CBonusSystemNode::detachFrom(CBonusSystemNode & parent)
  991. {
  992. assert(vstd::contains(parents, &parent));
  993. if(!isHypothetic())
  994. {
  995. if(parent.actsAsBonusSourceOnly())
  996. parent.removedRedDescendant(*this);
  997. else
  998. removedRedDescendant(parent);
  999. }
  1000. if (vstd::contains(parents, &parent))
  1001. {
  1002. parents -= &parent;
  1003. }
  1004. else
  1005. {
  1006. logBonus->error("Error on Detach. Node %s (nodeType=%d) has not parent %s (nodeType=%d)"
  1007. , nodeShortInfo(), nodeType, parent.nodeShortInfo(), parent.nodeType);
  1008. }
  1009. if(!isHypothetic())
  1010. {
  1011. parent.childDetached(*this);
  1012. }
  1013. CBonusSystemNode::treeHasChanged();
  1014. }
  1015. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  1016. {
  1017. removeBonuses(s);
  1018. for(CBonusSystemNode * child : children)
  1019. child->removeBonusesRecursive(s);
  1020. }
  1021. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  1022. {
  1023. BonusList bl;
  1024. exportedBonuses.getBonuses(bl, s, Selector::all);
  1025. for(auto b : bl)
  1026. {
  1027. b->turnsRemain--;
  1028. if(b->turnsRemain <= 0)
  1029. removeBonus(b);
  1030. }
  1031. for(CBonusSystemNode *child : children)
  1032. child->reduceBonusDurations(s);
  1033. }
  1034. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  1035. {
  1036. //turnsRemain shouldn't be zero for following durations
  1037. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  1038. {
  1039. assert(b->turnsRemain);
  1040. }
  1041. assert(!vstd::contains(exportedBonuses, b));
  1042. exportedBonuses.push_back(b);
  1043. exportBonus(b);
  1044. CBonusSystemNode::treeHasChanged();
  1045. }
  1046. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  1047. {
  1048. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  1049. if(bonus)
  1050. bonus->val += b->val;
  1051. else
  1052. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  1053. }
  1054. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  1055. {
  1056. exportedBonuses -= b;
  1057. if(b->propagator)
  1058. unpropagateBonus(b);
  1059. else
  1060. bonuses -= b;
  1061. CBonusSystemNode::treeHasChanged();
  1062. }
  1063. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  1064. {
  1065. BonusList toRemove;
  1066. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  1067. for(auto bonus : toRemove)
  1068. removeBonus(bonus);
  1069. }
  1070. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  1071. {
  1072. switch(nodeType)
  1073. {
  1074. case CREATURE:
  1075. case ARTIFACT:
  1076. case ARTIFACT_INSTANCE:
  1077. return true;
  1078. default:
  1079. return false;
  1080. }
  1081. }
  1082. void CBonusSystemNode::propagateBonus(std::shared_ptr<Bonus> b, const CBonusSystemNode & source)
  1083. {
  1084. if(b->propagator->shouldBeAttached(this))
  1085. {
  1086. auto propagated = b->propagationUpdater
  1087. ? source.getUpdatedBonus(b, b->propagationUpdater)
  1088. : b;
  1089. bonuses.push_back(propagated);
  1090. logBonus->trace("#$# %s #propagated to# %s", propagated->Description(), nodeName());
  1091. }
  1092. FOREACH_RED_CHILD(child)
  1093. child->propagateBonus(b, source);
  1094. }
  1095. void CBonusSystemNode::unpropagateBonus(std::shared_ptr<Bonus> b)
  1096. {
  1097. if(b->propagator->shouldBeAttached(this))
  1098. {
  1099. bonuses -= b;
  1100. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  1101. }
  1102. FOREACH_RED_CHILD(child)
  1103. child->unpropagateBonus(b);
  1104. }
  1105. void CBonusSystemNode::newChildAttached(CBonusSystemNode & child)
  1106. {
  1107. assert(!vstd::contains(children, &child));
  1108. children.push_back(&child);
  1109. }
  1110. void CBonusSystemNode::childDetached(CBonusSystemNode & child)
  1111. {
  1112. if(vstd::contains(children, &child))
  1113. children -= &child;
  1114. else
  1115. {
  1116. logBonus->error("Error on Detach. Node %s (nodeType=%d) is not a child of %s (nodeType=%d)"
  1117. , child.nodeShortInfo(), child.nodeType, nodeShortInfo(), nodeType);
  1118. }
  1119. }
  1120. void CBonusSystemNode::detachFromAll()
  1121. {
  1122. while(parents.size())
  1123. detachFrom(*parents.front());
  1124. }
  1125. bool CBonusSystemNode::isIndependentNode() const
  1126. {
  1127. return parents.empty() && children.empty();
  1128. }
  1129. std::string CBonusSystemNode::nodeName() const
  1130. {
  1131. return description.size()
  1132. ? description
  1133. : std::string("Bonus system node of type ") + typeid(*this).name();
  1134. }
  1135. std::string CBonusSystemNode::nodeShortInfo() const
  1136. {
  1137. std::ostringstream str;
  1138. str << "'" << typeid(* this).name() << "'";
  1139. description.length() > 0
  1140. ? str << " (" << description << ")"
  1141. : str << " (no description)";
  1142. return str.str();
  1143. }
  1144. void CBonusSystemNode::deserializationFix()
  1145. {
  1146. exportBonuses();
  1147. }
  1148. void CBonusSystemNode::getRedParents(TNodes & out)
  1149. {
  1150. FOREACH_PARENT(pname)
  1151. {
  1152. if(pname->actsAsBonusSourceOnly())
  1153. {
  1154. out.insert(pname);
  1155. }
  1156. }
  1157. if(!actsAsBonusSourceOnly())
  1158. {
  1159. for(CBonusSystemNode *child : children)
  1160. {
  1161. out.insert(child);
  1162. }
  1163. }
  1164. }
  1165. void CBonusSystemNode::getRedChildren(TNodes &out)
  1166. {
  1167. FOREACH_PARENT(pname)
  1168. {
  1169. if(!pname->actsAsBonusSourceOnly())
  1170. {
  1171. out.insert(pname);
  1172. }
  1173. }
  1174. if(actsAsBonusSourceOnly())
  1175. {
  1176. for(CBonusSystemNode *child : children)
  1177. {
  1178. out.insert(child);
  1179. }
  1180. }
  1181. }
  1182. void CBonusSystemNode::newRedDescendant(CBonusSystemNode & descendant)
  1183. {
  1184. for(auto b : exportedBonuses)
  1185. {
  1186. if(b->propagator)
  1187. descendant.propagateBonus(b, *this);
  1188. }
  1189. TNodes redParents;
  1190. getRedAncestors(redParents); //get all red parents recursively
  1191. for(auto parent : redParents)
  1192. {
  1193. for(auto b : parent->exportedBonuses)
  1194. {
  1195. if(b->propagator)
  1196. descendant.propagateBonus(b, *this);
  1197. }
  1198. }
  1199. }
  1200. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode & descendant)
  1201. {
  1202. for(auto b : exportedBonuses)
  1203. if(b->propagator)
  1204. descendant.unpropagateBonus(b);
  1205. TNodes redParents;
  1206. getRedAncestors(redParents); //get all red parents recursively
  1207. for(auto parent : redParents)
  1208. {
  1209. for(auto b : parent->exportedBonuses)
  1210. if(b->propagator)
  1211. descendant.unpropagateBonus(b);
  1212. }
  1213. }
  1214. void CBonusSystemNode::getRedAncestors(TNodes &out)
  1215. {
  1216. getRedParents(out);
  1217. TNodes redParents;
  1218. getRedParents(redParents);
  1219. for(CBonusSystemNode * parent : redParents)
  1220. parent->getRedAncestors(out);
  1221. }
  1222. void CBonusSystemNode::getRedDescendants(TNodes &out)
  1223. {
  1224. getRedChildren(out);
  1225. FOREACH_RED_CHILD(c)
  1226. c->getRedChildren(out);
  1227. }
  1228. void CBonusSystemNode::exportBonus(std::shared_ptr<Bonus> b)
  1229. {
  1230. if(b->propagator)
  1231. propagateBonus(b, *this);
  1232. else
  1233. bonuses.push_back(b);
  1234. CBonusSystemNode::treeHasChanged();
  1235. }
  1236. void CBonusSystemNode::exportBonuses()
  1237. {
  1238. for(auto b : exportedBonuses)
  1239. exportBonus(b);
  1240. }
  1241. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  1242. {
  1243. return nodeType;
  1244. }
  1245. const BonusList& CBonusSystemNode::getBonusList() const
  1246. {
  1247. return bonuses;
  1248. }
  1249. const TNodesVector& CBonusSystemNode::getParentNodes() const
  1250. {
  1251. return parents;
  1252. }
  1253. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  1254. {
  1255. return children;
  1256. }
  1257. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  1258. {
  1259. nodeType = type;
  1260. }
  1261. BonusList & CBonusSystemNode::getExportedBonusList()
  1262. {
  1263. return exportedBonuses;
  1264. }
  1265. const BonusList & CBonusSystemNode::getExportedBonusList() const
  1266. {
  1267. return exportedBonuses;
  1268. }
  1269. const std::string& CBonusSystemNode::getDescription() const
  1270. {
  1271. return description;
  1272. }
  1273. void CBonusSystemNode::setDescription(const std::string &description)
  1274. {
  1275. this->description = description;
  1276. }
  1277. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  1278. {
  1279. assert(&allBonuses != &out); //todo should it work in-place?
  1280. BonusList undecided = allBonuses,
  1281. &accepted = out;
  1282. while(true)
  1283. {
  1284. int undecidedCount = static_cast<int>(undecided.size());
  1285. for(int i = 0; i < undecided.size(); i++)
  1286. {
  1287. auto b = undecided[i];
  1288. BonusLimitationContext context = {b, *this, out, undecided};
  1289. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  1290. if(decision == ILimiter::DISCARD)
  1291. {
  1292. undecided.erase(i);
  1293. i--; continue;
  1294. }
  1295. else if(decision == ILimiter::ACCEPT)
  1296. {
  1297. accepted.push_back(b);
  1298. undecided.erase(i);
  1299. i--; continue;
  1300. }
  1301. else
  1302. assert(decision == ILimiter::NOT_SURE);
  1303. }
  1304. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  1305. return;
  1306. }
  1307. }
  1308. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  1309. {
  1310. auto ret = std::make_shared<BonusList>();
  1311. limitBonuses(allBonuses, *ret);
  1312. return ret;
  1313. }
  1314. void CBonusSystemNode::treeHasChanged()
  1315. {
  1316. treeChanged++;
  1317. }
  1318. int64_t CBonusSystemNode::getTreeVersion() const
  1319. {
  1320. int64_t ret = treeChanged;
  1321. return ret << 32;
  1322. }
  1323. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1324. {
  1325. if(obj)
  1326. return obj->valOfBonuses(type, subtype);
  1327. return 0;
  1328. }
  1329. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1330. {
  1331. if(obj)
  1332. return obj->hasBonusOfType(type, subtype);
  1333. return false;
  1334. }
  1335. std::string Bonus::Description() const
  1336. {
  1337. std::ostringstream str;
  1338. if(description.empty())
  1339. {
  1340. if(stacking.empty() || stacking == "ALWAYS")
  1341. {
  1342. switch(source)
  1343. {
  1344. case ARTIFACT:
  1345. str << ArtifactID(sid).toArtifact(VLC->artifacts())->getName();
  1346. break;
  1347. case SPELL_EFFECT:
  1348. str << SpellID(sid).toSpell(VLC->spells())->getName();
  1349. break;
  1350. case CREATURE_ABILITY:
  1351. str << VLC->creh->objects[sid]->namePl;
  1352. break;
  1353. case SECONDARY_SKILL:
  1354. str << VLC->skillh->skillName(sid);
  1355. break;
  1356. case HERO_SPECIAL:
  1357. str << VLC->heroh->objects[sid]->name;
  1358. break;
  1359. default:
  1360. //todo: handle all possible sources
  1361. str << "Unknown";
  1362. break;
  1363. }
  1364. }
  1365. else
  1366. str << stacking;
  1367. }
  1368. else
  1369. {
  1370. str << description;
  1371. }
  1372. if(val != 0)
  1373. str << " " << std::showpos << val;
  1374. return str.str();
  1375. }
  1376. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  1377. {
  1378. switch(type)
  1379. {
  1380. case Bonus::PRIMARY_SKILL:
  1381. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  1382. case Bonus::SECONDARY_SKILL_PREMY:
  1383. return JsonUtils::stringNode(CSkillHandler::encodeSkillWithType(subtype));
  1384. case Bonus::SPECIAL_SPELL_LEV:
  1385. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1386. case Bonus::SPECIAL_BLESS_DAMAGE:
  1387. case Bonus::MAXED_SPELL:
  1388. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1389. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1390. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1391. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "spell", SpellID::encode(subtype)));
  1392. case Bonus::IMPROVED_NECROMANCY:
  1393. case Bonus::SPECIAL_UPGRADE:
  1394. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(subtype)));
  1395. case Bonus::GENERATE_RESOURCE:
  1396. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1397. default:
  1398. return JsonUtils::intNode(subtype);
  1399. }
  1400. }
  1401. JsonNode additionalInfoToJson(Bonus::BonusType type, CAddInfo addInfo)
  1402. {
  1403. switch(type)
  1404. {
  1405. case Bonus::SPECIAL_UPGRADE:
  1406. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(addInfo[0])));
  1407. default:
  1408. return addInfo.toJsonNode();
  1409. }
  1410. }
  1411. JsonNode durationToJson(ui16 duration)
  1412. {
  1413. std::vector<std::string> durationNames;
  1414. for(ui16 durBit = 1; durBit; durBit = durBit << 1)
  1415. {
  1416. if(duration & durBit)
  1417. durationNames.push_back(vstd::findKey(bonusDurationMap, durBit));
  1418. }
  1419. if(durationNames.size() == 1)
  1420. {
  1421. return JsonUtils::stringNode(durationNames[0]);
  1422. }
  1423. else
  1424. {
  1425. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  1426. for(std::string dur : durationNames)
  1427. node.Vector().push_back(JsonUtils::stringNode(dur));
  1428. return node;
  1429. }
  1430. }
  1431. JsonNode Bonus::toJsonNode() const
  1432. {
  1433. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1434. // only add values that might reasonably be found in config files
  1435. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1436. if(subtype != -1)
  1437. root["subtype"] = subtypeToJson(type, subtype);
  1438. if(additionalInfo != CAddInfo::NONE)
  1439. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1440. if(duration != 0)
  1441. {
  1442. JsonNode durationVec(JsonNode::JsonType::DATA_VECTOR);
  1443. for(auto & kv : bonusDurationMap)
  1444. {
  1445. if(duration & kv.second)
  1446. durationVec.Vector().push_back(JsonUtils::stringNode(kv.first));
  1447. }
  1448. root["duration"] = durationVec;
  1449. }
  1450. if(turnsRemain != 0)
  1451. root["turns"].Integer() = turnsRemain;
  1452. if(source != OTHER)
  1453. root["source"].String() = vstd::findKey(bonusSourceMap, source);
  1454. if(sid != 0)
  1455. root["sourceID"].Integer() = sid;
  1456. if(val != 0)
  1457. root["val"].Integer() = val;
  1458. if(valType != ADDITIVE_VALUE)
  1459. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1460. if(!stacking.empty())
  1461. root["stacking"].String() = stacking;
  1462. if(!description.empty())
  1463. root["description"].String() = description;
  1464. if(effectRange != NO_LIMIT)
  1465. root["effectRange"].String() = vstd::findKey(bonusLimitEffect, effectRange);
  1466. if(duration != PERMANENT)
  1467. root["duration"] = durationToJson(duration);
  1468. if(turnsRemain)
  1469. root["turns"].Integer() = turnsRemain;
  1470. if(limiter)
  1471. root["limiters"] = limiter->toJsonNode();
  1472. if(updater)
  1473. root["updater"] = updater->toJsonNode();
  1474. if(propagator)
  1475. root["propagator"].String() = vstd::findKey(bonusPropagatorMap, propagator);
  1476. return root;
  1477. }
  1478. std::string Bonus::nameForBonus() const
  1479. {
  1480. switch(type)
  1481. {
  1482. case Bonus::PRIMARY_SKILL:
  1483. return PrimarySkill::names[subtype];
  1484. case Bonus::SECONDARY_SKILL_PREMY:
  1485. return CSkillHandler::encodeSkill(subtype);
  1486. case Bonus::SPECIAL_SPELL_LEV:
  1487. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1488. case Bonus::SPECIAL_BLESS_DAMAGE:
  1489. case Bonus::MAXED_SPELL:
  1490. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1491. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1492. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1493. return (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier;
  1494. case Bonus::SPECIAL_UPGRADE:
  1495. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo[0]);
  1496. case Bonus::GENERATE_RESOURCE:
  1497. return GameConstants::RESOURCE_NAMES[subtype];
  1498. case Bonus::STACKS_SPEED:
  1499. return "speed";
  1500. default:
  1501. return vstd::findKey(bonusNameMap, type);
  1502. }
  1503. }
  1504. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype)
  1505. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  1506. {
  1507. turnsRemain = 0;
  1508. valType = ADDITIVE_VALUE;
  1509. effectRange = NO_LIMIT;
  1510. boost::algorithm::trim(description);
  1511. }
  1512. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType)
  1513. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  1514. {
  1515. turnsRemain = 0;
  1516. effectRange = NO_LIMIT;
  1517. }
  1518. Bonus::Bonus()
  1519. {
  1520. duration = PERMANENT;
  1521. turnsRemain = 0;
  1522. type = NONE;
  1523. subtype = -1;
  1524. valType = ADDITIVE_VALUE;
  1525. effectRange = NO_LIMIT;
  1526. val = 0;
  1527. source = OTHER;
  1528. sid = 0;
  1529. }
  1530. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  1531. {
  1532. propagator = Propagator;
  1533. return this->shared_from_this();
  1534. }
  1535. namespace Selector
  1536. {
  1537. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type()
  1538. {
  1539. static CSelectFieldEqual<Bonus::BonusType> stype(&Bonus::type);
  1540. return stype;
  1541. }
  1542. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype()
  1543. {
  1544. static CSelectFieldEqual<TBonusSubtype> ssubtype(&Bonus::subtype);
  1545. return ssubtype;
  1546. }
  1547. DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info()
  1548. {
  1549. static CSelectFieldEqual<CAddInfo> sinfo(&Bonus::additionalInfo);
  1550. return sinfo;
  1551. }
  1552. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType()
  1553. {
  1554. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::source);
  1555. return ssourceType;
  1556. }
  1557. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange()
  1558. {
  1559. static CSelectFieldEqual<Bonus::LimitEffect> seffectRange(&Bonus::effectRange);
  1560. return seffectRange;
  1561. }
  1562. DLL_LINKAGE CWillLastTurns turns;
  1563. DLL_LINKAGE CWillLastDays days;
  1564. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1565. {
  1566. return type()(Type).And(subtype()(Subtype));
  1567. }
  1568. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, CAddInfo info)
  1569. {
  1570. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1571. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1572. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1573. }
  1574. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1575. {
  1576. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1577. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1578. }
  1579. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1580. {
  1581. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1582. }
  1583. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1584. {
  1585. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1586. }
  1587. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1588. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1589. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1590. {
  1591. Bonus dummy;
  1592. dummy.type = type;
  1593. return sel(&dummy);
  1594. }
  1595. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1596. {
  1597. Bonus dummy;
  1598. dummy.type = type;
  1599. dummy.subtype = subtype;
  1600. return sel(&dummy);
  1601. }
  1602. }
  1603. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1604. {
  1605. switch(node->getNodeType())
  1606. {
  1607. case CBonusSystemNode::CREATURE:
  1608. return (static_cast<const CCreature *>(node));
  1609. case CBonusSystemNode::STACK_BATTLE:
  1610. return (static_cast<const CStack*>(node))->type;
  1611. default:
  1612. const CStackInstance * csi = retrieveStackInstance(node);
  1613. if(csi)
  1614. return csi->type;
  1615. return nullptr;
  1616. }
  1617. }
  1618. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1619. {
  1620. for (ui32 i = 0; i < bonusList.size(); i++)
  1621. {
  1622. auto b = bonusList[i];
  1623. out << "Bonus " << i << "\n" << *b << std::endl;
  1624. }
  1625. return out;
  1626. }
  1627. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1628. {
  1629. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1630. if(i->second == bonus.type)
  1631. out << "\tType: " << i->first << " \t";
  1632. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1633. printField(val);
  1634. printField(subtype);
  1635. printField(duration);
  1636. printField(source);
  1637. printField(sid);
  1638. if(bonus.additionalInfo != CAddInfo::NONE)
  1639. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1640. printField(turnsRemain);
  1641. printField(valType);
  1642. if(!bonus.stacking.empty())
  1643. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1644. printField(effectRange);
  1645. #undef printField
  1646. if(bonus.limiter)
  1647. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1648. if(bonus.updater)
  1649. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1650. return out;
  1651. }
  1652. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1653. {
  1654. if (limiter)
  1655. {
  1656. //If we already have limiter list, retrieve it
  1657. auto limiterList = std::dynamic_pointer_cast<AllOfLimiter>(limiter);
  1658. if(!limiterList)
  1659. {
  1660. //Create a new limiter list with old limiter and the new one will be pushed later
  1661. limiterList = std::make_shared<AllOfLimiter>();
  1662. limiterList->add(limiter);
  1663. limiter = limiterList;
  1664. }
  1665. limiterList->add(Limiter);
  1666. }
  1667. else
  1668. {
  1669. limiter = Limiter;
  1670. }
  1671. return this->shared_from_this();
  1672. }
  1673. ILimiter::~ILimiter()
  1674. {
  1675. }
  1676. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1677. {
  1678. return false;
  1679. }
  1680. std::string ILimiter::toString() const
  1681. {
  1682. return typeid(*this).name();
  1683. }
  1684. JsonNode ILimiter::toJsonNode() const
  1685. {
  1686. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1687. root["type"].String() = toString();
  1688. return root;
  1689. }
  1690. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1691. {
  1692. const CCreature *c = retrieveCreature(&context.node);
  1693. if(!c)
  1694. return true;
  1695. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1696. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1697. }
  1698. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature & creature_, bool IncludeUpgrades)
  1699. : creature(&creature_), includeUpgrades(IncludeUpgrades)
  1700. {
  1701. }
  1702. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1703. {
  1704. creature = nullptr;
  1705. includeUpgrades = false;
  1706. }
  1707. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1708. {
  1709. creature = VLC->creh->objects[id];
  1710. }
  1711. std::string CCreatureTypeLimiter::toString() const
  1712. {
  1713. boost::format fmt("CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)");
  1714. fmt % creature->identifier % (includeUpgrades ? "true" : "false");
  1715. return fmt.str();
  1716. }
  1717. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1718. {
  1719. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1720. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1721. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->identifier));
  1722. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1723. return root;
  1724. }
  1725. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1726. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1727. {
  1728. }
  1729. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1730. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1731. {
  1732. }
  1733. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1734. {
  1735. CSelector mySelector = isSubtypeRelevant
  1736. ? Selector::typeSubtype(type, subtype)
  1737. : Selector::type()(type);
  1738. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1739. if(context.alreadyAccepted.getFirst(mySelector))
  1740. return ACCEPT;
  1741. //if there are no matching bonuses pending, we can (and must) reject right away
  1742. if(!context.stillUndecided.getFirst(mySelector))
  1743. return DISCARD;
  1744. //do not accept for now but it may change if more bonuses gets included
  1745. return NOT_SURE;
  1746. }
  1747. std::string HasAnotherBonusLimiter::toString() const
  1748. {
  1749. std::string typeName = vstd::findKey(bonusNameMap, type);
  1750. if(isSubtypeRelevant)
  1751. {
  1752. boost::format fmt("HasAnotherBonusLimiter(type=%s, subtype=%d)");
  1753. fmt % typeName % subtype;
  1754. return fmt.str();
  1755. }
  1756. else
  1757. {
  1758. boost::format fmt("HasAnotherBonusLimiter(type=%s)");
  1759. fmt % typeName;
  1760. return fmt.str();
  1761. }
  1762. }
  1763. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  1764. {
  1765. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1766. std::string typeName = vstd::findKey(bonusNameMap, type);
  1767. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  1768. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  1769. if(isSubtypeRelevant)
  1770. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  1771. return root;
  1772. }
  1773. IPropagator::~IPropagator()
  1774. {
  1775. }
  1776. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1777. {
  1778. return false;
  1779. }
  1780. CBonusSystemNode::ENodeTypes IPropagator::getPropagatorType() const
  1781. {
  1782. return CBonusSystemNode::ENodeTypes::NONE;
  1783. }
  1784. CPropagatorNodeType::CPropagatorNodeType()
  1785. :nodeType(CBonusSystemNode::ENodeTypes::UNKNOWN)
  1786. {
  1787. }
  1788. CPropagatorNodeType::CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType)
  1789. : nodeType(NodeType)
  1790. {
  1791. }
  1792. CBonusSystemNode::ENodeTypes CPropagatorNodeType::getPropagatorType() const
  1793. {
  1794. return nodeType;
  1795. }
  1796. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1797. {
  1798. return nodeType == dest->getNodeType();
  1799. }
  1800. CreatureTerrainLimiter::CreatureTerrainLimiter()
  1801. : terrainType(Terrain::NATIVE_TERRAIN)
  1802. {
  1803. }
  1804. CreatureTerrainLimiter::CreatureTerrainLimiter(TerrainId terrain):
  1805. terrainType(terrain)
  1806. {
  1807. }
  1808. int CreatureTerrainLimiter::limit(const BonusLimitationContext &context) const
  1809. {
  1810. const CStack *stack = retrieveStackBattle(&context.node);
  1811. if(stack)
  1812. {
  1813. if (terrainType == Terrain::NATIVE_TERRAIN)//terrainType not specified = native
  1814. {
  1815. return !stack->isOnNativeTerrain();
  1816. }
  1817. else
  1818. {
  1819. return !stack->isOnTerrain(terrainType);
  1820. }
  1821. }
  1822. return true;
  1823. //TODO neutral creatues
  1824. }
  1825. std::string CreatureTerrainLimiter::toString() const
  1826. {
  1827. boost::format fmt("CreatureTerrainLimiter(terrainType=%s)");
  1828. auto terrainName = VLC->terrainTypeHandler->terrains()[terrainType].name;
  1829. fmt % (terrainType == Terrain::NATIVE_TERRAIN ? "native" : terrainName);
  1830. return fmt.str();
  1831. }
  1832. JsonNode CreatureTerrainLimiter::toJsonNode() const
  1833. {
  1834. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1835. root["type"].String() = "CREATURE_TERRAIN_LIMITER";
  1836. auto terrainName = VLC->terrainTypeHandler->terrains()[terrainType].name;
  1837. root["parameters"].Vector().push_back(JsonUtils::stringNode(terrainName));
  1838. return root;
  1839. }
  1840. CreatureFactionLimiter::CreatureFactionLimiter(TFaction creatureFaction)
  1841. : faction(creatureFaction)
  1842. {
  1843. }
  1844. CreatureFactionLimiter::CreatureFactionLimiter()
  1845. : faction((TFaction)-1)
  1846. {
  1847. }
  1848. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1849. {
  1850. const CCreature *c = retrieveCreature(&context.node);
  1851. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1852. }
  1853. std::string CreatureFactionLimiter::toString() const
  1854. {
  1855. boost::format fmt("CreatureFactionLimiter(faction=%s)");
  1856. fmt % VLC->factions()->getByIndex(faction)->getJsonKey();
  1857. return fmt.str();
  1858. }
  1859. JsonNode CreatureFactionLimiter::toJsonNode() const
  1860. {
  1861. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1862. root["type"].String() = "CREATURE_FACTION_LIMITER";
  1863. root["parameters"].Vector().push_back(JsonUtils::stringNode(VLC->factions()->getByIndex(faction)->getJsonKey()));
  1864. return root;
  1865. }
  1866. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1867. : alignment(-1)
  1868. {
  1869. }
  1870. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1871. : alignment(Alignment)
  1872. {
  1873. }
  1874. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1875. {
  1876. const CCreature *c = retrieveCreature(&context.node);
  1877. if(!c)
  1878. return true;
  1879. switch(alignment)
  1880. {
  1881. case EAlignment::GOOD:
  1882. return !c->isGood(); //if not good -> return true (drop bonus)
  1883. case EAlignment::NEUTRAL:
  1884. return c->isEvil() || c->isGood();
  1885. case EAlignment::EVIL:
  1886. return !c->isEvil();
  1887. default:
  1888. logBonus->warn("Warning: illegal alignment in limiter!");
  1889. return true;
  1890. }
  1891. }
  1892. std::string CreatureAlignmentLimiter::toString() const
  1893. {
  1894. boost::format fmt("CreatureAlignmentLimiter(alignment=%s)");
  1895. fmt % EAlignment::names[alignment];
  1896. return fmt.str();
  1897. }
  1898. JsonNode CreatureAlignmentLimiter::toJsonNode() const
  1899. {
  1900. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1901. root["type"].String() = "CREATURE_ALIGNMENT_LIMITER";
  1902. root["parameters"].Vector().push_back(JsonUtils::stringNode(EAlignment::names[alignment]));
  1903. return root;
  1904. }
  1905. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1906. :minRank(Min), maxRank(Max)
  1907. {
  1908. }
  1909. RankRangeLimiter::RankRangeLimiter()
  1910. {
  1911. minRank = maxRank = -1;
  1912. }
  1913. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1914. {
  1915. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1916. if(csi)
  1917. {
  1918. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1919. return true;
  1920. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1921. }
  1922. return true;
  1923. }
  1924. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1925. {
  1926. const CStack * s = retrieveStackBattle(&context.node);
  1927. if(s)
  1928. return s->owner != owner;
  1929. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1930. if(csi && csi->armyObj)
  1931. return csi->armyObj->tempOwner != owner;
  1932. return true;
  1933. }
  1934. StackOwnerLimiter::StackOwnerLimiter()
  1935. : owner(-1)
  1936. {
  1937. }
  1938. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1939. : owner(Owner)
  1940. {
  1941. }
  1942. OppositeSideLimiter::OppositeSideLimiter()
  1943. : owner(PlayerColor::CANNOT_DETERMINE)
  1944. {
  1945. }
  1946. OppositeSideLimiter::OppositeSideLimiter(PlayerColor Owner)
  1947. : owner(Owner)
  1948. {
  1949. }
  1950. int OppositeSideLimiter::limit(const BonusLimitationContext & context) const
  1951. {
  1952. auto contextOwner = CBonusSystemNode::retrieveNodeOwner(& context.node);
  1953. auto decision = (owner == contextOwner || owner == PlayerColor::CANNOT_DETERMINE) ? ILimiter::DISCARD : ILimiter::ACCEPT;
  1954. return decision;
  1955. }
  1956. // Aggregate/Boolean Limiters
  1957. void AggregateLimiter::add(TLimiterPtr limiter)
  1958. {
  1959. if(limiter)
  1960. limiters.push_back(limiter);
  1961. }
  1962. JsonNode AggregateLimiter::toJsonNode() const
  1963. {
  1964. JsonNode result(JsonNode::JsonType::DATA_VECTOR);
  1965. result.Vector().push_back(JsonUtils::stringNode(getAggregator()));
  1966. for(auto l : limiters)
  1967. result.Vector().push_back(l->toJsonNode());
  1968. return result;
  1969. }
  1970. const std::string AllOfLimiter::aggregator = "allOf";
  1971. const std::string & AllOfLimiter::getAggregator() const
  1972. {
  1973. return aggregator;
  1974. }
  1975. int AllOfLimiter::limit(const BonusLimitationContext & context) const
  1976. {
  1977. bool wasntSure = false;
  1978. for(auto limiter : limiters)
  1979. {
  1980. auto result = limiter->limit(context);
  1981. if(result == ILimiter::DISCARD)
  1982. return result;
  1983. if(result == ILimiter::NOT_SURE)
  1984. wasntSure = true;
  1985. }
  1986. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1987. }
  1988. const std::string AnyOfLimiter::aggregator = "anyOf";
  1989. const std::string & AnyOfLimiter::getAggregator() const
  1990. {
  1991. return aggregator;
  1992. }
  1993. int AnyOfLimiter::limit(const BonusLimitationContext & context) const
  1994. {
  1995. bool wasntSure = false;
  1996. for(auto limiter : limiters)
  1997. {
  1998. auto result = limiter->limit(context);
  1999. if(result == ILimiter::ACCEPT)
  2000. return result;
  2001. if(result == ILimiter::NOT_SURE)
  2002. wasntSure = true;
  2003. }
  2004. return wasntSure ? ILimiter::NOT_SURE : ILimiter::DISCARD;
  2005. }
  2006. const std::string NoneOfLimiter::aggregator = "noneOf";
  2007. const std::string & NoneOfLimiter::getAggregator() const
  2008. {
  2009. return aggregator;
  2010. }
  2011. int NoneOfLimiter::limit(const BonusLimitationContext & context) const
  2012. {
  2013. bool wasntSure = false;
  2014. for(auto limiter : limiters)
  2015. {
  2016. auto result = limiter->limit(context);
  2017. if(result == ILimiter::ACCEPT)
  2018. return ILimiter::DISCARD;
  2019. if(result == ILimiter::NOT_SURE)
  2020. wasntSure = true;
  2021. }
  2022. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  2023. }
  2024. // Updaters
  2025. std::shared_ptr<Bonus> Bonus::addUpdater(TUpdaterPtr Updater)
  2026. {
  2027. updater = Updater;
  2028. return this->shared_from_this();
  2029. }
  2030. // Update ONLY_ENEMY_ARMY bonuses from old saves to make them workable.
  2031. // Also, we should foreseen possible errors in bonus configuration and fix them.
  2032. void Bonus::updateOppositeBonuses()
  2033. {
  2034. if(effectRange != Bonus::ONLY_ENEMY_ARMY)
  2035. return;
  2036. if(propagator)
  2037. {
  2038. if(propagator->getPropagatorType() != CBonusSystemNode::BATTLE)
  2039. {
  2040. logMod->error("Wrong Propagator will be ignored: The 'ONLY_ENEMY_ARMY' effectRange is only compatible with the 'BATTLE_WIDE' propagator.");
  2041. propagator.reset(new CPropagatorNodeType(CBonusSystemNode::BATTLE));
  2042. }
  2043. }
  2044. else
  2045. {
  2046. propagator = std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE);
  2047. }
  2048. if(limiter)
  2049. {
  2050. if(!dynamic_cast<OppositeSideLimiter*>(limiter.get()))
  2051. {
  2052. logMod->error("Wrong Limiter will be ignored: The 'ONLY_ENEMY_ARMY' effectRange is only compatible with the 'OPPOSITE_SIDE' limiter.");
  2053. limiter.reset(new OppositeSideLimiter());
  2054. }
  2055. }
  2056. else
  2057. {
  2058. limiter = std::make_shared<OppositeSideLimiter>();
  2059. }
  2060. propagationUpdater = std::make_shared<OwnerUpdater>();
  2061. }
  2062. IUpdater::~IUpdater()
  2063. {
  2064. }
  2065. std::shared_ptr<Bonus> IUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2066. {
  2067. return b;
  2068. }
  2069. std::string IUpdater::toString() const
  2070. {
  2071. return typeid(*this).name();
  2072. }
  2073. JsonNode IUpdater::toJsonNode() const
  2074. {
  2075. return JsonNode(JsonNode::JsonType::DATA_NULL);
  2076. }
  2077. GrowsWithLevelUpdater::GrowsWithLevelUpdater() : valPer20(0), stepSize(1)
  2078. {
  2079. }
  2080. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  2081. {
  2082. }
  2083. std::shared_ptr<Bonus> GrowsWithLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2084. {
  2085. if(context.getNodeType() == CBonusSystemNode::HERO)
  2086. {
  2087. int level = static_cast<const CGHeroInstance &>(context).level;
  2088. int steps = stepSize ? level / stepSize : level;
  2089. //rounding follows format for HMM3 creature specialty bonus
  2090. int newVal = (valPer20 * steps + 19) / 20;
  2091. //return copy of bonus with updated val
  2092. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2093. newBonus->val = newVal;
  2094. return newBonus;
  2095. }
  2096. return b;
  2097. }
  2098. std::string GrowsWithLevelUpdater::toString() const
  2099. {
  2100. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  2101. }
  2102. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  2103. {
  2104. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2105. root["type"].String() = "GROWS_WITH_LEVEL";
  2106. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  2107. if(stepSize > 1)
  2108. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  2109. return root;
  2110. }
  2111. TimesHeroLevelUpdater::TimesHeroLevelUpdater()
  2112. {
  2113. }
  2114. std::shared_ptr<Bonus> TimesHeroLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2115. {
  2116. if(context.getNodeType() == CBonusSystemNode::HERO)
  2117. {
  2118. int level = static_cast<const CGHeroInstance &>(context).level;
  2119. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2120. newBonus->val *= level;
  2121. return newBonus;
  2122. }
  2123. return b;
  2124. }
  2125. std::string TimesHeroLevelUpdater::toString() const
  2126. {
  2127. return "TimesHeroLevelUpdater";
  2128. }
  2129. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  2130. {
  2131. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  2132. }
  2133. TimesStackLevelUpdater::TimesStackLevelUpdater()
  2134. {
  2135. }
  2136. std::shared_ptr<Bonus> TimesStackLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2137. {
  2138. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  2139. {
  2140. int level = static_cast<const CStackInstance &>(context).getLevel();
  2141. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2142. newBonus->val *= level;
  2143. return newBonus;
  2144. }
  2145. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  2146. {
  2147. const CStack & stack = static_cast<const CStack &>(context);
  2148. //only update if stack doesn't have an instance (summons, war machines)
  2149. //otherwise we'd end up multiplying twice
  2150. if(stack.base == nullptr)
  2151. {
  2152. int level = stack.type->level;
  2153. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2154. newBonus->val *= level;
  2155. return newBonus;
  2156. }
  2157. }
  2158. return b;
  2159. }
  2160. std::string TimesStackLevelUpdater::toString() const
  2161. {
  2162. return "TimesStackLevelUpdater";
  2163. }
  2164. JsonNode TimesStackLevelUpdater::toJsonNode() const
  2165. {
  2166. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  2167. }
  2168. OwnerUpdater::OwnerUpdater()
  2169. {
  2170. }
  2171. std::string OwnerUpdater::toString() const
  2172. {
  2173. return "OwnerUpdater";
  2174. }
  2175. JsonNode OwnerUpdater::toJsonNode() const
  2176. {
  2177. return JsonUtils::stringNode("BONUS_OWNER_UPDATER");
  2178. }
  2179. std::shared_ptr<Bonus> OwnerUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2180. {
  2181. auto owner = CBonusSystemNode::retrieveNodeOwner(&context);
  2182. if(owner == PlayerColor::UNFLAGGABLE)
  2183. owner = PlayerColor::NEUTRAL;
  2184. std::shared_ptr<Bonus> updated = std::make_shared<Bonus>(
  2185. (Bonus::BonusDuration)b->duration, b->type, b->source, b->val, b->sid, b->subtype, b->valType);
  2186. updated->limiter = std::make_shared<OppositeSideLimiter>(owner);
  2187. return updated;
  2188. }
  2189. VCMI_LIB_NAMESPACE_END