HeroBonus.cpp 68 KB

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