HeroBonus.cpp 65 KB

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