HeroBonus.cpp 68 KB

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