HeroBonus.cpp 59 KB

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