HeroBonus.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336
  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 "StringConstants.h"
  23. #include "battle/BattleInfo.h"
  24. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  25. #define FOREACH_CPARENT(pname) TCNodes lparents; getParents(lparents); for(const CBonusSystemNode *pname : lparents)
  26. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  27. #define FOREACH_RED_PARENT(pname) TNodes lparents; getRedParents(lparents); for(CBonusSystemNode *pname : lparents)
  28. #define BONUS_NAME(x) { #x, Bonus::x },
  29. const std::map<std::string, Bonus::BonusType> bonusNameMap = { BONUS_LIST };
  30. #undef BONUS_NAME
  31. #define BONUS_VALUE(x) { #x, Bonus::x },
  32. const std::map<std::string, Bonus::ValueType> bonusValueMap = { BONUS_VALUE_LIST };
  33. #undef BONUS_VALUE
  34. #define BONUS_SOURCE(x) { #x, Bonus::x },
  35. const std::map<std::string, Bonus::BonusSource> bonusSourceMap = { BONUS_SOURCE_LIST };
  36. #undef BONUS_SOURCE
  37. #define BONUS_ITEM(x) { #x, Bonus::x },
  38. const std::map<std::string, ui16> bonusDurationMap =
  39. {
  40. BONUS_ITEM(PERMANENT)
  41. BONUS_ITEM(ONE_BATTLE)
  42. BONUS_ITEM(ONE_DAY)
  43. BONUS_ITEM(ONE_WEEK)
  44. BONUS_ITEM(N_TURNS)
  45. BONUS_ITEM(N_DAYS)
  46. BONUS_ITEM(UNTIL_BEING_ATTACKED)
  47. BONUS_ITEM(UNTIL_ATTACK)
  48. BONUS_ITEM(STACK_GETS_TURN)
  49. BONUS_ITEM(COMMANDER_KILLED)
  50. { "UNITL_BEING_ATTACKED", Bonus::UNTIL_BEING_ATTACKED }//typo, but used in some mods
  51. };
  52. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  53. {
  54. BONUS_ITEM(NO_LIMIT)
  55. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  56. BONUS_ITEM(ONLY_MELEE_FIGHT)
  57. BONUS_ITEM(ONLY_ENEMY_ARMY)
  58. };
  59. const std::map<std::string, TLimiterPtr> bonusLimiterMap =
  60. {
  61. {"SHOOTER_ONLY", std::make_shared<HasAnotherBonusLimiter>(Bonus::SHOOTER)},
  62. {"DRAGON_NATURE", std::make_shared<HasAnotherBonusLimiter>(Bonus::DRAGON_NATURE)},
  63. {"IS_UNDEAD", std::make_shared<HasAnotherBonusLimiter>(Bonus::UNDEAD)},
  64. {"CREATURE_NATIVE_TERRAIN", std::make_shared<CreatureTerrainLimiter>()},
  65. {"CREATURE_FACTION", std::make_shared<CreatureFactionLimiter>()}
  66. };
  67. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  68. {
  69. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  70. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  71. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  72. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  73. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  74. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)},
  75. {"ALL_CREATURES", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::ALL_CREATURES)}
  76. }; //untested
  77. const std::map<std::string, TUpdaterPtr> bonusUpdaterMap =
  78. {
  79. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>()},
  80. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>()}
  81. };
  82. ///CBonusProxy
  83. CBonusProxy::CBonusProxy(const IBonusBearer * Target, CSelector Selector)
  84. : bonusListCachedLast(0),
  85. target(Target),
  86. selector(Selector),
  87. bonusList()
  88. {
  89. }
  90. CBonusProxy::CBonusProxy(const CBonusProxy & other)
  91. : bonusListCachedLast(other.bonusListCachedLast),
  92. target(other.target),
  93. selector(other.selector),
  94. bonusList(other.bonusList)
  95. {
  96. }
  97. CBonusProxy::CBonusProxy(CBonusProxy && other)
  98. : bonusListCachedLast(0),
  99. target(other.target),
  100. selector(),
  101. bonusList()
  102. {
  103. std::swap(bonusListCachedLast, other.bonusListCachedLast);
  104. std::swap(selector, other.selector);
  105. std::swap(bonusList, other.bonusList);
  106. }
  107. CBonusProxy & CBonusProxy::operator=(const CBonusProxy & other)
  108. {
  109. bonusListCachedLast = other.bonusListCachedLast;
  110. selector = other.selector;
  111. bonusList = other.bonusList;
  112. return *this;
  113. }
  114. CBonusProxy & CBonusProxy::operator=(CBonusProxy && other)
  115. {
  116. std::swap(bonusListCachedLast, other.bonusListCachedLast);
  117. std::swap(selector, other.selector);
  118. std::swap(bonusList, other.bonusList);
  119. return *this;
  120. }
  121. TConstBonusListPtr CBonusProxy::getBonusList() const
  122. {
  123. if(target->getTreeVersion() != bonusListCachedLast || !bonusList)
  124. {
  125. //TODO: support limiters
  126. bonusList = target->getAllBonuses(selector, Selector::all);
  127. bonusListCachedLast = target->getTreeVersion();
  128. }
  129. return bonusList;
  130. }
  131. const BonusList * CBonusProxy::operator->() const
  132. {
  133. return getBonusList().get();
  134. }
  135. CTotalsProxy::CTotalsProxy(const IBonusBearer * Target, CSelector Selector, int InitialValue)
  136. : CBonusProxy(Target, Selector),
  137. initialValue(InitialValue),
  138. meleeCachedLast(0),
  139. meleeValue(0),
  140. rangedCachedLast(0),
  141. rangedValue(0),
  142. value(0),
  143. valueCachedLast(0)
  144. {
  145. }
  146. CTotalsProxy::CTotalsProxy(const CTotalsProxy & other)
  147. : CBonusProxy(other),
  148. initialValue(other.initialValue),
  149. meleeCachedLast(other.meleeCachedLast),
  150. meleeValue(other.meleeValue),
  151. rangedCachedLast(other.rangedCachedLast),
  152. rangedValue(other.rangedValue)
  153. {
  154. }
  155. CTotalsProxy & CTotalsProxy::operator=(const CTotalsProxy & other)
  156. {
  157. CBonusProxy::operator=(other);
  158. initialValue = other.initialValue;
  159. meleeCachedLast = other.meleeCachedLast;
  160. meleeValue = other.meleeValue;
  161. rangedCachedLast = other.rangedCachedLast;
  162. rangedValue = other.rangedValue;
  163. value = other.value;
  164. valueCachedLast = other.valueCachedLast;
  165. return *this;
  166. }
  167. int CTotalsProxy::getValue() const
  168. {
  169. const auto treeVersion = target->getTreeVersion();
  170. if(treeVersion != valueCachedLast)
  171. {
  172. auto bonuses = getBonusList();
  173. value = initialValue + bonuses->totalValue();
  174. valueCachedLast = treeVersion;
  175. }
  176. return value;
  177. }
  178. int CTotalsProxy::getValueAndList(TConstBonusListPtr & outBonusList) const
  179. {
  180. const auto treeVersion = target->getTreeVersion();
  181. outBonusList = getBonusList();
  182. if(treeVersion != valueCachedLast)
  183. {
  184. value = initialValue + outBonusList->totalValue();
  185. valueCachedLast = treeVersion;
  186. }
  187. return value;
  188. }
  189. int CTotalsProxy::getMeleeValue() const
  190. {
  191. static const auto limit = Selector::effectRange()(Bonus::NO_LIMIT).Or(Selector::effectRange()(Bonus::ONLY_MELEE_FIGHT));
  192. const auto treeVersion = target->getTreeVersion();
  193. if(treeVersion != meleeCachedLast)
  194. {
  195. auto bonuses = target->getBonuses(selector, limit);
  196. meleeValue = initialValue + bonuses->totalValue();
  197. meleeCachedLast = treeVersion;
  198. }
  199. return meleeValue;
  200. }
  201. int CTotalsProxy::getRangedValue() const
  202. {
  203. static const auto limit = Selector::effectRange()(Bonus::NO_LIMIT).Or(Selector::effectRange()(Bonus::ONLY_DISTANCE_FIGHT));
  204. const auto treeVersion = target->getTreeVersion();
  205. if(treeVersion != rangedCachedLast)
  206. {
  207. auto bonuses = target->getBonuses(selector, limit);
  208. rangedValue = initialValue + bonuses->totalValue();
  209. rangedCachedLast = treeVersion;
  210. }
  211. return rangedValue;
  212. }
  213. ///CCheckProxy
  214. CCheckProxy::CCheckProxy(const IBonusBearer * Target, CSelector Selector)
  215. : target(Target),
  216. selector(Selector),
  217. cachedLast(0),
  218. hasBonus(false)
  219. {
  220. }
  221. CCheckProxy::CCheckProxy(const CCheckProxy & other)
  222. : target(other.target),
  223. selector(other.selector),
  224. cachedLast(other.cachedLast),
  225. hasBonus(other.hasBonus)
  226. {
  227. }
  228. bool CCheckProxy::getHasBonus() const
  229. {
  230. const auto treeVersion = target->getTreeVersion();
  231. if(treeVersion != cachedLast)
  232. {
  233. hasBonus = target->hasBonus(selector);
  234. cachedLast = treeVersion;
  235. }
  236. return hasBonus;
  237. }
  238. CAddInfo::CAddInfo()
  239. {
  240. }
  241. CAddInfo::CAddInfo(si32 value)
  242. {
  243. if(value != CAddInfo::NONE)
  244. push_back(value);
  245. }
  246. bool CAddInfo::operator==(si32 value) const
  247. {
  248. switch(size())
  249. {
  250. case 0:
  251. return value == CAddInfo::NONE;
  252. case 1:
  253. return operator[](0) == value;
  254. default:
  255. return false;
  256. }
  257. }
  258. bool CAddInfo::operator!=(si32 value) const
  259. {
  260. return !operator==(value);
  261. }
  262. si32 & CAddInfo::operator[](size_type pos)
  263. {
  264. if(pos >= size())
  265. resize(pos + 1, CAddInfo::NONE);
  266. return vector::operator[](pos);
  267. }
  268. si32 CAddInfo::operator[](size_type pos) const
  269. {
  270. return pos < size() ? vector::operator[](pos) : CAddInfo::NONE;
  271. }
  272. std::string CAddInfo::toString() const
  273. {
  274. return toJsonNode().toJson(true);
  275. }
  276. JsonNode CAddInfo::toJsonNode() const
  277. {
  278. if(size() < 2)
  279. {
  280. return JsonUtils::intNode(operator[](0));
  281. }
  282. else
  283. {
  284. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  285. for(si32 value : *this)
  286. node.Vector().push_back(JsonUtils::intNode(value));
  287. return node;
  288. }
  289. }
  290. std::atomic<int32_t> CBonusSystemNode::treeChanged(1);
  291. const bool CBonusSystemNode::cachingEnabled = true;
  292. BonusList::BonusList(bool BelongsToTree) : belongsToTree(BelongsToTree)
  293. {
  294. }
  295. BonusList::BonusList(const BonusList &bonusList)
  296. {
  297. bonuses.resize(bonusList.size());
  298. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  299. belongsToTree = false;
  300. }
  301. BonusList::BonusList(BonusList&& other):
  302. belongsToTree(false)
  303. {
  304. std::swap(belongsToTree, other.belongsToTree);
  305. std::swap(bonuses, other.bonuses);
  306. }
  307. BonusList& BonusList::operator=(const BonusList &bonusList)
  308. {
  309. bonuses.resize(bonusList.size());
  310. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  311. belongsToTree = false;
  312. return *this;
  313. }
  314. void BonusList::changed()
  315. {
  316. if(belongsToTree)
  317. CBonusSystemNode::treeHasChanged();
  318. }
  319. void BonusList::stackBonuses()
  320. {
  321. boost::sort(bonuses, [](std::shared_ptr<Bonus> b1, std::shared_ptr<Bonus> b2) -> bool
  322. {
  323. if(b1 == b2)
  324. return false;
  325. #define COMPARE_ATT(ATT) if(b1->ATT != b2->ATT) return b1->ATT < b2->ATT
  326. COMPARE_ATT(stacking);
  327. COMPARE_ATT(type);
  328. COMPARE_ATT(subtype);
  329. COMPARE_ATT(valType);
  330. #undef COMPARE_ATT
  331. return b1->val > b2->val;
  332. });
  333. // remove non-stacking
  334. size_t next = 1;
  335. while(next < bonuses.size())
  336. {
  337. bool remove;
  338. std::shared_ptr<Bonus> last = bonuses[next-1];
  339. std::shared_ptr<Bonus> current = bonuses[next];
  340. if(current->stacking.empty())
  341. remove = current == last;
  342. else if(current->stacking == "ALWAYS")
  343. remove = false;
  344. else
  345. remove = current->stacking == last->stacking
  346. && current->type == last->type
  347. && current->subtype == last->subtype
  348. && current->valType == last->valType;
  349. if(remove)
  350. bonuses.erase(bonuses.begin() + next);
  351. else
  352. next++;
  353. }
  354. }
  355. int BonusList::totalValue() const
  356. {
  357. int base = 0;
  358. int percentToBase = 0;
  359. int percentToAll = 0;
  360. int additive = 0;
  361. int indepMax = 0;
  362. bool hasIndepMax = false;
  363. int indepMin = 0;
  364. bool hasIndepMin = false;
  365. for(std::shared_ptr<Bonus> b : bonuses)
  366. {
  367. switch(b->valType)
  368. {
  369. case Bonus::BASE_NUMBER:
  370. base += b->val;
  371. break;
  372. case Bonus::PERCENT_TO_ALL:
  373. percentToAll += b->val;
  374. break;
  375. case Bonus::PERCENT_TO_BASE:
  376. percentToBase += b->val;
  377. break;
  378. case Bonus::ADDITIVE_VALUE:
  379. additive += b->val;
  380. break;
  381. case Bonus::INDEPENDENT_MAX:
  382. if (!hasIndepMax)
  383. {
  384. indepMax = b->val;
  385. hasIndepMax = true;
  386. }
  387. else
  388. {
  389. vstd::amax(indepMax, b->val);
  390. }
  391. break;
  392. case Bonus::INDEPENDENT_MIN:
  393. if (!hasIndepMin)
  394. {
  395. indepMin = b->val;
  396. hasIndepMin = true;
  397. }
  398. else
  399. {
  400. vstd::amin(indepMin, b->val);
  401. }
  402. break;
  403. }
  404. }
  405. int modifiedBase = base + (base * percentToBase) / 100;
  406. modifiedBase += additive;
  407. int valFirst = (modifiedBase * (100 + percentToAll)) / 100;
  408. if(hasIndepMin && hasIndepMax)
  409. assert(indepMin < indepMax);
  410. const int notIndepBonuses = (int)boost::count_if(bonuses, [](const std::shared_ptr<Bonus>& b)
  411. {
  412. return b->valType != Bonus::INDEPENDENT_MAX && b->valType != Bonus::INDEPENDENT_MIN;
  413. });
  414. if (hasIndepMax)
  415. {
  416. if(notIndepBonuses)
  417. vstd::amax(valFirst, indepMax);
  418. else
  419. valFirst = indepMax;
  420. }
  421. if (hasIndepMin)
  422. {
  423. if(notIndepBonuses)
  424. vstd::amin(valFirst, indepMin);
  425. else
  426. valFirst = indepMin;
  427. }
  428. return valFirst;
  429. }
  430. std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &select)
  431. {
  432. for (auto & b : bonuses)
  433. {
  434. if(select(b.get()))
  435. return b;
  436. }
  437. return nullptr;
  438. }
  439. std::shared_ptr<const Bonus> BonusList::getFirst(const CSelector &selector) const
  440. {
  441. for (auto & b : bonuses)
  442. {
  443. if(selector(b.get()))
  444. return b;
  445. }
  446. return nullptr;
  447. }
  448. void BonusList::getBonuses(BonusList & out, const CSelector &selector) const
  449. {
  450. getBonuses(out, selector, nullptr);
  451. }
  452. void BonusList::getBonuses(BonusList & out, const CSelector &selector, const CSelector &limit) const
  453. {
  454. for (auto & b : bonuses)
  455. {
  456. //add matching bonuses that matches limit predicate or have NO_LIMIT if no given predicate
  457. if(selector(b.get()) && ((!limit && b->effectRange == Bonus::NO_LIMIT) || ((bool)limit && limit(b.get()))))
  458. out.push_back(b);
  459. }
  460. }
  461. void BonusList::getAllBonuses(BonusList &out) const
  462. {
  463. for(auto & b : bonuses)
  464. out.push_back(b);
  465. }
  466. int BonusList::valOfBonuses(const CSelector &select) const
  467. {
  468. BonusList ret;
  469. CSelector limit = nullptr;
  470. getBonuses(ret, select, limit);
  471. return ret.totalValue();
  472. }
  473. JsonNode BonusList::toJsonNode() const
  474. {
  475. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  476. for(std::shared_ptr<Bonus> b : bonuses)
  477. node.Vector().push_back(b->toJsonNode());
  478. return node;
  479. }
  480. void BonusList::push_back(std::shared_ptr<Bonus> x)
  481. {
  482. bonuses.push_back(x);
  483. changed();
  484. }
  485. BonusList::TInternalContainer::iterator BonusList::erase(const int position)
  486. {
  487. changed();
  488. return bonuses.erase(bonuses.begin() + position);
  489. }
  490. void BonusList::clear()
  491. {
  492. bonuses.clear();
  493. changed();
  494. }
  495. std::vector<BonusList*>::size_type BonusList::operator-=(std::shared_ptr<Bonus> const &i)
  496. {
  497. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  498. if(itr == bonuses.end())
  499. return false;
  500. bonuses.erase(itr);
  501. changed();
  502. return true;
  503. }
  504. void BonusList::resize(BonusList::TInternalContainer::size_type sz, std::shared_ptr<Bonus> c )
  505. {
  506. bonuses.resize(sz, c);
  507. changed();
  508. }
  509. void BonusList::insert(BonusList::TInternalContainer::iterator position, BonusList::TInternalContainer::size_type n, std::shared_ptr<Bonus> const &x)
  510. {
  511. bonuses.insert(position, n, x);
  512. changed();
  513. }
  514. CSelector IBonusBearer::anaffectedByMoraleSelector
  515. = Selector::type()(Bonus::NON_LIVING)
  516. .Or(Selector::type()(Bonus::UNDEAD))
  517. .Or(Selector::type()(Bonus::NO_MORALE))
  518. .Or(Selector::type()(Bonus::SIEGE_WEAPON));
  519. CSelector IBonusBearer::moraleSelector = Selector::type()(Bonus::MORALE);
  520. CSelector IBonusBearer::luckSelector = Selector::type()(Bonus::LUCK);
  521. CSelector IBonusBearer::selfMoraleSelector = Selector::type()(Bonus::SELF_MORALE);
  522. CSelector IBonusBearer::selfLuckSelector = Selector::type()(Bonus::SELF_LUCK);
  523. IBonusBearer::IBonusBearer()
  524. :anaffectedByMorale(this, anaffectedByMoraleSelector),
  525. moraleValue(this, moraleSelector, 0),
  526. luckValue(this, luckSelector, 0),
  527. selfMorale(this, selfMoraleSelector),
  528. selfLuck(this, selfLuckSelector)
  529. {
  530. }
  531. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  532. {
  533. return valOfBonuses(Selector::type()(type).And(selector));
  534. }
  535. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype) const
  536. {
  537. boost::format fmt("type_%ds_%d");
  538. fmt % (int)type % subtype;
  539. CSelector s = Selector::type()(type);
  540. if(subtype != -1)
  541. s = s.And(Selector::subtype()(subtype));
  542. return valOfBonuses(s, fmt.str());
  543. }
  544. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  545. {
  546. CSelector limit = nullptr;
  547. TConstBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  548. return hlp->totalValue();
  549. }
  550. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  551. {
  552. return getBonuses(selector, cachingStr)->size() > 0;
  553. }
  554. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  555. {
  556. return getBonuses(selector, limit, cachingStr)->size() > 0;
  557. }
  558. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  559. {
  560. boost::format fmt("type_%ds_%d");
  561. fmt % (int)type % subtype;
  562. CSelector s = Selector::type()(type);
  563. if(subtype != -1)
  564. s = s.And(Selector::subtype()(subtype));
  565. return hasBonus(s, fmt.str());
  566. }
  567. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  568. {
  569. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  570. }
  571. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  572. {
  573. return getAllBonuses(selector, limit, nullptr, cachingStr);
  574. }
  575. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  576. {
  577. boost::format fmt("source_%did_%d");
  578. fmt % (int)source % sourceID;
  579. return hasBonus(Selector::source(source,sourceID), fmt.str());
  580. }
  581. int IBonusBearer::MoraleVal() const
  582. {
  583. if(anaffectedByMorale.getHasBonus())
  584. return 0;
  585. int ret = moraleValue.getValue();
  586. if(selfMorale.getHasBonus()) //eg. minotaur
  587. vstd::amax(ret, +1);
  588. return vstd::abetween(ret, -3, +3);
  589. }
  590. int IBonusBearer::LuckVal() const
  591. {
  592. if(hasBonusOfType(Bonus::NO_LUCK))
  593. return 0;
  594. int ret = luckValue.getValue();
  595. if(selfLuck.getHasBonus()) //eg. halfling
  596. vstd::amax(ret, +1);
  597. return vstd::abetween(ret, -3, +3);
  598. }
  599. int IBonusBearer::MoraleValAndBonusList(TConstBonusListPtr & bonusList) const
  600. {
  601. if(anaffectedByMorale.getHasBonus())
  602. {
  603. if(!bonusList->empty())
  604. bonusList = std::make_shared<const BonusList>();
  605. return 0;
  606. }
  607. int ret = moraleValue.getValueAndList(bonusList);
  608. if(selfMorale.getHasBonus()) //eg. minotaur
  609. vstd::amax(ret, +1);
  610. return vstd::abetween(ret, -3, +3);
  611. }
  612. int IBonusBearer::LuckValAndBonusList(TConstBonusListPtr & bonusList) const
  613. {
  614. if(hasBonusOfType(Bonus::NO_LUCK))
  615. {
  616. if(!bonusList->empty())
  617. bonusList = std::make_shared<const BonusList>();
  618. return 0;
  619. }
  620. int ret = luckValue.getValueAndList(bonusList);
  621. if(selfLuck.getHasBonus()) //eg. halfling
  622. vstd::amax(ret, +1);
  623. return vstd::abetween(ret, -3, +3);
  624. }
  625. ui32 IBonusBearer::MaxHealth() const
  626. {
  627. const std::string cachingStr = "type_STACK_HEALTH";
  628. static const auto selector = Selector::type()(Bonus::STACK_HEALTH);
  629. auto value = valOfBonuses(selector, cachingStr);
  630. return std::max(1, value); //never 0
  631. }
  632. int IBonusBearer::getAttack(bool ranged) const
  633. {
  634. const std::string cachingStr = "type_PRIMARY_SKILLs_ATTACK";
  635. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  636. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  637. }
  638. int IBonusBearer::getDefence(bool ranged) const
  639. {
  640. const std::string cachingStr = "type_PRIMARY_SKILLs_DEFENSE";
  641. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  642. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  643. }
  644. int IBonusBearer::getMinDamage(bool ranged) const
  645. {
  646. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_1";
  647. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1));
  648. return valOfBonuses(selector, cachingStr);
  649. }
  650. int IBonusBearer::getMaxDamage(bool ranged) const
  651. {
  652. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_2";
  653. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2));
  654. return valOfBonuses(selector, cachingStr);
  655. }
  656. si32 IBonusBearer::manaLimit() const
  657. {
  658. return si32(getPrimSkillLevel(PrimarySkill::KNOWLEDGE)
  659. * (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::INTELLIGENCE))
  660. / 10.0);
  661. }
  662. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  663. {
  664. static const CSelector selectorAllSkills = Selector::type()(Bonus::PRIMARY_SKILL);
  665. static const std::string keyAllSkills = "type_PRIMARY_SKILL";
  666. auto allSkills = getBonuses(selectorAllSkills, keyAllSkills);
  667. int ret = allSkills->valOfBonuses(Selector::subtype()(id));
  668. vstd::amax(ret, id/2); //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  669. return ret;
  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 std::string& CBonusSystemNode::getDescription() const
  1126. {
  1127. return description;
  1128. }
  1129. void CBonusSystemNode::setDescription(const std::string &description)
  1130. {
  1131. this->description = description;
  1132. }
  1133. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  1134. {
  1135. assert(&allBonuses != &out); //todo should it work in-place?
  1136. BonusList undecided = allBonuses,
  1137. &accepted = out;
  1138. while(true)
  1139. {
  1140. int undecidedCount = static_cast<int>(undecided.size());
  1141. for(int i = 0; i < undecided.size(); i++)
  1142. {
  1143. auto b = undecided[i];
  1144. BonusLimitationContext context = {b, *this, out, undecided};
  1145. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  1146. if(decision == ILimiter::DISCARD)
  1147. {
  1148. undecided.erase(i);
  1149. i--; continue;
  1150. }
  1151. else if(decision == ILimiter::ACCEPT)
  1152. {
  1153. accepted.push_back(b);
  1154. undecided.erase(i);
  1155. i--; continue;
  1156. }
  1157. else
  1158. assert(decision == ILimiter::NOT_SURE);
  1159. }
  1160. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  1161. return;
  1162. }
  1163. }
  1164. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  1165. {
  1166. auto ret = std::make_shared<BonusList>();
  1167. limitBonuses(allBonuses, *ret);
  1168. return ret;
  1169. }
  1170. void CBonusSystemNode::treeHasChanged()
  1171. {
  1172. treeChanged++;
  1173. }
  1174. int64_t CBonusSystemNode::getTreeVersion() const
  1175. {
  1176. int64_t ret = treeChanged;
  1177. return ret << 32;
  1178. }
  1179. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1180. {
  1181. if(obj)
  1182. return obj->valOfBonuses(type, subtype);
  1183. return 0;
  1184. }
  1185. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1186. {
  1187. if(obj)
  1188. return obj->hasBonusOfType(type, subtype);
  1189. return false;
  1190. }
  1191. std::string Bonus::Description() const
  1192. {
  1193. std::ostringstream str;
  1194. if(description.empty())
  1195. {
  1196. if(stacking.empty() || stacking == "ALWAYS")
  1197. {
  1198. switch(source)
  1199. {
  1200. case ARTIFACT:
  1201. str << VLC->arth->artifacts[sid]->Name();
  1202. break;
  1203. case SPELL_EFFECT:
  1204. str << SpellID(sid).toSpell()->name;
  1205. break;
  1206. case CREATURE_ABILITY:
  1207. str << VLC->creh->creatures[sid]->namePl;
  1208. break;
  1209. case SECONDARY_SKILL:
  1210. str << VLC->skillh->skillName(sid);
  1211. break;
  1212. case HERO_SPECIAL:
  1213. str << VLC->heroh->heroes[sid]->name;
  1214. break;
  1215. default:
  1216. //todo: handle all possible sources
  1217. str << "Unknown";
  1218. break;
  1219. }
  1220. }
  1221. else
  1222. str << stacking;
  1223. }
  1224. else
  1225. {
  1226. str << description;
  1227. }
  1228. if(val != 0)
  1229. str << " " << std::showpos << val;
  1230. return str.str();
  1231. }
  1232. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  1233. {
  1234. switch(type)
  1235. {
  1236. case Bonus::PRIMARY_SKILL:
  1237. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  1238. case Bonus::SECONDARY_SKILL_PREMY:
  1239. return JsonUtils::stringNode(CSkillHandler::encodeSkillWithType(subtype));
  1240. case Bonus::SPECIAL_SPELL_LEV:
  1241. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1242. case Bonus::SPECIAL_BLESS_DAMAGE:
  1243. case Bonus::MAXED_SPELL:
  1244. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1245. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1246. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1247. return JsonUtils::stringNode("spell." + (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier);
  1248. case Bonus::IMPROVED_NECROMANCY:
  1249. case Bonus::SPECIAL_UPGRADE:
  1250. return JsonUtils::stringNode("creature." + CreatureID::encode(subtype));
  1251. case Bonus::GENERATE_RESOURCE:
  1252. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1253. default:
  1254. return JsonUtils::intNode(subtype);
  1255. }
  1256. }
  1257. JsonNode additionalInfoToJson(Bonus::BonusType type, CAddInfo addInfo)
  1258. {
  1259. switch(type)
  1260. {
  1261. case Bonus::SPECIAL_UPGRADE:
  1262. return JsonUtils::stringNode("creature." + CreatureID::encode(addInfo[0]));
  1263. default:
  1264. return addInfo.toJsonNode();
  1265. }
  1266. }
  1267. JsonNode durationToJson(ui16 duration)
  1268. {
  1269. std::vector<std::string> durationNames;
  1270. for(ui16 durBit = 1; durBit; durBit = durBit << 1)
  1271. {
  1272. if(duration & durBit)
  1273. durationNames.push_back(vstd::findKey(bonusDurationMap, durBit));
  1274. }
  1275. if(durationNames.size() == 1)
  1276. {
  1277. return JsonUtils::stringNode(durationNames[0]);
  1278. }
  1279. else
  1280. {
  1281. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  1282. for(std::string dur : durationNames)
  1283. node.Vector().push_back(JsonUtils::stringNode(dur));
  1284. return node;
  1285. }
  1286. }
  1287. JsonNode Bonus::toJsonNode() const
  1288. {
  1289. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1290. // only add values that might reasonably be found in config files
  1291. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1292. if(subtype != -1)
  1293. root["subtype"] = subtypeToJson(type, subtype);
  1294. if(additionalInfo != CAddInfo::NONE)
  1295. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1296. if(val != 0)
  1297. root["val"].Integer() = val;
  1298. if(valType != ADDITIVE_VALUE)
  1299. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1300. if(stacking != "")
  1301. root["stacking"].String() = stacking;
  1302. if(description != "")
  1303. root["description"].String() = description;
  1304. if(effectRange != NO_LIMIT)
  1305. root["effectRange"].String() = vstd::findKey(bonusLimitEffect, effectRange);
  1306. if(duration != PERMANENT)
  1307. root["duration"] = durationToJson(duration);
  1308. if(turnsRemain)
  1309. root["turns"].Integer() = turnsRemain;
  1310. if(limiter)
  1311. root["limiters"] = limiter->toJsonNode();
  1312. if(updater)
  1313. root["updater"] = updater->toJsonNode();
  1314. if(propagator)
  1315. root["propagator"].String() = vstd::findKey(bonusPropagatorMap, propagator);
  1316. return root;
  1317. }
  1318. std::string Bonus::nameForBonus() const
  1319. {
  1320. switch(type)
  1321. {
  1322. case Bonus::PRIMARY_SKILL:
  1323. return PrimarySkill::names[subtype];
  1324. case Bonus::SECONDARY_SKILL_PREMY:
  1325. return CSkillHandler::encodeSkill(subtype);
  1326. case Bonus::SPECIAL_SPELL_LEV:
  1327. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1328. case Bonus::SPECIAL_BLESS_DAMAGE:
  1329. case Bonus::MAXED_SPELL:
  1330. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1331. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1332. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1333. return (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier;
  1334. case Bonus::SPECIAL_UPGRADE:
  1335. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo[0]);
  1336. case Bonus::GENERATE_RESOURCE:
  1337. return GameConstants::RESOURCE_NAMES[subtype];
  1338. case Bonus::STACKS_SPEED:
  1339. return "speed";
  1340. default:
  1341. return vstd::findKey(bonusNameMap, type);
  1342. }
  1343. }
  1344. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype)
  1345. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  1346. {
  1347. turnsRemain = 0;
  1348. valType = ADDITIVE_VALUE;
  1349. effectRange = NO_LIMIT;
  1350. boost::algorithm::trim(description);
  1351. }
  1352. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType)
  1353. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  1354. {
  1355. turnsRemain = 0;
  1356. effectRange = NO_LIMIT;
  1357. }
  1358. Bonus::Bonus()
  1359. {
  1360. duration = PERMANENT;
  1361. turnsRemain = 0;
  1362. type = NONE;
  1363. subtype = -1;
  1364. valType = ADDITIVE_VALUE;
  1365. effectRange = NO_LIMIT;
  1366. val = 0;
  1367. source = OTHER;
  1368. sid = 0;
  1369. }
  1370. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  1371. {
  1372. propagator = Propagator;
  1373. return this->shared_from_this();
  1374. }
  1375. namespace Selector
  1376. {
  1377. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type()
  1378. {
  1379. static CSelectFieldEqual<Bonus::BonusType> stype(&Bonus::type);
  1380. return stype;
  1381. }
  1382. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype()
  1383. {
  1384. static CSelectFieldEqual<TBonusSubtype> ssubtype(&Bonus::subtype);
  1385. return ssubtype;
  1386. }
  1387. DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info()
  1388. {
  1389. static CSelectFieldEqual<CAddInfo> sinfo(&Bonus::additionalInfo);
  1390. return sinfo;
  1391. }
  1392. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType()
  1393. {
  1394. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::source);
  1395. return ssourceType;
  1396. }
  1397. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange()
  1398. {
  1399. static CSelectFieldEqual<Bonus::LimitEffect> seffectRange(&Bonus::effectRange);
  1400. return seffectRange;
  1401. }
  1402. DLL_LINKAGE CWillLastTurns turns;
  1403. DLL_LINKAGE CWillLastDays days;
  1404. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1405. {
  1406. return type()(Type).And(subtype()(Subtype));
  1407. }
  1408. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, CAddInfo info)
  1409. {
  1410. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1411. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1412. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1413. }
  1414. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1415. {
  1416. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1417. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1418. }
  1419. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1420. {
  1421. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1422. }
  1423. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1424. {
  1425. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1426. }
  1427. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1428. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1429. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1430. {
  1431. Bonus dummy;
  1432. dummy.type = type;
  1433. return sel(&dummy);
  1434. }
  1435. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1436. {
  1437. Bonus dummy;
  1438. dummy.type = type;
  1439. dummy.subtype = subtype;
  1440. return sel(&dummy);
  1441. }
  1442. }
  1443. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  1444. {
  1445. switch(node->getNodeType())
  1446. {
  1447. case CBonusSystemNode::STACK_BATTLE:
  1448. return static_cast<const CStack*>(node);
  1449. default:
  1450. return nullptr;
  1451. }
  1452. }
  1453. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  1454. {
  1455. switch(node->getNodeType())
  1456. {
  1457. case CBonusSystemNode::STACK_INSTANCE:
  1458. return (static_cast<const CStackInstance *>(node));
  1459. case CBonusSystemNode::STACK_BATTLE:
  1460. return (static_cast<const CStack*>(node))->base;
  1461. default:
  1462. return nullptr;
  1463. }
  1464. }
  1465. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1466. {
  1467. switch(node->getNodeType())
  1468. {
  1469. case CBonusSystemNode::CREATURE:
  1470. return (static_cast<const CCreature *>(node));
  1471. case CBonusSystemNode::STACK_BATTLE:
  1472. return (static_cast<const CStack*>(node))->type;
  1473. default:
  1474. const CStackInstance * csi = retrieveStackInstance(node);
  1475. if(csi)
  1476. return csi->type;
  1477. return nullptr;
  1478. }
  1479. }
  1480. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1481. {
  1482. for (ui32 i = 0; i < bonusList.size(); i++)
  1483. {
  1484. auto b = bonusList[i];
  1485. out << "Bonus " << i << "\n" << *b << std::endl;
  1486. }
  1487. return out;
  1488. }
  1489. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1490. {
  1491. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1492. if(i->second == bonus.type)
  1493. out << "\tType: " << i->first << " \t";
  1494. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1495. printField(val);
  1496. printField(subtype);
  1497. printField(duration);
  1498. printField(source);
  1499. printField(sid);
  1500. if(bonus.additionalInfo != CAddInfo::NONE)
  1501. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1502. printField(turnsRemain);
  1503. printField(valType);
  1504. if(!bonus.stacking.empty())
  1505. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1506. printField(effectRange);
  1507. #undef printField
  1508. if(bonus.limiter)
  1509. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1510. if(bonus.updater)
  1511. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1512. return out;
  1513. }
  1514. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1515. {
  1516. if (limiter)
  1517. {
  1518. //If we already have limiter list, retrieve it
  1519. auto limiterList = std::dynamic_pointer_cast<AllOfLimiter>(limiter);
  1520. if(!limiterList)
  1521. {
  1522. //Create a new limiter list with old limiter and the new one will be pushed later
  1523. limiterList = std::make_shared<AllOfLimiter>();
  1524. limiterList->add(limiter);
  1525. limiter = limiterList;
  1526. }
  1527. limiterList->add(Limiter);
  1528. }
  1529. else
  1530. {
  1531. limiter = Limiter;
  1532. }
  1533. return this->shared_from_this();
  1534. }
  1535. ILimiter::~ILimiter()
  1536. {
  1537. }
  1538. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1539. {
  1540. return false;
  1541. }
  1542. std::string ILimiter::toString() const
  1543. {
  1544. return typeid(*this).name();
  1545. }
  1546. JsonNode ILimiter::toJsonNode() const
  1547. {
  1548. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1549. root["type"].String() = toString();
  1550. return root;
  1551. }
  1552. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1553. {
  1554. const CCreature *c = retrieveCreature(&context.node);
  1555. if(!c)
  1556. return true;
  1557. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1558. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1559. }
  1560. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature &Creature, bool IncludeUpgrades)
  1561. :creature(&Creature), includeUpgrades(IncludeUpgrades)
  1562. {
  1563. }
  1564. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1565. {
  1566. creature = nullptr;
  1567. includeUpgrades = false;
  1568. }
  1569. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1570. {
  1571. creature = VLC->creh->creatures[id];
  1572. }
  1573. std::string CCreatureTypeLimiter::toString() const
  1574. {
  1575. boost::format fmt("CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)");
  1576. fmt % creature->identifier % (includeUpgrades ? "true" : "false");
  1577. return fmt.str();
  1578. }
  1579. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1580. {
  1581. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1582. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1583. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->identifier));
  1584. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1585. return root;
  1586. }
  1587. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1588. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1589. {
  1590. }
  1591. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1592. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1593. {
  1594. }
  1595. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1596. {
  1597. CSelector mySelector = isSubtypeRelevant
  1598. ? Selector::typeSubtype(type, subtype)
  1599. : Selector::type()(type);
  1600. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1601. if(context.alreadyAccepted.getFirst(mySelector))
  1602. return ACCEPT;
  1603. //if there are no matching bonuses pending, we can (and must) reject right away
  1604. if(!context.stillUndecided.getFirst(mySelector))
  1605. return DISCARD;
  1606. //do not accept for now but it may change if more bonuses gets included
  1607. return NOT_SURE;
  1608. }
  1609. std::string HasAnotherBonusLimiter::toString() const
  1610. {
  1611. std::string typeName = vstd::findKey(bonusNameMap, type);
  1612. if(isSubtypeRelevant)
  1613. {
  1614. boost::format fmt("HasAnotherBonusLimiter(type=%s, subtype=%d)");
  1615. fmt % typeName % subtype;
  1616. return fmt.str();
  1617. }
  1618. else
  1619. {
  1620. boost::format fmt("HasAnotherBonusLimiter(type=%s)");
  1621. fmt % typeName;
  1622. return fmt.str();
  1623. }
  1624. }
  1625. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  1626. {
  1627. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1628. std::string typeName = vstd::findKey(bonusNameMap, type);
  1629. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  1630. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  1631. if(isSubtypeRelevant)
  1632. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  1633. return root;
  1634. }
  1635. IPropagator::~IPropagator()
  1636. {
  1637. }
  1638. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1639. {
  1640. return false;
  1641. }
  1642. CBonusSystemNode::ENodeTypes IPropagator::getPropagatorType() const
  1643. {
  1644. return CBonusSystemNode::ENodeTypes::NONE;
  1645. }
  1646. CPropagatorNodeType::CPropagatorNodeType()
  1647. :nodeType(CBonusSystemNode::ENodeTypes::UNKNOWN)
  1648. {
  1649. }
  1650. CPropagatorNodeType::CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType)
  1651. : nodeType(NodeType)
  1652. {
  1653. }
  1654. CBonusSystemNode::ENodeTypes CPropagatorNodeType::getPropagatorType() const
  1655. {
  1656. return nodeType;
  1657. }
  1658. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1659. {
  1660. return nodeType == dest->getNodeType();
  1661. }
  1662. CreatureTerrainLimiter::CreatureTerrainLimiter(int TerrainType)
  1663. : terrainType(TerrainType)
  1664. {
  1665. }
  1666. CreatureTerrainLimiter::CreatureTerrainLimiter()
  1667. : terrainType(-1)
  1668. {
  1669. }
  1670. int CreatureTerrainLimiter::limit(const BonusLimitationContext &context) const
  1671. {
  1672. const CStack *stack = retrieveStackBattle(&context.node);
  1673. if(stack)
  1674. {
  1675. if(terrainType == -1)//terrainType not specified = native
  1676. return !stack->isOnNativeTerrain();
  1677. return !stack->isOnTerrain(terrainType);
  1678. }
  1679. return true;
  1680. //TODO neutral creatues
  1681. }
  1682. std::string CreatureTerrainLimiter::toString() const
  1683. {
  1684. boost::format fmt("CreatureTerrainLimiter(terrainType=%s)");
  1685. fmt % (terrainType >= 0 ? GameConstants::TERRAIN_NAMES[terrainType] : "native");
  1686. return fmt.str();
  1687. }
  1688. JsonNode CreatureTerrainLimiter::toJsonNode() const
  1689. {
  1690. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1691. root["type"].String() = "CREATURE_TERRAIN_LIMITER";
  1692. if(terrainType >= 0)
  1693. root["parameters"].Vector().push_back(JsonUtils::stringNode(GameConstants::TERRAIN_NAMES[terrainType]));
  1694. return root;
  1695. }
  1696. CreatureFactionLimiter::CreatureFactionLimiter(TFaction creatureFaction)
  1697. : faction(creatureFaction)
  1698. {
  1699. }
  1700. CreatureFactionLimiter::CreatureFactionLimiter()
  1701. : faction((TFaction)-1)
  1702. {
  1703. }
  1704. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1705. {
  1706. const CCreature *c = retrieveCreature(&context.node);
  1707. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1708. }
  1709. std::string CreatureFactionLimiter::toString() const
  1710. {
  1711. boost::format fmt("CreatureFactionLimiter(faction=%s)");
  1712. fmt % VLC->townh->factions[faction]->identifier;
  1713. return fmt.str();
  1714. }
  1715. JsonNode CreatureFactionLimiter::toJsonNode() const
  1716. {
  1717. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1718. root["type"].String() = "CREATURE_FACTION_LIMITER";
  1719. root["parameters"].Vector().push_back(JsonUtils::stringNode(VLC->townh->factions[faction]->identifier));
  1720. return root;
  1721. }
  1722. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1723. : alignment(-1)
  1724. {
  1725. }
  1726. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1727. : alignment(Alignment)
  1728. {
  1729. }
  1730. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1731. {
  1732. const CCreature *c = retrieveCreature(&context.node);
  1733. if(!c)
  1734. return true;
  1735. switch(alignment)
  1736. {
  1737. case EAlignment::GOOD:
  1738. return !c->isGood(); //if not good -> return true (drop bonus)
  1739. case EAlignment::NEUTRAL:
  1740. return c->isEvil() || c->isGood();
  1741. case EAlignment::EVIL:
  1742. return !c->isEvil();
  1743. default:
  1744. logBonus->warn("Warning: illegal alignment in limiter!");
  1745. return true;
  1746. }
  1747. }
  1748. std::string CreatureAlignmentLimiter::toString() const
  1749. {
  1750. boost::format fmt("CreatureAlignmentLimiter(alignment=%s)");
  1751. fmt % EAlignment::names[alignment];
  1752. return fmt.str();
  1753. }
  1754. JsonNode CreatureAlignmentLimiter::toJsonNode() const
  1755. {
  1756. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1757. root["type"].String() = "CREATURE_ALIGNMENT_LIMITER";
  1758. root["parameters"].Vector().push_back(JsonUtils::stringNode(EAlignment::names[alignment]));
  1759. return root;
  1760. }
  1761. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1762. :minRank(Min), maxRank(Max)
  1763. {
  1764. }
  1765. RankRangeLimiter::RankRangeLimiter()
  1766. {
  1767. minRank = maxRank = -1;
  1768. }
  1769. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1770. {
  1771. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1772. if(csi)
  1773. {
  1774. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1775. return true;
  1776. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1777. }
  1778. return true;
  1779. }
  1780. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1781. {
  1782. const CStack * s = retrieveStackBattle(&context.node);
  1783. if(s)
  1784. return s->owner != owner;
  1785. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1786. if(csi && csi->armyObj)
  1787. return csi->armyObj->tempOwner != owner;
  1788. return true;
  1789. }
  1790. StackOwnerLimiter::StackOwnerLimiter()
  1791. : owner(-1)
  1792. {
  1793. }
  1794. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1795. : owner(Owner)
  1796. {
  1797. }
  1798. // Aggregate/Boolean Limiters
  1799. void AggregateLimiter::add(TLimiterPtr limiter)
  1800. {
  1801. if(limiter)
  1802. limiters.push_back(limiter);
  1803. }
  1804. JsonNode AggregateLimiter::toJsonNode() const
  1805. {
  1806. JsonNode result(JsonNode::JsonType::DATA_VECTOR);
  1807. result.Vector().push_back(JsonUtils::stringNode(getAggregator()));
  1808. for(auto l : limiters)
  1809. result.Vector().push_back(l->toJsonNode());
  1810. return result;
  1811. }
  1812. const std::string AllOfLimiter::aggregator = "allOf";
  1813. const std::string & AllOfLimiter::getAggregator() const
  1814. {
  1815. return aggregator;
  1816. }
  1817. int AllOfLimiter::limit(const BonusLimitationContext & context) const
  1818. {
  1819. bool wasntSure = false;
  1820. for(auto limiter : limiters)
  1821. {
  1822. auto result = limiter->limit(context);
  1823. if(result == ILimiter::DISCARD)
  1824. return result;
  1825. if(result == ILimiter::NOT_SURE)
  1826. wasntSure = true;
  1827. }
  1828. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1829. }
  1830. const std::string AnyOfLimiter::aggregator = "anyOf";
  1831. const std::string & AnyOfLimiter::getAggregator() const
  1832. {
  1833. return aggregator;
  1834. }
  1835. int AnyOfLimiter::limit(const BonusLimitationContext & context) const
  1836. {
  1837. bool wasntSure = false;
  1838. for(auto limiter : limiters)
  1839. {
  1840. auto result = limiter->limit(context);
  1841. if(result == ILimiter::ACCEPT)
  1842. return result;
  1843. if(result == ILimiter::NOT_SURE)
  1844. wasntSure = true;
  1845. }
  1846. return wasntSure ? ILimiter::NOT_SURE : ILimiter::DISCARD;
  1847. }
  1848. const std::string NoneOfLimiter::aggregator = "noneOf";
  1849. const std::string & NoneOfLimiter::getAggregator() const
  1850. {
  1851. return aggregator;
  1852. }
  1853. int NoneOfLimiter::limit(const BonusLimitationContext & context) const
  1854. {
  1855. bool wasntSure = false;
  1856. for(auto limiter : limiters)
  1857. {
  1858. auto result = limiter->limit(context);
  1859. if(result == ILimiter::ACCEPT)
  1860. return ILimiter::DISCARD;
  1861. if(result == ILimiter::NOT_SURE)
  1862. wasntSure = true;
  1863. }
  1864. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1865. }
  1866. // Updaters
  1867. std::shared_ptr<Bonus> Bonus::addUpdater(TUpdaterPtr Updater)
  1868. {
  1869. updater = Updater;
  1870. return this->shared_from_this();
  1871. }
  1872. IUpdater::~IUpdater()
  1873. {
  1874. }
  1875. std::shared_ptr<Bonus> IUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1876. {
  1877. return b;
  1878. }
  1879. std::string IUpdater::toString() const
  1880. {
  1881. return typeid(*this).name();
  1882. }
  1883. JsonNode IUpdater::toJsonNode() const
  1884. {
  1885. return JsonNode(JsonNode::JsonType::DATA_NULL);
  1886. }
  1887. GrowsWithLevelUpdater::GrowsWithLevelUpdater() : valPer20(0), stepSize(1)
  1888. {
  1889. }
  1890. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  1891. {
  1892. }
  1893. std::shared_ptr<Bonus> GrowsWithLevelUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1894. {
  1895. if(context.getNodeType() == CBonusSystemNode::HERO)
  1896. {
  1897. int level = static_cast<const CGHeroInstance &>(context).level;
  1898. int steps = stepSize ? level / stepSize : level;
  1899. //rounding follows format for HMM3 creature specialty bonus
  1900. int newVal = (valPer20 * steps + 19) / 20;
  1901. //return copy of bonus with updated val
  1902. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1903. newBonus->val = newVal;
  1904. return newBonus;
  1905. }
  1906. return b;
  1907. }
  1908. std::string GrowsWithLevelUpdater::toString() const
  1909. {
  1910. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  1911. }
  1912. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  1913. {
  1914. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1915. root["type"].String() = "GROWS_WITH_LEVEL";
  1916. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  1917. if(stepSize > 1)
  1918. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  1919. return root;
  1920. }
  1921. TimesHeroLevelUpdater::TimesHeroLevelUpdater()
  1922. {
  1923. }
  1924. std::shared_ptr<Bonus> TimesHeroLevelUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1925. {
  1926. if(context.getNodeType() == CBonusSystemNode::HERO)
  1927. {
  1928. int level = static_cast<const CGHeroInstance &>(context).level;
  1929. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1930. newBonus->val *= level;
  1931. return newBonus;
  1932. }
  1933. return b;
  1934. }
  1935. std::string TimesHeroLevelUpdater::toString() const
  1936. {
  1937. return "TimesHeroLevelUpdater";
  1938. }
  1939. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  1940. {
  1941. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  1942. }
  1943. TimesStackLevelUpdater::TimesStackLevelUpdater()
  1944. {
  1945. }
  1946. std::shared_ptr<Bonus> TimesStackLevelUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1947. {
  1948. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  1949. {
  1950. int level = static_cast<const CStackInstance &>(context).getLevel();
  1951. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1952. newBonus->val *= level;
  1953. return newBonus;
  1954. }
  1955. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  1956. {
  1957. const CStack & stack = static_cast<const CStack &>(context);
  1958. //only update if stack doesn't have an instance (summons, war machines)
  1959. //otherwise we'd end up multiplying twice
  1960. if(stack.base == nullptr)
  1961. {
  1962. int level = stack.type->level;
  1963. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1964. newBonus->val *= level;
  1965. return newBonus;
  1966. }
  1967. }
  1968. return b;
  1969. }
  1970. std::string TimesStackLevelUpdater::toString() const
  1971. {
  1972. return "TimesStackLevelUpdater";
  1973. }
  1974. JsonNode TimesStackLevelUpdater::toJsonNode() const
  1975. {
  1976. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  1977. }