HeroBonus.cpp 47 KB

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