HeroBonus.cpp 47 KB

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