HeroBonus.cpp 64 KB

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