HeroBonus.cpp 53 KB

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