HeroBonus.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013
  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 "ILimiter.h"
  13. #include "IUpdater.h"
  14. #include "../VCMI_Lib.h"
  15. #include "../spells/CSpellHandler.h"
  16. #include "../CCreatureHandler.h"
  17. #include "../CCreatureSet.h"
  18. #include "../CHeroHandler.h"
  19. #include "../CTownHandler.h"
  20. #include "../CGeneralTextHandler.h"
  21. #include "../CSkillHandler.h"
  22. #include "../CStack.h"
  23. #include "../CArtHandler.h"
  24. #include "../CModHandler.h"
  25. #include "../TerrainHandler.h"
  26. #include "../StringConstants.h"
  27. #include "../battle/BattleInfo.h"
  28. VCMI_LIB_NAMESPACE_BEGIN
  29. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  30. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  31. #define BONUS_NAME(x) { #x, Bonus::x },
  32. const std::map<std::string, Bonus::BonusType> bonusNameMap = {
  33. BONUS_LIST
  34. };
  35. #undef BONUS_NAME
  36. #define BONUS_VALUE(x) { #x, Bonus::x },
  37. const std::map<std::string, Bonus::ValueType> bonusValueMap = { BONUS_VALUE_LIST };
  38. #undef BONUS_VALUE
  39. #define BONUS_SOURCE(x) { #x, Bonus::x },
  40. const std::map<std::string, Bonus::BonusSource> bonusSourceMap = { BONUS_SOURCE_LIST };
  41. #undef BONUS_SOURCE
  42. #define BONUS_ITEM(x) { #x, Bonus::x },
  43. const std::map<std::string, ui16> bonusDurationMap =
  44. {
  45. BONUS_ITEM(PERMANENT)
  46. BONUS_ITEM(ONE_BATTLE)
  47. BONUS_ITEM(ONE_DAY)
  48. BONUS_ITEM(ONE_WEEK)
  49. BONUS_ITEM(N_TURNS)
  50. BONUS_ITEM(N_DAYS)
  51. BONUS_ITEM(UNTIL_BEING_ATTACKED)
  52. BONUS_ITEM(UNTIL_ATTACK)
  53. BONUS_ITEM(STACK_GETS_TURN)
  54. BONUS_ITEM(COMMANDER_KILLED)
  55. { "UNITL_BEING_ATTACKED", Bonus::UNTIL_BEING_ATTACKED }//typo, but used in some mods
  56. };
  57. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  58. {
  59. BONUS_ITEM(NO_LIMIT)
  60. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  61. BONUS_ITEM(ONLY_MELEE_FIGHT)
  62. };
  63. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  64. {
  65. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  66. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  67. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  68. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  69. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  70. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)}
  71. }; //untested
  72. const std::set<std::string> deprecatedBonusSet = {
  73. "SECONDARY_SKILL_PREMY",
  74. "SECONDARY_SKILL_VAL2",
  75. "MAXED_SPELL",
  76. "LAND_MOVEMENT",
  77. "SEA_MOVEMENT",
  78. "SIGHT_RADIOUS",
  79. "NO_TYPE",
  80. "SPECIAL_SECONDARY_SKILL",
  81. "FULL_HP_REGENERATION",
  82. "KING1",
  83. "KING2",
  84. "KING3",
  85. "BLOCK_MORALE",
  86. "BLOCK_LUCK",
  87. "SELF_MORALE",
  88. "SELF_LUCK"
  89. };
  90. ///CBonusProxy
  91. CBonusProxy::CBonusProxy(const IBonusBearer * Target, CSelector Selector):
  92. bonusListCachedLast(0),
  93. target(Target),
  94. selector(std::move(Selector)),
  95. currentBonusListIndex(0)
  96. {
  97. }
  98. CBonusProxy::CBonusProxy(const CBonusProxy & other):
  99. bonusListCachedLast(other.bonusListCachedLast),
  100. target(other.target),
  101. selector(other.selector),
  102. currentBonusListIndex(other.currentBonusListIndex)
  103. {
  104. bonusList[currentBonusListIndex] = other.bonusList[currentBonusListIndex];
  105. }
  106. CBonusProxy::CBonusProxy(CBonusProxy && other) noexcept:
  107. bonusListCachedLast(0),
  108. target(other.target),
  109. currentBonusListIndex(0)
  110. {
  111. std::swap(bonusListCachedLast, other.bonusListCachedLast);
  112. std::swap(selector, other.selector);
  113. std::swap(bonusList, other.bonusList);
  114. std::swap(currentBonusListIndex, other.currentBonusListIndex);
  115. }
  116. CBonusProxy & CBonusProxy::operator=(const CBonusProxy & other)
  117. {
  118. boost::lock_guard<boost::mutex> lock(swapGuard);
  119. selector = other.selector;
  120. swapBonusList(other.bonusList[other.currentBonusListIndex]);
  121. bonusListCachedLast = other.bonusListCachedLast;
  122. return *this;
  123. }
  124. CBonusProxy & CBonusProxy::operator=(CBonusProxy && other) noexcept
  125. {
  126. std::swap(bonusListCachedLast, other.bonusListCachedLast);
  127. std::swap(selector, other.selector);
  128. std::swap(bonusList, other.bonusList);
  129. std::swap(currentBonusListIndex, other.currentBonusListIndex);
  130. return *this;
  131. }
  132. void CBonusProxy::swapBonusList(TConstBonusListPtr other) const
  133. {
  134. // The idea here is to avoid changing active bonusList while it can be read by a different thread.
  135. // Because such use of shared ptr is not thread safe
  136. // So to avoid this we change the second offline instance and swap active index
  137. auto newCurrent = 1 - currentBonusListIndex;
  138. bonusList[newCurrent] = std::move(other);
  139. currentBonusListIndex = newCurrent;
  140. }
  141. TConstBonusListPtr CBonusProxy::getBonusList() const
  142. {
  143. auto needUpdateBonusList = [&]() -> bool
  144. {
  145. return target->getTreeVersion() != bonusListCachedLast || !bonusList[currentBonusListIndex];
  146. };
  147. // avoid locking if everything is up-to-date
  148. if(needUpdateBonusList())
  149. {
  150. boost::lock_guard<boost::mutex>lock(swapGuard);
  151. if(needUpdateBonusList())
  152. {
  153. //TODO: support limiters
  154. swapBonusList(target->getAllBonuses(selector, Selector::all));
  155. bonusListCachedLast = target->getTreeVersion();
  156. }
  157. }
  158. return bonusList[currentBonusListIndex];
  159. }
  160. const BonusList * CBonusProxy::operator->() const
  161. {
  162. return getBonusList().get();
  163. }
  164. CTotalsProxy::CTotalsProxy(const IBonusBearer * Target, CSelector Selector, int InitialValue):
  165. CBonusProxy(Target, std::move(Selector)),
  166. initialValue(InitialValue),
  167. meleeCachedLast(0),
  168. meleeValue(0),
  169. rangedCachedLast(0),
  170. rangedValue(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. int CTotalsProxy::getValue() const
  183. {
  184. const auto treeVersion = target->getTreeVersion();
  185. if(treeVersion != valueCachedLast)
  186. {
  187. auto bonuses = getBonusList();
  188. value = initialValue + bonuses->totalValue();
  189. valueCachedLast = treeVersion;
  190. }
  191. return value;
  192. }
  193. int CTotalsProxy::getValueAndList(TConstBonusListPtr & outBonusList) const
  194. {
  195. const auto treeVersion = target->getTreeVersion();
  196. outBonusList = getBonusList();
  197. if(treeVersion != valueCachedLast)
  198. {
  199. value = initialValue + outBonusList->totalValue();
  200. valueCachedLast = treeVersion;
  201. }
  202. return value;
  203. }
  204. int CTotalsProxy::getMeleeValue() const
  205. {
  206. static const auto limit = Selector::effectRange()(Bonus::NO_LIMIT).Or(Selector::effectRange()(Bonus::ONLY_MELEE_FIGHT));
  207. const auto treeVersion = target->getTreeVersion();
  208. if(treeVersion != meleeCachedLast)
  209. {
  210. auto bonuses = target->getBonuses(selector, limit);
  211. meleeValue = initialValue + bonuses->totalValue();
  212. meleeCachedLast = treeVersion;
  213. }
  214. return meleeValue;
  215. }
  216. int CTotalsProxy::getRangedValue() const
  217. {
  218. static const auto limit = Selector::effectRange()(Bonus::NO_LIMIT).Or(Selector::effectRange()(Bonus::ONLY_DISTANCE_FIGHT));
  219. const auto treeVersion = target->getTreeVersion();
  220. if(treeVersion != rangedCachedLast)
  221. {
  222. auto bonuses = target->getBonuses(selector, limit);
  223. rangedValue = initialValue + bonuses->totalValue();
  224. rangedCachedLast = treeVersion;
  225. }
  226. return rangedValue;
  227. }
  228. ///CCheckProxy
  229. CCheckProxy::CCheckProxy(const IBonusBearer * Target, CSelector Selector):
  230. target(Target),
  231. selector(std::move(Selector)),
  232. cachedLast(0),
  233. hasBonus(false)
  234. {
  235. }
  236. //This constructor should be placed here to avoid side effects
  237. CCheckProxy::CCheckProxy(const CCheckProxy & other) = default;
  238. bool CCheckProxy::getHasBonus() const
  239. {
  240. const auto treeVersion = target->getTreeVersion();
  241. if(treeVersion != cachedLast)
  242. {
  243. hasBonus = target->hasBonus(selector);
  244. cachedLast = treeVersion;
  245. }
  246. return hasBonus;
  247. }
  248. //This constructor should be placed here to avoid side effects
  249. CAddInfo::CAddInfo() = default;
  250. CAddInfo::CAddInfo(si32 value)
  251. {
  252. if(value != CAddInfo::NONE)
  253. push_back(value);
  254. }
  255. bool CAddInfo::operator==(si32 value) const
  256. {
  257. switch(size())
  258. {
  259. case 0:
  260. return value == CAddInfo::NONE;
  261. case 1:
  262. return operator[](0) == value;
  263. default:
  264. return false;
  265. }
  266. }
  267. bool CAddInfo::operator!=(si32 value) const
  268. {
  269. return !operator==(value);
  270. }
  271. si32 & CAddInfo::operator[](size_type pos)
  272. {
  273. if(pos >= size())
  274. resize(pos + 1, CAddInfo::NONE);
  275. return vector::operator[](pos);
  276. }
  277. si32 CAddInfo::operator[](size_type pos) const
  278. {
  279. return pos < size() ? vector::operator[](pos) : CAddInfo::NONE;
  280. }
  281. std::string CAddInfo::toString() const
  282. {
  283. return toJsonNode().toJson(true);
  284. }
  285. JsonNode CAddInfo::toJsonNode() const
  286. {
  287. if(size() < 2)
  288. {
  289. return JsonUtils::intNode(operator[](0));
  290. }
  291. else
  292. {
  293. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  294. for(si32 value : *this)
  295. node.Vector().push_back(JsonUtils::intNode(value));
  296. return node;
  297. }
  298. }
  299. std::atomic<int64_t> CBonusSystemNode::treeChanged(1);
  300. constexpr bool CBonusSystemNode::cachingEnabled = true;
  301. BonusList::BonusList(bool BelongsToTree) : belongsToTree(BelongsToTree)
  302. {
  303. }
  304. BonusList::BonusList(const BonusList & bonusList): belongsToTree(false)
  305. {
  306. bonuses.resize(bonusList.size());
  307. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  308. }
  309. BonusList::BonusList(BonusList && other) noexcept: belongsToTree(false)
  310. {
  311. std::swap(belongsToTree, other.belongsToTree);
  312. std::swap(bonuses, other.bonuses);
  313. }
  314. BonusList& BonusList::operator=(const BonusList &bonusList)
  315. {
  316. bonuses.resize(bonusList.size());
  317. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  318. belongsToTree = false;
  319. return *this;
  320. }
  321. void BonusList::changed() const
  322. {
  323. if(belongsToTree)
  324. CBonusSystemNode::treeHasChanged();
  325. }
  326. void BonusList::stackBonuses()
  327. {
  328. boost::sort(bonuses, [](const std::shared_ptr<Bonus> & b1, const std::shared_ptr<Bonus> & b2) -> bool
  329. {
  330. if(b1 == b2)
  331. return false;
  332. #define COMPARE_ATT(ATT) if(b1->ATT != b2->ATT) return b1->ATT < b2->ATT
  333. COMPARE_ATT(stacking);
  334. COMPARE_ATT(type);
  335. COMPARE_ATT(subtype);
  336. COMPARE_ATT(valType);
  337. #undef COMPARE_ATT
  338. return b1->val > b2->val;
  339. });
  340. // remove non-stacking
  341. size_t next = 1;
  342. while(next < bonuses.size())
  343. {
  344. bool remove = false;
  345. std::shared_ptr<Bonus> last = bonuses[next-1];
  346. std::shared_ptr<Bonus> current = bonuses[next];
  347. if(current->stacking.empty())
  348. remove = current == last;
  349. else if(current->stacking == "ALWAYS")
  350. remove = false;
  351. else
  352. remove = current->stacking == last->stacking
  353. && current->type == last->type
  354. && current->subtype == last->subtype
  355. && current->valType == last->valType;
  356. if(remove)
  357. bonuses.erase(bonuses.begin() + next);
  358. else
  359. next++;
  360. }
  361. }
  362. int BonusList::totalValue() const
  363. {
  364. struct BonusCollection
  365. {
  366. int base = 0;
  367. int percentToBase = 0;
  368. int percentToAll = 0;
  369. int additive = 0;
  370. int percentToSource = 0;
  371. int indepMin = std::numeric_limits<int>::max();
  372. int indepMax = std::numeric_limits<int>::min();
  373. };
  374. auto percent = [](int64_t base, int64_t percent) -> int {
  375. return static_cast<int>(std::clamp<int64_t>((base * (100 + percent)) / 100, std::numeric_limits<int>::min(), std::numeric_limits<int>::max()));
  376. };
  377. std::array <BonusCollection, Bonus::BonusSource::NUM_BONUS_SOURCE> sources = {};
  378. BonusCollection any;
  379. bool hasIndepMax = false;
  380. bool hasIndepMin = false;
  381. for(const auto & b : bonuses)
  382. {
  383. switch(b->valType)
  384. {
  385. case Bonus::BASE_NUMBER:
  386. sources[b->source].base += b->val;
  387. break;
  388. case Bonus::PERCENT_TO_ALL:
  389. sources[b->source].percentToAll += b->val;
  390. break;
  391. case Bonus::PERCENT_TO_BASE:
  392. sources[b->source].percentToBase += b->val;
  393. break;
  394. case Bonus::PERCENT_TO_SOURCE:
  395. sources[b->source].percentToSource += b->val;
  396. break;
  397. case Bonus::PERCENT_TO_TARGET_TYPE:
  398. sources[b->targetSourceType].percentToSource += b->val;
  399. break;
  400. case Bonus::ADDITIVE_VALUE:
  401. sources[b->source].additive += b->val;
  402. break;
  403. case Bonus::INDEPENDENT_MAX:
  404. hasIndepMax = true;
  405. vstd::amax(sources[b->source].indepMax, b->val);
  406. break;
  407. case Bonus::INDEPENDENT_MIN:
  408. hasIndepMin = true;
  409. vstd::amin(sources[b->source].indepMin, b->val);
  410. break;
  411. }
  412. }
  413. for(const auto & src : sources)
  414. {
  415. any.base += percent(src.base, src.percentToSource);
  416. any.percentToBase += percent(src.percentToBase, src.percentToSource);
  417. any.percentToAll += percent(src.percentToAll, src.percentToSource);
  418. any.additive += percent(src.additive, src.percentToSource);
  419. if(hasIndepMin)
  420. vstd::amin(any.indepMin, percent(src.indepMin, src.percentToSource));
  421. if(hasIndepMax)
  422. vstd::amax(any.indepMax, percent(src.indepMax, src.percentToSource));
  423. }
  424. any.base = percent(any.base, any.percentToBase);
  425. any.base += any.additive;
  426. auto valFirst = percent(any.base ,any.percentToAll);
  427. if(hasIndepMin && hasIndepMax && any.indepMin < any.indepMax)
  428. any.indepMax = any.indepMin;
  429. const int notIndepBonuses = static_cast<int>(std::count_if(bonuses.cbegin(), bonuses.cend(), [](const std::shared_ptr<Bonus>& b)
  430. {
  431. return b->valType != Bonus::INDEPENDENT_MAX && b->valType != Bonus::INDEPENDENT_MIN;
  432. }));
  433. if(notIndepBonuses)
  434. return std::clamp(valFirst, any.indepMax, any.indepMin);
  435. return hasIndepMin ? any.indepMin : hasIndepMax ? any.indepMax : 0;
  436. }
  437. std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &select)
  438. {
  439. for (auto & b : bonuses)
  440. {
  441. if(select(b.get()))
  442. return b;
  443. }
  444. return nullptr;
  445. }
  446. std::shared_ptr<const Bonus> BonusList::getFirst(const CSelector &selector) const
  447. {
  448. for(const auto & b : bonuses)
  449. {
  450. if(selector(b.get()))
  451. return b;
  452. }
  453. return nullptr;
  454. }
  455. void BonusList::getBonuses(BonusList & out, const CSelector &selector, const CSelector &limit) const
  456. {
  457. out.reserve(bonuses.size());
  458. for(const auto & b : bonuses)
  459. {
  460. //add matching bonuses that matches limit predicate or have NO_LIMIT if no given predicate
  461. auto noFightLimit = b->effectRange == Bonus::NO_LIMIT;
  462. if(selector(b.get()) && ((!limit && noFightLimit) || ((bool)limit && limit(b.get()))))
  463. out.push_back(b);
  464. }
  465. }
  466. void BonusList::getAllBonuses(BonusList &out) const
  467. {
  468. for(const auto & b : bonuses)
  469. out.push_back(b);
  470. }
  471. int BonusList::valOfBonuses(const CSelector &select) const
  472. {
  473. BonusList ret;
  474. CSelector limit = nullptr;
  475. getBonuses(ret, select, limit);
  476. return ret.totalValue();
  477. }
  478. JsonNode BonusList::toJsonNode() const
  479. {
  480. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  481. for(const std::shared_ptr<Bonus> & b : bonuses)
  482. node.Vector().push_back(b->toJsonNode());
  483. return node;
  484. }
  485. void BonusList::push_back(const std::shared_ptr<Bonus> & x)
  486. {
  487. bonuses.push_back(x);
  488. changed();
  489. }
  490. BonusList::TInternalContainer::iterator BonusList::erase(const int position)
  491. {
  492. changed();
  493. return bonuses.erase(bonuses.begin() + position);
  494. }
  495. void BonusList::clear()
  496. {
  497. bonuses.clear();
  498. changed();
  499. }
  500. std::vector<BonusList *>::size_type BonusList::operator-=(const std::shared_ptr<Bonus> & i)
  501. {
  502. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  503. if(itr == bonuses.end())
  504. return false;
  505. bonuses.erase(itr);
  506. changed();
  507. return true;
  508. }
  509. void BonusList::resize(BonusList::TInternalContainer::size_type sz, const std::shared_ptr<Bonus> & c)
  510. {
  511. bonuses.resize(sz, c);
  512. changed();
  513. }
  514. void BonusList::reserve(TInternalContainer::size_type sz)
  515. {
  516. bonuses.reserve(sz);
  517. }
  518. void BonusList::insert(BonusList::TInternalContainer::iterator position, BonusList::TInternalContainer::size_type n, const std::shared_ptr<Bonus> & x)
  519. {
  520. bonuses.insert(position, n, x);
  521. changed();
  522. }
  523. CSelector IBonusBearer::anaffectedByMoraleSelector =
  524. Selector::type()(Bonus::NON_LIVING)
  525. .Or(Selector::type()(Bonus::UNDEAD))
  526. .Or(Selector::type()(Bonus::SIEGE_WEAPON))
  527. .Or(Selector::type()(Bonus::NO_MORALE));
  528. CSelector IBonusBearer::moraleSelector = Selector::type()(Bonus::MORALE);
  529. CSelector IBonusBearer::luckSelector = Selector::type()(Bonus::LUCK);
  530. IBonusBearer::IBonusBearer()
  531. :anaffectedByMorale(this, anaffectedByMoraleSelector),
  532. moraleValue(this, moraleSelector, 0),
  533. luckValue(this, luckSelector, 0)
  534. {
  535. }
  536. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  537. {
  538. return valOfBonuses(Selector::type()(type).And(selector));
  539. }
  540. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype) const
  541. {
  542. //This part is performance-critical
  543. std::string cachingStr = "type_" + std::to_string(static_cast<int>(type)) + "_" + std::to_string(subtype);
  544. CSelector s = Selector::type()(type);
  545. if(subtype != -1)
  546. s = s.And(Selector::subtype()(subtype));
  547. return valOfBonuses(s, cachingStr);
  548. }
  549. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  550. {
  551. CSelector limit = nullptr;
  552. TConstBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  553. return hlp->totalValue();
  554. }
  555. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  556. {
  557. //TODO: We don't need to count all bonuses and could break on first matching
  558. return getBonuses(selector, cachingStr)->size() > 0;
  559. }
  560. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  561. {
  562. return getBonuses(selector, limit, cachingStr)->size() > 0;
  563. }
  564. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  565. {
  566. //This part is performance-ciritcal
  567. std::string cachingStr = "type_" + std::to_string(static_cast<int>(type)) + "_" + std::to_string(subtype);
  568. CSelector s = Selector::type()(type);
  569. if(subtype != -1)
  570. s = s.And(Selector::subtype()(subtype));
  571. return hasBonus(s, cachingStr);
  572. }
  573. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  574. {
  575. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  576. }
  577. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  578. {
  579. return getAllBonuses(selector, limit, nullptr, cachingStr);
  580. }
  581. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  582. {
  583. boost::format fmt("source_%did_%d");
  584. fmt % static_cast<int>(source) % sourceID;
  585. return hasBonus(Selector::source(source,sourceID), fmt.str());
  586. }
  587. int IBonusBearer::MoraleVal() const
  588. {
  589. if(anaffectedByMorale.getHasBonus())
  590. return 0;
  591. return std::clamp(moraleValue.getValue(), -3, +3);
  592. }
  593. int IBonusBearer::LuckVal() const
  594. {
  595. if(hasBonusOfType(Bonus::NO_LUCK))
  596. return 0;
  597. return std::clamp(luckValue.getValue(), -3, +3);
  598. }
  599. int IBonusBearer::MoraleValAndBonusList(TConstBonusListPtr & bonusList) const
  600. {
  601. if(anaffectedByMorale.getHasBonus())
  602. {
  603. if(!bonusList->empty())
  604. bonusList = std::make_shared<const BonusList>();
  605. return 0;
  606. }
  607. return std::clamp(moraleValue.getValueAndList(bonusList), -3, +3);
  608. }
  609. int IBonusBearer::LuckValAndBonusList(TConstBonusListPtr & bonusList) const
  610. {
  611. if(hasBonusOfType(Bonus::NO_LUCK))
  612. {
  613. if(!bonusList->empty())
  614. bonusList = std::make_shared<const BonusList>();
  615. return 0;
  616. }
  617. return std::clamp(luckValue.getValueAndList(bonusList), -3, +3);
  618. }
  619. std::shared_ptr<const Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  620. {
  621. auto bonuses = getAllBonuses(selector, Selector::all);
  622. return bonuses->getFirst(Selector::all);
  623. }
  624. PlayerColor CBonusSystemNode::retrieveNodeOwner(const CBonusSystemNode * node)
  625. {
  626. return node ? node->getOwner() : PlayerColor::CANNOT_DETERMINE;
  627. }
  628. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector)
  629. {
  630. auto ret = bonuses.getFirst(selector);
  631. if(ret)
  632. return ret;
  633. FOREACH_PARENT(pname)
  634. {
  635. ret = pname->getBonusLocalFirst(selector);
  636. if (ret)
  637. return ret;
  638. }
  639. return nullptr;
  640. }
  641. std::shared_ptr<const Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector) const
  642. {
  643. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  644. }
  645. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  646. {
  647. for(const auto & elem : parents)
  648. {
  649. const CBonusSystemNode *parent = elem;
  650. out.insert(parent);
  651. }
  652. }
  653. void CBonusSystemNode::getParents(TNodes &out)
  654. {
  655. for (auto & elem : parents)
  656. {
  657. const CBonusSystemNode *parent = elem;
  658. out.insert(const_cast<CBonusSystemNode*>(parent));
  659. }
  660. }
  661. void CBonusSystemNode::getAllParents(TCNodes & out) const //retrieves list of parent nodes (nodes to inherit bonuses from)
  662. {
  663. for(auto * parent : parents)
  664. {
  665. out.insert(parent);
  666. parent->getAllParents(out);
  667. }
  668. }
  669. void CBonusSystemNode::getAllBonusesRec(BonusList &out, const CSelector & selector) const
  670. {
  671. //out has been reserved sufficient capacity at getAllBonuses() call
  672. BonusList beforeUpdate;
  673. TCNodes lparents;
  674. getAllParents(lparents);
  675. if(!lparents.empty())
  676. {
  677. //estimate on how many bonuses are missing yet - must be positive
  678. beforeUpdate.reserve(std::max(out.capacity() - out.size(), bonuses.size()));
  679. }
  680. else
  681. {
  682. beforeUpdate.reserve(bonuses.size()); //at most all local bonuses
  683. }
  684. for(const auto * parent : lparents)
  685. {
  686. parent->getAllBonusesRec(beforeUpdate, selector);
  687. }
  688. bonuses.getAllBonuses(beforeUpdate);
  689. for(const auto & b : beforeUpdate)
  690. {
  691. //We should not run updaters on non-selected bonuses
  692. auto updated = selector(b.get()) && b->updater
  693. ? getUpdatedBonus(b, b->updater)
  694. : b;
  695. //do not add bonus with updater
  696. bool bonusExists = false;
  697. for(const auto & bonus : out)
  698. {
  699. if (bonus == updated)
  700. bonusExists = true;
  701. if (bonus->updater && bonus->updater == updated->updater)
  702. bonusExists = true;
  703. }
  704. if (!bonusExists)
  705. out.push_back(updated);
  706. }
  707. }
  708. TConstBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  709. {
  710. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  711. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  712. {
  713. // Exclusive access for one thread
  714. boost::lock_guard<boost::mutex> lock(sync);
  715. // If the bonus system tree changes(state of a single node or the relations to each other) then
  716. // cache all bonus objects. Selector objects doesn't matter.
  717. if (cachedLast != treeChanged)
  718. {
  719. BonusList allBonuses;
  720. allBonuses.reserve(cachedBonuses.capacity()); //we assume we'll get about the same number of bonuses
  721. cachedBonuses.clear();
  722. cachedRequests.clear();
  723. getAllBonusesRec(allBonuses, Selector::all);
  724. limitBonuses(allBonuses, cachedBonuses);
  725. cachedBonuses.stackBonuses();
  726. cachedLast = treeChanged;
  727. }
  728. // If a bonus system request comes with a caching string then look up in the map if there are any
  729. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  730. if(!cachingStr.empty())
  731. {
  732. auto it = cachedRequests.find(cachingStr);
  733. if(it != cachedRequests.end())
  734. {
  735. //Cached list contains bonuses for our query with applied limiters
  736. return it->second;
  737. }
  738. }
  739. //We still don't have the bonuses (didn't returned them from cache)
  740. //Perform bonus selection
  741. auto ret = std::make_shared<BonusList>();
  742. cachedBonuses.getBonuses(*ret, selector, limit);
  743. // Save the results in the cache
  744. if(!cachingStr.empty())
  745. cachedRequests[cachingStr] = ret;
  746. return ret;
  747. }
  748. else
  749. {
  750. return getAllBonusesWithoutCaching(selector, limit, root);
  751. }
  752. }
  753. TConstBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  754. {
  755. auto ret = std::make_shared<BonusList>();
  756. // Get bonus results without caching enabled.
  757. BonusList beforeLimiting;
  758. BonusList afterLimiting;
  759. getAllBonusesRec(beforeLimiting, selector);
  760. if(!root || root == this)
  761. {
  762. limitBonuses(beforeLimiting, afterLimiting);
  763. }
  764. else if(root)
  765. {
  766. //We want to limit our query against an external node. We get all its bonuses,
  767. // add the ones we're considering and see if they're cut out by limiters
  768. BonusList rootBonuses;
  769. BonusList limitedRootBonuses;
  770. getAllBonusesRec(rootBonuses, selector);
  771. for(const auto & b : beforeLimiting)
  772. rootBonuses.push_back(b);
  773. root->limitBonuses(rootBonuses, limitedRootBonuses);
  774. for(const auto & b : beforeLimiting)
  775. if(vstd::contains(limitedRootBonuses, b))
  776. afterLimiting.push_back(b);
  777. }
  778. afterLimiting.getBonuses(*ret, selector, limit);
  779. ret->stackBonuses();
  780. return ret;
  781. }
  782. std::shared_ptr<Bonus> CBonusSystemNode::getUpdatedBonus(const std::shared_ptr<Bonus> & b, const TUpdaterPtr & updater) const
  783. {
  784. assert(updater);
  785. return updater->createUpdatedBonus(b, * this);
  786. }
  787. CBonusSystemNode::CBonusSystemNode()
  788. :CBonusSystemNode(false)
  789. {
  790. }
  791. CBonusSystemNode::CBonusSystemNode(bool isHypotetic):
  792. bonuses(true),
  793. exportedBonuses(true),
  794. nodeType(UNKNOWN),
  795. cachedLast(0),
  796. isHypotheticNode(isHypotetic)
  797. {
  798. }
  799. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType):
  800. bonuses(true),
  801. exportedBonuses(true),
  802. nodeType(NodeType),
  803. cachedLast(0),
  804. isHypotheticNode(false)
  805. {
  806. }
  807. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other) noexcept:
  808. bonuses(std::move(other.bonuses)),
  809. exportedBonuses(std::move(other.exportedBonuses)),
  810. nodeType(other.nodeType),
  811. description(other.description),
  812. cachedLast(0),
  813. isHypotheticNode(other.isHypotheticNode)
  814. {
  815. std::swap(parents, other.parents);
  816. std::swap(children, other.children);
  817. //fixing bonus tree without recalculation
  818. if(!isHypothetic())
  819. {
  820. for(CBonusSystemNode * n : parents)
  821. {
  822. n->children -= &other;
  823. n->children.push_back(this);
  824. }
  825. }
  826. for(CBonusSystemNode * n : children)
  827. {
  828. n->parents -= &other;
  829. n->parents.push_back(this);
  830. }
  831. //cache ignored
  832. //cachedBonuses
  833. //cachedRequests
  834. }
  835. CBonusSystemNode::~CBonusSystemNode()
  836. {
  837. detachFromAll();
  838. if(!children.empty())
  839. {
  840. while(!children.empty())
  841. children.front()->detachFrom(*this);
  842. }
  843. }
  844. void CBonusSystemNode::attachTo(CBonusSystemNode & parent)
  845. {
  846. assert(!vstd::contains(parents, &parent));
  847. parents.push_back(&parent);
  848. if(!isHypothetic())
  849. {
  850. if(parent.actsAsBonusSourceOnly())
  851. parent.newRedDescendant(*this);
  852. else
  853. newRedDescendant(parent);
  854. parent.newChildAttached(*this);
  855. }
  856. CBonusSystemNode::treeHasChanged();
  857. }
  858. void CBonusSystemNode::detachFrom(CBonusSystemNode & parent)
  859. {
  860. assert(vstd::contains(parents, &parent));
  861. if(!isHypothetic())
  862. {
  863. if(parent.actsAsBonusSourceOnly())
  864. parent.removedRedDescendant(*this);
  865. else
  866. removedRedDescendant(parent);
  867. }
  868. if (vstd::contains(parents, &parent))
  869. {
  870. parents -= &parent;
  871. }
  872. else
  873. {
  874. logBonus->error("Error on Detach. Node %s (nodeType=%d) has not parent %s (nodeType=%d)"
  875. , nodeShortInfo(), nodeType, parent.nodeShortInfo(), parent.nodeType);
  876. }
  877. if(!isHypothetic())
  878. {
  879. parent.childDetached(*this);
  880. }
  881. CBonusSystemNode::treeHasChanged();
  882. }
  883. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  884. {
  885. removeBonuses(s);
  886. for(CBonusSystemNode * child : children)
  887. child->removeBonusesRecursive(s);
  888. }
  889. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  890. {
  891. BonusList bl;
  892. exportedBonuses.getBonuses(bl, s, Selector::all);
  893. for(const auto & b : bl)
  894. {
  895. b->turnsRemain--;
  896. if(b->turnsRemain <= 0)
  897. removeBonus(b);
  898. }
  899. for(CBonusSystemNode *child : children)
  900. child->reduceBonusDurations(s);
  901. }
  902. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  903. {
  904. //turnsRemain shouldn't be zero for following durations
  905. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  906. {
  907. assert(b->turnsRemain);
  908. }
  909. assert(!vstd::contains(exportedBonuses, b));
  910. exportedBonuses.push_back(b);
  911. exportBonus(b);
  912. CBonusSystemNode::treeHasChanged();
  913. }
  914. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  915. {
  916. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  917. if(bonus)
  918. bonus->val += b->val;
  919. else
  920. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  921. }
  922. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  923. {
  924. exportedBonuses -= b;
  925. if(b->propagator)
  926. unpropagateBonus(b);
  927. else
  928. bonuses -= b;
  929. CBonusSystemNode::treeHasChanged();
  930. }
  931. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  932. {
  933. BonusList toRemove;
  934. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  935. for(const auto & bonus : toRemove)
  936. removeBonus(bonus);
  937. }
  938. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  939. {
  940. switch(nodeType)
  941. {
  942. case CREATURE:
  943. case ARTIFACT:
  944. case ARTIFACT_INSTANCE:
  945. return true;
  946. default:
  947. return false;
  948. }
  949. }
  950. void CBonusSystemNode::propagateBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & source)
  951. {
  952. if(b->propagator->shouldBeAttached(this))
  953. {
  954. auto propagated = b->propagationUpdater
  955. ? source.getUpdatedBonus(b, b->propagationUpdater)
  956. : b;
  957. bonuses.push_back(propagated);
  958. logBonus->trace("#$# %s #propagated to# %s", propagated->Description(), nodeName());
  959. }
  960. FOREACH_RED_CHILD(child)
  961. child->propagateBonus(b, source);
  962. }
  963. void CBonusSystemNode::unpropagateBonus(const std::shared_ptr<Bonus> & b)
  964. {
  965. if(b->propagator->shouldBeAttached(this))
  966. {
  967. bonuses -= b;
  968. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  969. }
  970. FOREACH_RED_CHILD(child)
  971. child->unpropagateBonus(b);
  972. }
  973. void CBonusSystemNode::newChildAttached(CBonusSystemNode & child)
  974. {
  975. assert(!vstd::contains(children, &child));
  976. children.push_back(&child);
  977. }
  978. void CBonusSystemNode::childDetached(CBonusSystemNode & child)
  979. {
  980. if(vstd::contains(children, &child))
  981. children -= &child;
  982. else
  983. {
  984. logBonus->error("Error on Detach. Node %s (nodeType=%d) is not a child of %s (nodeType=%d)"
  985. , child.nodeShortInfo(), child.nodeType, nodeShortInfo(), nodeType);
  986. }
  987. }
  988. void CBonusSystemNode::detachFromAll()
  989. {
  990. while(!parents.empty())
  991. detachFrom(*parents.front());
  992. }
  993. bool CBonusSystemNode::isIndependentNode() const
  994. {
  995. return parents.empty() && children.empty();
  996. }
  997. std::string CBonusSystemNode::nodeName() const
  998. {
  999. return !description.empty()
  1000. ? description
  1001. : std::string("Bonus system node of type ") + typeid(*this).name();
  1002. }
  1003. std::string CBonusSystemNode::nodeShortInfo() const
  1004. {
  1005. std::ostringstream str;
  1006. str << "'" << typeid(* this).name() << "'";
  1007. description.length() > 0
  1008. ? str << " (" << description << ")"
  1009. : str << " (no description)";
  1010. return str.str();
  1011. }
  1012. void CBonusSystemNode::deserializationFix()
  1013. {
  1014. exportBonuses();
  1015. }
  1016. void CBonusSystemNode::getRedParents(TNodes & out)
  1017. {
  1018. FOREACH_PARENT(pname)
  1019. {
  1020. if(pname->actsAsBonusSourceOnly())
  1021. {
  1022. out.insert(pname);
  1023. }
  1024. }
  1025. if(!actsAsBonusSourceOnly())
  1026. {
  1027. for(CBonusSystemNode *child : children)
  1028. {
  1029. out.insert(child);
  1030. }
  1031. }
  1032. }
  1033. void CBonusSystemNode::getRedChildren(TNodes &out)
  1034. {
  1035. FOREACH_PARENT(pname)
  1036. {
  1037. if(!pname->actsAsBonusSourceOnly())
  1038. {
  1039. out.insert(pname);
  1040. }
  1041. }
  1042. if(actsAsBonusSourceOnly())
  1043. {
  1044. for(CBonusSystemNode *child : children)
  1045. {
  1046. out.insert(child);
  1047. }
  1048. }
  1049. }
  1050. void CBonusSystemNode::newRedDescendant(CBonusSystemNode & descendant)
  1051. {
  1052. for(const auto & b : exportedBonuses)
  1053. {
  1054. if(b->propagator)
  1055. descendant.propagateBonus(b, *this);
  1056. }
  1057. TNodes redParents;
  1058. getRedAncestors(redParents); //get all red parents recursively
  1059. for(auto * parent : redParents)
  1060. {
  1061. for(const auto & b : parent->exportedBonuses)
  1062. {
  1063. if(b->propagator)
  1064. descendant.propagateBonus(b, *this);
  1065. }
  1066. }
  1067. }
  1068. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode & descendant)
  1069. {
  1070. for(const auto & b : exportedBonuses)
  1071. if(b->propagator)
  1072. descendant.unpropagateBonus(b);
  1073. TNodes redParents;
  1074. getRedAncestors(redParents); //get all red parents recursively
  1075. for(auto * parent : redParents)
  1076. {
  1077. for(const auto & b : parent->exportedBonuses)
  1078. if(b->propagator)
  1079. descendant.unpropagateBonus(b);
  1080. }
  1081. }
  1082. void CBonusSystemNode::getRedAncestors(TNodes &out)
  1083. {
  1084. getRedParents(out);
  1085. TNodes redParents;
  1086. getRedParents(redParents);
  1087. for(CBonusSystemNode * parent : redParents)
  1088. parent->getRedAncestors(out);
  1089. }
  1090. void CBonusSystemNode::exportBonus(const std::shared_ptr<Bonus> & b)
  1091. {
  1092. if(b->propagator)
  1093. propagateBonus(b, *this);
  1094. else
  1095. bonuses.push_back(b);
  1096. CBonusSystemNode::treeHasChanged();
  1097. }
  1098. void CBonusSystemNode::exportBonuses()
  1099. {
  1100. for(const auto & b : exportedBonuses)
  1101. exportBonus(b);
  1102. }
  1103. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  1104. {
  1105. return nodeType;
  1106. }
  1107. const BonusList& CBonusSystemNode::getBonusList() const
  1108. {
  1109. return bonuses;
  1110. }
  1111. const TNodesVector& CBonusSystemNode::getParentNodes() const
  1112. {
  1113. return parents;
  1114. }
  1115. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  1116. {
  1117. return children;
  1118. }
  1119. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  1120. {
  1121. nodeType = type;
  1122. }
  1123. BonusList & CBonusSystemNode::getExportedBonusList()
  1124. {
  1125. return exportedBonuses;
  1126. }
  1127. const BonusList & CBonusSystemNode::getExportedBonusList() const
  1128. {
  1129. return exportedBonuses;
  1130. }
  1131. const std::string& CBonusSystemNode::getDescription() const
  1132. {
  1133. return description;
  1134. }
  1135. void CBonusSystemNode::setDescription(const std::string &description)
  1136. {
  1137. this->description = description;
  1138. }
  1139. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  1140. {
  1141. assert(&allBonuses != &out); //todo should it work in-place?
  1142. BonusList undecided = allBonuses;
  1143. BonusList & accepted = out;
  1144. while(true)
  1145. {
  1146. int undecidedCount = static_cast<int>(undecided.size());
  1147. for(int i = 0; i < undecided.size(); i++)
  1148. {
  1149. auto b = undecided[i];
  1150. BonusLimitationContext context = {*b, *this, out, undecided};
  1151. auto decision = b->limiter ? b->limiter->limit(context) : ILimiter::EDecision::ACCEPT; //bonuses without limiters will be accepted by default
  1152. if(decision == ILimiter::EDecision::DISCARD)
  1153. {
  1154. undecided.erase(i);
  1155. i--; continue;
  1156. }
  1157. else if(decision == ILimiter::EDecision::ACCEPT)
  1158. {
  1159. accepted.push_back(b);
  1160. undecided.erase(i);
  1161. i--; continue;
  1162. }
  1163. else
  1164. assert(decision == ILimiter::EDecision::NOT_SURE);
  1165. }
  1166. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  1167. return;
  1168. }
  1169. }
  1170. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  1171. {
  1172. auto ret = std::make_shared<BonusList>();
  1173. limitBonuses(allBonuses, *ret);
  1174. return ret;
  1175. }
  1176. void CBonusSystemNode::treeHasChanged()
  1177. {
  1178. treeChanged++;
  1179. }
  1180. int64_t CBonusSystemNode::getTreeVersion() const
  1181. {
  1182. return treeChanged;
  1183. }
  1184. std::string Bonus::Description(std::optional<si32> customValue) const
  1185. {
  1186. std::ostringstream str;
  1187. if(description.empty())
  1188. {
  1189. if(stacking.empty() || stacking == "ALWAYS")
  1190. {
  1191. switch(source)
  1192. {
  1193. case ARTIFACT:
  1194. str << ArtifactID(sid).toArtifact(VLC->artifacts())->getNameTranslated();
  1195. break;
  1196. case SPELL_EFFECT:
  1197. str << SpellID(sid).toSpell(VLC->spells())->getNameTranslated();
  1198. break;
  1199. case CREATURE_ABILITY:
  1200. str << VLC->creh->objects[sid]->getNamePluralTranslated();
  1201. break;
  1202. case SECONDARY_SKILL:
  1203. str << VLC->skillh->getByIndex(sid)->getNameTranslated();
  1204. break;
  1205. case HERO_SPECIAL:
  1206. str << VLC->heroh->objects[sid]->getNameTranslated();
  1207. break;
  1208. default:
  1209. //todo: handle all possible sources
  1210. str << "Unknown";
  1211. break;
  1212. }
  1213. }
  1214. else
  1215. str << stacking;
  1216. }
  1217. else
  1218. {
  1219. str << description;
  1220. }
  1221. if(auto value = customValue.value_or(val))
  1222. str << " " << std::showpos << value;
  1223. return str.str();
  1224. }
  1225. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  1226. {
  1227. switch(type)
  1228. {
  1229. case Bonus::PRIMARY_SKILL:
  1230. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  1231. case Bonus::SPECIAL_SPELL_LEV:
  1232. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1233. case Bonus::SPELL:
  1234. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1235. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1236. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1237. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "spell", SpellID::encode(subtype)));
  1238. case Bonus::IMPROVED_NECROMANCY:
  1239. case Bonus::SPECIAL_UPGRADE:
  1240. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(subtype)));
  1241. case Bonus::GENERATE_RESOURCE:
  1242. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1243. default:
  1244. return JsonUtils::intNode(subtype);
  1245. }
  1246. }
  1247. JsonNode additionalInfoToJson(Bonus::BonusType type, CAddInfo addInfo)
  1248. {
  1249. switch(type)
  1250. {
  1251. case Bonus::SPECIAL_UPGRADE:
  1252. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(addInfo[0])));
  1253. default:
  1254. return addInfo.toJsonNode();
  1255. }
  1256. }
  1257. JsonNode durationToJson(ui16 duration)
  1258. {
  1259. std::vector<std::string> durationNames;
  1260. for(ui16 durBit = 1; durBit; durBit = durBit << 1)
  1261. {
  1262. if(duration & durBit)
  1263. durationNames.push_back(vstd::findKey(bonusDurationMap, durBit));
  1264. }
  1265. if(durationNames.size() == 1)
  1266. {
  1267. return JsonUtils::stringNode(durationNames[0]);
  1268. }
  1269. else
  1270. {
  1271. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  1272. for(const std::string & dur : durationNames)
  1273. node.Vector().push_back(JsonUtils::stringNode(dur));
  1274. return node;
  1275. }
  1276. }
  1277. JsonNode Bonus::toJsonNode() const
  1278. {
  1279. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1280. // only add values that might reasonably be found in config files
  1281. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1282. if(subtype != -1)
  1283. root["subtype"] = subtypeToJson(type, subtype);
  1284. if(additionalInfo != CAddInfo::NONE)
  1285. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1286. if(duration != 0)
  1287. {
  1288. JsonNode durationVec(JsonNode::JsonType::DATA_VECTOR);
  1289. for(const auto & kv : bonusDurationMap)
  1290. {
  1291. if(duration & kv.second)
  1292. durationVec.Vector().push_back(JsonUtils::stringNode(kv.first));
  1293. }
  1294. root["duration"] = durationVec;
  1295. }
  1296. if(turnsRemain != 0)
  1297. root["turns"].Integer() = turnsRemain;
  1298. if(source != OTHER)
  1299. root["sourceType"].String() = vstd::findKey(bonusSourceMap, source);
  1300. if(targetSourceType != OTHER)
  1301. root["targetSourceType"].String() = vstd::findKey(bonusSourceMap, targetSourceType);
  1302. if(sid != 0)
  1303. root["sourceID"].Integer() = sid;
  1304. if(val != 0)
  1305. root["val"].Integer() = val;
  1306. if(valType != ADDITIVE_VALUE)
  1307. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1308. if(!stacking.empty())
  1309. root["stacking"].String() = stacking;
  1310. if(!description.empty())
  1311. root["description"].String() = description;
  1312. if(effectRange != NO_LIMIT)
  1313. root["effectRange"].String() = vstd::findKey(bonusLimitEffect, effectRange);
  1314. if(duration != PERMANENT)
  1315. root["duration"] = durationToJson(duration);
  1316. if(turnsRemain)
  1317. root["turns"].Integer() = turnsRemain;
  1318. if(limiter)
  1319. root["limiters"] = limiter->toJsonNode();
  1320. if(updater)
  1321. root["updater"] = updater->toJsonNode();
  1322. if(propagator)
  1323. root["propagator"].String() = vstd::findKey(bonusPropagatorMap, propagator);
  1324. return root;
  1325. }
  1326. std::string Bonus::nameForBonus() const
  1327. {
  1328. switch(type)
  1329. {
  1330. case Bonus::PRIMARY_SKILL:
  1331. return PrimarySkill::names[subtype];
  1332. case Bonus::SPECIAL_SPELL_LEV:
  1333. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1334. case Bonus::SPELL:
  1335. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1336. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1337. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1338. return VLC->spells()->getByIndex(subtype)->getJsonKey();
  1339. case Bonus::SPECIAL_UPGRADE:
  1340. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo[0]);
  1341. case Bonus::GENERATE_RESOURCE:
  1342. return GameConstants::RESOURCE_NAMES[subtype];
  1343. case Bonus::STACKS_SPEED:
  1344. return "speed";
  1345. default:
  1346. return vstd::findKey(bonusNameMap, type);
  1347. }
  1348. }
  1349. BonusParams::BonusParams(std::string deprecatedTypeStr, std::string deprecatedSubtypeStr, int deprecatedSubtype):
  1350. isConverted(true)
  1351. {
  1352. if(deprecatedTypeStr == "SECONDARY_SKILL_PREMY" || deprecatedTypeStr == "SPECIAL_SECONDARY_SKILL")
  1353. {
  1354. if(deprecatedSubtype == SecondarySkill::PATHFINDING || deprecatedSubtypeStr == "skill.pathfinding")
  1355. type = Bonus::ROUGH_TERRAIN_DISCOUNT;
  1356. else if(deprecatedSubtype == SecondarySkill::DIPLOMACY || deprecatedSubtypeStr == "skill.diplomacy")
  1357. type = Bonus::WANDERING_CREATURES_JOIN_BONUS;
  1358. else if(deprecatedSubtype == SecondarySkill::WISDOM || deprecatedSubtypeStr == "skill.wisdom")
  1359. type = Bonus::MAX_LEARNABLE_SPELL_LEVEL;
  1360. else if(deprecatedSubtype == SecondarySkill::MYSTICISM || deprecatedSubtypeStr == "skill.mysticism")
  1361. type = Bonus::MANA_REGENERATION;
  1362. else if(deprecatedSubtype == SecondarySkill::NECROMANCY || deprecatedSubtypeStr == "skill.necromancy")
  1363. type = Bonus::UNDEAD_RAISE_PERCENTAGE;
  1364. else if(deprecatedSubtype == SecondarySkill::LEARNING || deprecatedSubtypeStr == "skill.learning")
  1365. type = Bonus::HERO_EXPERIENCE_GAIN_PERCENT;
  1366. else if(deprecatedSubtype == SecondarySkill::RESISTANCE || deprecatedSubtypeStr == "skill.resistance")
  1367. type = Bonus::MAGIC_RESISTANCE;
  1368. else if(deprecatedSubtype == SecondarySkill::EAGLE_EYE || deprecatedSubtypeStr == "skill.eagleEye")
  1369. type = Bonus::LEARN_BATTLE_SPELL_CHANCE;
  1370. else if(deprecatedSubtype == SecondarySkill::SCOUTING || deprecatedSubtypeStr == "skill.scouting")
  1371. type = Bonus::SIGHT_RADIUS;
  1372. else if(deprecatedSubtype == SecondarySkill::INTELLIGENCE || deprecatedSubtypeStr == "skill.intelligence")
  1373. {
  1374. type = Bonus::MANA_PER_KNOWLEDGE;
  1375. valueType = Bonus::PERCENT_TO_BASE;
  1376. valueTypeRelevant = true;
  1377. }
  1378. else if(deprecatedSubtype == SecondarySkill::SORCERY || deprecatedSubtypeStr == "skill.sorcery")
  1379. type = Bonus::SPELL_DAMAGE;
  1380. else if(deprecatedSubtype == SecondarySkill::SCHOLAR || deprecatedSubtypeStr == "skill.scholar")
  1381. type = Bonus::LEARN_MEETING_SPELL_LIMIT;
  1382. else if(deprecatedSubtype == SecondarySkill::ARCHERY|| deprecatedSubtypeStr == "skill.archery")
  1383. {
  1384. subtype = 1;
  1385. subtypeRelevant = true;
  1386. type = Bonus::PERCENTAGE_DAMAGE_BOOST;
  1387. }
  1388. else if(deprecatedSubtype == SecondarySkill::OFFENCE || deprecatedSubtypeStr == "skill.offence")
  1389. {
  1390. subtype = 0;
  1391. subtypeRelevant = true;
  1392. type = Bonus::PERCENTAGE_DAMAGE_BOOST;
  1393. }
  1394. else if(deprecatedSubtype == SecondarySkill::ARMORER || deprecatedSubtypeStr == "skill.armorer")
  1395. {
  1396. subtype = -1;
  1397. subtypeRelevant = true;
  1398. type = Bonus::GENERAL_DAMAGE_REDUCTION;
  1399. }
  1400. else if(deprecatedSubtype == SecondarySkill::NAVIGATION || deprecatedSubtypeStr == "skill.navigation")
  1401. {
  1402. subtype = 0;
  1403. subtypeRelevant = true;
  1404. valueType = Bonus::PERCENT_TO_BASE;
  1405. valueTypeRelevant = true;
  1406. type = Bonus::MOVEMENT;
  1407. }
  1408. else if(deprecatedSubtype == SecondarySkill::LOGISTICS || deprecatedSubtypeStr == "skill.logistics")
  1409. {
  1410. subtype = 1;
  1411. subtypeRelevant = true;
  1412. valueType = Bonus::PERCENT_TO_BASE;
  1413. valueTypeRelevant = true;
  1414. type = Bonus::MOVEMENT;
  1415. }
  1416. else if(deprecatedSubtype == SecondarySkill::ESTATES || deprecatedSubtypeStr == "skill.estates")
  1417. {
  1418. type = Bonus::GENERATE_RESOURCE;
  1419. subtype = GameResID(EGameResID::GOLD);
  1420. subtypeRelevant = true;
  1421. }
  1422. else if(deprecatedSubtype == SecondarySkill::AIR_MAGIC || deprecatedSubtypeStr == "skill.airMagic")
  1423. {
  1424. type = Bonus::MAGIC_SCHOOL_SKILL;
  1425. subtypeRelevant = true;
  1426. subtype = 4;
  1427. }
  1428. else if(deprecatedSubtype == SecondarySkill::WATER_MAGIC || deprecatedSubtypeStr == "skill.waterMagic")
  1429. {
  1430. type = Bonus::MAGIC_SCHOOL_SKILL;
  1431. subtypeRelevant = true;
  1432. subtype = 1;
  1433. }
  1434. else if(deprecatedSubtype == SecondarySkill::FIRE_MAGIC || deprecatedSubtypeStr == "skill.fireMagic")
  1435. {
  1436. type = Bonus::MAGIC_SCHOOL_SKILL;
  1437. subtypeRelevant = true;
  1438. subtype = 2;
  1439. }
  1440. else if(deprecatedSubtype == SecondarySkill::EARTH_MAGIC || deprecatedSubtypeStr == "skill.earthMagic")
  1441. {
  1442. type = Bonus::MAGIC_SCHOOL_SKILL;
  1443. subtypeRelevant = true;
  1444. subtype = 8;
  1445. }
  1446. else if (deprecatedSubtype == SecondarySkill::ARTILLERY || deprecatedSubtypeStr == "skill.artillery")
  1447. {
  1448. type = Bonus::BONUS_DAMAGE_CHANCE;
  1449. subtypeRelevant = true;
  1450. subtypeStr = "core:creature.ballista";
  1451. }
  1452. else if (deprecatedSubtype == SecondarySkill::FIRST_AID || deprecatedSubtypeStr == "skill.firstAid")
  1453. {
  1454. type = Bonus::SPECIFIC_SPELL_POWER;
  1455. subtypeRelevant = true;
  1456. subtypeStr = "core:spell.firstAid";
  1457. }
  1458. else if (deprecatedSubtype == SecondarySkill::BALLISTICS || deprecatedSubtypeStr == "skill.ballistics")
  1459. {
  1460. type = Bonus::CATAPULT_EXTRA_SHOTS;
  1461. subtypeRelevant = true;
  1462. subtypeStr = "core:spell.catapultShot";
  1463. }
  1464. else
  1465. isConverted = false;
  1466. }
  1467. else if (deprecatedTypeStr == "SECONDARY_SKILL_VAL2")
  1468. {
  1469. if(deprecatedSubtype == SecondarySkill::EAGLE_EYE || deprecatedSubtypeStr == "skill.eagleEye")
  1470. type = Bonus::LEARN_BATTLE_SPELL_LEVEL_LIMIT;
  1471. else if (deprecatedSubtype == SecondarySkill::ARTILLERY || deprecatedSubtypeStr == "skill.artillery")
  1472. {
  1473. type = Bonus::HERO_GRANTS_ATTACKS;
  1474. subtypeRelevant = true;
  1475. subtypeStr = "core:creature.ballista";
  1476. }
  1477. else
  1478. isConverted = false;
  1479. }
  1480. else if (deprecatedTypeStr == "SEA_MOVEMENT")
  1481. {
  1482. subtype = 0;
  1483. subtypeRelevant = true;
  1484. valueType = Bonus::ADDITIVE_VALUE;
  1485. valueTypeRelevant = true;
  1486. type = Bonus::MOVEMENT;
  1487. }
  1488. else if (deprecatedTypeStr == "LAND_MOVEMENT")
  1489. {
  1490. subtype = 1;
  1491. subtypeRelevant = true;
  1492. valueType = Bonus::ADDITIVE_VALUE;
  1493. valueTypeRelevant = true;
  1494. type = Bonus::MOVEMENT;
  1495. }
  1496. else if (deprecatedTypeStr == "MAXED_SPELL")
  1497. {
  1498. type = Bonus::SPELL;
  1499. subtypeStr = deprecatedSubtypeStr;
  1500. subtypeRelevant = true;
  1501. valueType = Bonus::INDEPENDENT_MAX;
  1502. valueTypeRelevant = true;
  1503. val = 3;
  1504. valRelevant = true;
  1505. }
  1506. else if (deprecatedTypeStr == "FULL_HP_REGENERATION")
  1507. {
  1508. type = Bonus::HP_REGENERATION;
  1509. val = 100000; //very high value to always chose stack health
  1510. valRelevant = true;
  1511. }
  1512. else if (deprecatedTypeStr == "KING1")
  1513. {
  1514. type = Bonus::KING;
  1515. val = 0;
  1516. valRelevant = true;
  1517. }
  1518. else if (deprecatedTypeStr == "KING2")
  1519. {
  1520. type = Bonus::KING;
  1521. val = 2;
  1522. valRelevant = true;
  1523. }
  1524. else if (deprecatedTypeStr == "KING3")
  1525. {
  1526. type = Bonus::KING;
  1527. val = 3;
  1528. valRelevant = true;
  1529. }
  1530. else if (deprecatedTypeStr == "SIGHT_RADIOUS")
  1531. type = Bonus::SIGHT_RADIUS;
  1532. else if (deprecatedTypeStr == "SELF_MORALE")
  1533. {
  1534. type = Bonus::MORALE;
  1535. val = 1;
  1536. valRelevant = true;
  1537. valueType = Bonus::INDEPENDENT_MAX;
  1538. valueTypeRelevant = true;
  1539. }
  1540. else if (deprecatedTypeStr == "SELF_LUCK")
  1541. {
  1542. type = Bonus::LUCK;
  1543. val = 1;
  1544. valRelevant = true;
  1545. valueType = Bonus::INDEPENDENT_MAX;
  1546. valueTypeRelevant = true;
  1547. }
  1548. else
  1549. isConverted = false;
  1550. }
  1551. const JsonNode & BonusParams::toJson()
  1552. {
  1553. assert(isConverted);
  1554. if(ret.isNull())
  1555. {
  1556. ret["type"].String() = vstd::findKey(bonusNameMap, type);
  1557. if(subtypeRelevant && !subtypeStr.empty())
  1558. ret["subtype"].String() = subtypeStr;
  1559. else if(subtypeRelevant)
  1560. ret["subtype"].Integer() = subtype;
  1561. if(valueTypeRelevant)
  1562. ret["valueType"].String() = vstd::findKey(bonusValueMap, valueType);
  1563. if(valRelevant)
  1564. ret["val"].Float() = val;
  1565. if(targetTypeRelevant)
  1566. ret["targetSourceType"].String() = vstd::findKey(bonusSourceMap, targetType);
  1567. jsonCreated = true;
  1568. }
  1569. return ret;
  1570. };
  1571. CSelector BonusParams::toSelector()
  1572. {
  1573. assert(isConverted);
  1574. if(subtypeRelevant && !subtypeStr.empty())
  1575. JsonUtils::resolveIdentifier(subtype, toJson(), "subtype");
  1576. auto ret = Selector::type()(type);
  1577. if(subtypeRelevant)
  1578. ret = ret.And(Selector::subtype()(subtype));
  1579. if(valueTypeRelevant)
  1580. ret = ret.And(Selector::valueType(valueType));
  1581. if(targetTypeRelevant)
  1582. ret = ret.And(Selector::targetSourceType()(targetType));
  1583. return ret;
  1584. }
  1585. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype):
  1586. duration(static_cast<ui16>(Duration)),
  1587. type(Type),
  1588. subtype(Subtype),
  1589. source(Src),
  1590. val(Val),
  1591. sid(ID),
  1592. description(std::move(Desc))
  1593. {
  1594. boost::algorithm::trim(description);
  1595. targetSourceType = OTHER;
  1596. }
  1597. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType):
  1598. duration(static_cast<ui16>(Duration)),
  1599. type(Type),
  1600. subtype(Subtype),
  1601. source(Src),
  1602. val(Val),
  1603. sid(ID),
  1604. valType(ValType)
  1605. {
  1606. turnsRemain = 0;
  1607. effectRange = NO_LIMIT;
  1608. targetSourceType = OTHER;
  1609. }
  1610. std::shared_ptr<Bonus> Bonus::addPropagator(const TPropagatorPtr & Propagator)
  1611. {
  1612. propagator = Propagator;
  1613. return this->shared_from_this();
  1614. }
  1615. namespace Selector
  1616. {
  1617. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type()
  1618. {
  1619. static CSelectFieldEqual<Bonus::BonusType> stype(&Bonus::type);
  1620. return stype;
  1621. }
  1622. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype()
  1623. {
  1624. static CSelectFieldEqual<TBonusSubtype> ssubtype(&Bonus::subtype);
  1625. return ssubtype;
  1626. }
  1627. DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info()
  1628. {
  1629. static CSelectFieldEqual<CAddInfo> sinfo(&Bonus::additionalInfo);
  1630. return sinfo;
  1631. }
  1632. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType()
  1633. {
  1634. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::source);
  1635. return ssourceType;
  1636. }
  1637. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & targetSourceType()
  1638. {
  1639. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::targetSourceType);
  1640. return ssourceType;
  1641. }
  1642. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange()
  1643. {
  1644. static CSelectFieldEqual<Bonus::LimitEffect> seffectRange(&Bonus::effectRange);
  1645. return seffectRange;
  1646. }
  1647. DLL_LINKAGE CWillLastTurns turns;
  1648. DLL_LINKAGE CWillLastDays days;
  1649. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1650. {
  1651. return type()(Type).And(subtype()(Subtype));
  1652. }
  1653. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, const CAddInfo & info)
  1654. {
  1655. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1656. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1657. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1658. }
  1659. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1660. {
  1661. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1662. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1663. }
  1664. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1665. {
  1666. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1667. }
  1668. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1669. {
  1670. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1671. }
  1672. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1673. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1674. }
  1675. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1676. {
  1677. for (ui32 i = 0; i < bonusList.size(); i++)
  1678. {
  1679. const auto & b = bonusList[i];
  1680. out << "Bonus " << i << "\n" << *b << std::endl;
  1681. }
  1682. return out;
  1683. }
  1684. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1685. {
  1686. for(const auto & i : bonusNameMap)
  1687. if(i.second == bonus.type)
  1688. out << "\tType: " << i.first << " \t";
  1689. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1690. printField(val);
  1691. printField(subtype);
  1692. printField(duration);
  1693. printField(source);
  1694. printField(sid);
  1695. if(bonus.additionalInfo != CAddInfo::NONE)
  1696. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1697. printField(turnsRemain);
  1698. printField(valType);
  1699. if(!bonus.stacking.empty())
  1700. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1701. printField(effectRange);
  1702. #undef printField
  1703. if(bonus.limiter)
  1704. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1705. if(bonus.updater)
  1706. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1707. return out;
  1708. }
  1709. std::shared_ptr<Bonus> Bonus::addLimiter(const TLimiterPtr & Limiter)
  1710. {
  1711. if (limiter)
  1712. {
  1713. //If we already have limiter list, retrieve it
  1714. auto limiterList = std::dynamic_pointer_cast<AllOfLimiter>(limiter);
  1715. if(!limiterList)
  1716. {
  1717. //Create a new limiter list with old limiter and the new one will be pushed later
  1718. limiterList = std::make_shared<AllOfLimiter>();
  1719. limiterList->add(limiter);
  1720. limiter = limiterList;
  1721. }
  1722. limiterList->add(Limiter);
  1723. }
  1724. else
  1725. {
  1726. limiter = Limiter;
  1727. }
  1728. return this->shared_from_this();
  1729. }
  1730. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1731. {
  1732. return false;
  1733. }
  1734. CBonusSystemNode::ENodeTypes IPropagator::getPropagatorType() const
  1735. {
  1736. return CBonusSystemNode::ENodeTypes::NONE;
  1737. }
  1738. CPropagatorNodeType::CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType)
  1739. : nodeType(NodeType)
  1740. {
  1741. }
  1742. CBonusSystemNode::ENodeTypes CPropagatorNodeType::getPropagatorType() const
  1743. {
  1744. return nodeType;
  1745. }
  1746. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1747. {
  1748. return nodeType == dest->getNodeType();
  1749. }
  1750. // Updaters
  1751. std::shared_ptr<Bonus> Bonus::addUpdater(const TUpdaterPtr & Updater)
  1752. {
  1753. updater = Updater;
  1754. return this->shared_from_this();
  1755. }
  1756. VCMI_LIB_NAMESPACE_END