HeroBonus.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  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 "CGeneralTextHandler.h"
  18. #include "CSkillHandler.h"
  19. #include "CStack.h"
  20. #include "CArtHandler.h"
  21. #include "StringConstants.h"
  22. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  23. #define FOREACH_CPARENT(pname) TCNodes lparents; getParents(lparents); for(const CBonusSystemNode *pname : lparents)
  24. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  25. #define FOREACH_RED_PARENT(pname) TNodes lparents; getRedParents(lparents); for(CBonusSystemNode *pname : lparents)
  26. #define BONUS_NAME(x) { #x, Bonus::x },
  27. const std::map<std::string, Bonus::BonusType> bonusNameMap = { BONUS_LIST };
  28. #undef BONUS_NAME
  29. #define BONUS_VALUE(x) { #x, Bonus::x },
  30. const std::map<std::string, Bonus::ValueType> bonusValueMap = { BONUS_VALUE_LIST };
  31. #undef BONUS_VALUE
  32. #define BONUS_SOURCE(x) { #x, Bonus::x },
  33. const std::map<std::string, Bonus::BonusSource> bonusSourceMap = { BONUS_SOURCE_LIST };
  34. #undef BONUS_SOURCE
  35. #define BONUS_ITEM(x) { #x, Bonus::x },
  36. const std::map<std::string, ui16> bonusDurationMap =
  37. {
  38. BONUS_ITEM(PERMANENT)
  39. BONUS_ITEM(ONE_BATTLE)
  40. BONUS_ITEM(ONE_DAY)
  41. BONUS_ITEM(ONE_WEEK)
  42. BONUS_ITEM(N_TURNS)
  43. BONUS_ITEM(N_DAYS)
  44. BONUS_ITEM(UNTIL_BEING_ATTACKED)
  45. BONUS_ITEM(UNTIL_ATTACK)
  46. BONUS_ITEM(STACK_GETS_TURN)
  47. BONUS_ITEM(COMMANDER_KILLED)
  48. { "UNITL_BEING_ATTACKED", Bonus::UNTIL_BEING_ATTACKED }//typo, but used in some mods
  49. };
  50. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  51. {
  52. BONUS_ITEM(NO_LIMIT)
  53. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  54. BONUS_ITEM(ONLY_MELEE_FIGHT)
  55. BONUS_ITEM(ONLY_ENEMY_ARMY)
  56. };
  57. const std::map<std::string, TLimiterPtr> bonusLimiterMap =
  58. {
  59. {"SHOOTER_ONLY", std::make_shared<HasAnotherBonusLimiter>(Bonus::SHOOTER)},
  60. {"DRAGON_NATURE", std::make_shared<HasAnotherBonusLimiter>(Bonus::DRAGON_NATURE)},
  61. {"IS_UNDEAD", std::make_shared<HasAnotherBonusLimiter>(Bonus::UNDEAD)}
  62. };
  63. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  64. {
  65. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  66. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  67. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  68. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  69. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  70. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)}
  71. }; //untested
  72. ///CBonusProxy
  73. CBonusProxy::CBonusProxy(const IBonusBearer * Target, CSelector Selector)
  74. : cachedLast(0),
  75. target(Target),
  76. selector(Selector),
  77. data()
  78. {
  79. }
  80. CBonusProxy::CBonusProxy(const CBonusProxy & other)
  81. : cachedLast(other.cachedLast),
  82. target(other.target),
  83. selector(other.selector),
  84. data(other.data)
  85. {
  86. }
  87. CBonusProxy::CBonusProxy(CBonusProxy && other)
  88. : cachedLast(0),
  89. target(other.target),
  90. selector(),
  91. data()
  92. {
  93. std::swap(cachedLast, other.cachedLast);
  94. std::swap(selector, other.selector);
  95. std::swap(data, other.data);
  96. }
  97. CBonusProxy & CBonusProxy::operator=(const CBonusProxy & other)
  98. {
  99. cachedLast = other.cachedLast;
  100. selector = other.selector;
  101. data = other.data;
  102. return *this;
  103. }
  104. CBonusProxy & CBonusProxy::operator=(CBonusProxy && other)
  105. {
  106. std::swap(cachedLast, other.cachedLast);
  107. std::swap(selector, other.selector);
  108. std::swap(data, other.data);
  109. return *this;
  110. }
  111. TBonusListPtr CBonusProxy::get() const
  112. {
  113. if(target->getTreeVersion() != cachedLast || !data)
  114. {
  115. //TODO: support limiters
  116. data = target->getAllBonuses(selector, Selector::all);
  117. data->eliminateDuplicates();
  118. cachedLast = target->getTreeVersion();
  119. }
  120. return data;
  121. }
  122. const BonusList * CBonusProxy::operator->() const
  123. {
  124. return get().get();
  125. }
  126. std::atomic<int32_t> CBonusSystemNode::treeChanged(1);
  127. const bool CBonusSystemNode::cachingEnabled = true;
  128. BonusList::BonusList(bool BelongsToTree) : belongsToTree(BelongsToTree)
  129. {
  130. }
  131. BonusList::BonusList(const BonusList &bonusList)
  132. {
  133. bonuses.resize(bonusList.size());
  134. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  135. belongsToTree = false;
  136. }
  137. BonusList::BonusList(BonusList&& other):
  138. belongsToTree(false)
  139. {
  140. std::swap(belongsToTree, other.belongsToTree);
  141. std::swap(bonuses, other.bonuses);
  142. }
  143. BonusList& BonusList::operator=(const BonusList &bonusList)
  144. {
  145. bonuses.resize(bonusList.size());
  146. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  147. belongsToTree = false;
  148. return *this;
  149. }
  150. void BonusList::changed()
  151. {
  152. if(belongsToTree)
  153. CBonusSystemNode::treeHasChanged();
  154. }
  155. int BonusList::totalValue() const
  156. {
  157. int base = 0;
  158. int percentToBase = 0;
  159. int percentToAll = 0;
  160. int additive = 0;
  161. int indepMax = 0;
  162. bool hasIndepMax = false;
  163. int indepMin = 0;
  164. bool hasIndepMin = false;
  165. for (auto& b : bonuses)
  166. {
  167. switch(b->valType)
  168. {
  169. case Bonus::BASE_NUMBER:
  170. base += b->val;
  171. break;
  172. case Bonus::PERCENT_TO_ALL:
  173. percentToAll += b->val;
  174. break;
  175. case Bonus::PERCENT_TO_BASE:
  176. percentToBase += b->val;
  177. break;
  178. case Bonus::ADDITIVE_VALUE:
  179. additive += b->val;
  180. break;
  181. case Bonus::INDEPENDENT_MAX:
  182. if (!hasIndepMax)
  183. {
  184. indepMax = b->val;
  185. hasIndepMax = true;
  186. }
  187. else
  188. {
  189. vstd::amax(indepMax, b->val);
  190. }
  191. break;
  192. case Bonus::INDEPENDENT_MIN:
  193. if (!hasIndepMin)
  194. {
  195. indepMin = b->val;
  196. hasIndepMin = true;
  197. }
  198. else
  199. {
  200. vstd::amin(indepMin, b->val);
  201. }
  202. break;
  203. }
  204. }
  205. int modifiedBase = base + (base * percentToBase) / 100;
  206. modifiedBase += additive;
  207. int valFirst = (modifiedBase * (100 + percentToAll)) / 100;
  208. if(hasIndepMin && hasIndepMax)
  209. assert(indepMin < indepMax);
  210. const int notIndepBonuses = boost::count_if(bonuses, [](const std::shared_ptr<Bonus>& b)
  211. {
  212. return b->valType != Bonus::INDEPENDENT_MAX && b->valType != Bonus::INDEPENDENT_MIN;
  213. });
  214. if (hasIndepMax)
  215. {
  216. if(notIndepBonuses)
  217. vstd::amax(valFirst, indepMax);
  218. else
  219. valFirst = indepMax;
  220. }
  221. if (hasIndepMin)
  222. {
  223. if(notIndepBonuses)
  224. vstd::amin(valFirst, indepMin);
  225. else
  226. valFirst = indepMin;
  227. }
  228. return valFirst;
  229. }
  230. std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &select)
  231. {
  232. for (auto & b : bonuses)
  233. {
  234. if(select(b.get()))
  235. return b;
  236. }
  237. return nullptr;
  238. }
  239. const std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &selector) const
  240. {
  241. for (auto & b : bonuses)
  242. {
  243. if(selector(b.get()))
  244. return b;
  245. }
  246. return nullptr;
  247. }
  248. void BonusList::getBonuses(BonusList & out, const CSelector &selector) const
  249. {
  250. getBonuses(out, selector, nullptr);
  251. }
  252. void BonusList::getBonuses(BonusList & out, const CSelector &selector, const CSelector &limit) const
  253. {
  254. for (auto & b : bonuses)
  255. {
  256. //add matching bonuses that matches limit predicate or have NO_LIMIT if no given predicate
  257. if(selector(b.get()) && ((!limit && b->effectRange == Bonus::NO_LIMIT) || ((bool)limit && limit(b.get()))))
  258. out.push_back(b);
  259. }
  260. }
  261. void BonusList::getAllBonuses(BonusList &out) const
  262. {
  263. for(auto & b : bonuses)
  264. out.push_back(b);
  265. }
  266. int BonusList::valOfBonuses(const CSelector &select) const
  267. {
  268. BonusList ret;
  269. CSelector limit = nullptr;
  270. getBonuses(ret, select, limit);
  271. ret.eliminateDuplicates();
  272. return ret.totalValue();
  273. }
  274. void BonusList::eliminateDuplicates()
  275. {
  276. sort( bonuses.begin(), bonuses.end() );
  277. bonuses.erase( unique( bonuses.begin(), bonuses.end() ), bonuses.end() );
  278. }
  279. bool BonusList::updateBonuses(const CBonusSystemNode & context)
  280. {
  281. bool updated = false;
  282. for(std::shared_ptr<Bonus> b : *this)
  283. {
  284. if(b->updater)
  285. updated = b->updater->update(*b, context) || updated;
  286. }
  287. return updated;
  288. }
  289. void BonusList::push_back(std::shared_ptr<Bonus> x)
  290. {
  291. bonuses.push_back(x);
  292. changed();
  293. }
  294. BonusList::TInternalContainer::iterator BonusList::erase(const int position)
  295. {
  296. changed();
  297. return bonuses.erase(bonuses.begin() + position);
  298. }
  299. void BonusList::clear()
  300. {
  301. bonuses.clear();
  302. changed();
  303. }
  304. std::vector<BonusList*>::size_type BonusList::operator-=(std::shared_ptr<Bonus> const &i)
  305. {
  306. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  307. if(itr == bonuses.end())
  308. return false;
  309. bonuses.erase(itr);
  310. changed();
  311. return true;
  312. }
  313. void BonusList::resize(BonusList::TInternalContainer::size_type sz, std::shared_ptr<Bonus> c )
  314. {
  315. bonuses.resize(sz, c);
  316. changed();
  317. }
  318. void BonusList::insert(BonusList::TInternalContainer::iterator position, BonusList::TInternalContainer::size_type n, std::shared_ptr<Bonus> const &x)
  319. {
  320. bonuses.insert(position, n, x);
  321. changed();
  322. }
  323. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  324. {
  325. return valOfBonuses(Selector::type(type).And(selector));
  326. }
  327. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype) const
  328. {
  329. std::stringstream cachingStr;
  330. cachingStr << "type_" << type << "s_" << subtype;
  331. CSelector s = Selector::type(type);
  332. if(subtype != -1)
  333. s = s.And(Selector::subtype(subtype));
  334. return valOfBonuses(s, cachingStr.str());
  335. }
  336. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  337. {
  338. CSelector limit = nullptr;
  339. TBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  340. return hlp->totalValue();
  341. }
  342. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  343. {
  344. return getBonuses(selector, cachingStr)->size() > 0;
  345. }
  346. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  347. {
  348. return getBonuses(selector, limit, cachingStr)->size() > 0;
  349. }
  350. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  351. {
  352. std::stringstream cachingStr;
  353. cachingStr << "type_" << type << "s_" << subtype;
  354. CSelector s = Selector::type(type);
  355. if(subtype != -1)
  356. s = s.And(Selector::subtype(subtype));
  357. return hasBonus(s, cachingStr.str());
  358. }
  359. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  360. {
  361. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  362. }
  363. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  364. {
  365. return getAllBonuses(selector, limit, nullptr, cachingStr);
  366. }
  367. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  368. {
  369. std::stringstream cachingStr;
  370. cachingStr << "source_" << source << "id_" << sourceID;
  371. return hasBonus(Selector::source(source,sourceID), cachingStr.str());
  372. }
  373. int IBonusBearer::MoraleVal() const
  374. {
  375. if(hasBonusOfType(Bonus::NON_LIVING) || hasBonusOfType(Bonus::UNDEAD) ||
  376. hasBonusOfType(Bonus::NO_MORALE) || hasBonusOfType(Bonus::SIEGE_WEAPON))
  377. return 0;
  378. int ret = valOfBonuses(Bonus::MORALE);
  379. if(hasBonusOfType(Bonus::SELF_MORALE)) //eg. minotaur
  380. vstd::amax(ret, +1);
  381. return vstd::abetween(ret, -3, +3);
  382. }
  383. int IBonusBearer::LuckVal() const
  384. {
  385. if(hasBonusOfType(Bonus::NO_LUCK))
  386. return 0;
  387. int ret = valOfBonuses(Bonus::LUCK);
  388. if(hasBonusOfType(Bonus::SELF_LUCK)) //eg. halfling
  389. vstd::amax(ret, +1);
  390. return vstd::abetween(ret, -3, +3);
  391. }
  392. ui32 IBonusBearer::MaxHealth() const
  393. {
  394. const std::string cachingStr = "type_STACK_HEALTH";
  395. static const auto selector = Selector::type(Bonus::STACK_HEALTH);
  396. auto value = valOfBonuses(selector, cachingStr);
  397. return std::max(1, value); //never 0
  398. }
  399. int IBonusBearer::getAttack(bool ranged) const
  400. {
  401. const std::string cachingStr = "type_PRIMARY_SKILLs_ATTACK";
  402. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  403. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  404. }
  405. int IBonusBearer::getDefence(bool ranged) const
  406. {
  407. const std::string cachingStr = "type_PRIMARY_SKILLs_DEFENSE";
  408. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  409. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  410. }
  411. int IBonusBearer::getMinDamage(bool ranged) const
  412. {
  413. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_1";
  414. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1));
  415. return valOfBonuses(selector, cachingStr);
  416. }
  417. int IBonusBearer::getMaxDamage(bool ranged) const
  418. {
  419. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_2";
  420. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2));
  421. return valOfBonuses(selector, cachingStr);
  422. }
  423. si32 IBonusBearer::manaLimit() const
  424. {
  425. return si32(getPrimSkillLevel(PrimarySkill::KNOWLEDGE)
  426. * (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::INTELLIGENCE))
  427. / 10.0);
  428. }
  429. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  430. {
  431. int ret = valOfBonuses(Bonus::PRIMARY_SKILL, id);
  432. vstd::amax(ret, id/2); //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  433. return ret;
  434. }
  435. si32 IBonusBearer::magicResistance() const
  436. {
  437. return valOfBonuses(Bonus::MAGIC_RESISTANCE);
  438. }
  439. ui32 IBonusBearer::Speed(int turn, bool useBind) const
  440. {
  441. //war machines cannot move
  442. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON).And(Selector::turns(turn))))
  443. {
  444. return 0;
  445. }
  446. //bind effect check - doesn't influence stack initiative
  447. if(useBind && hasBonus(Selector::type(Bonus::BIND_EFFECT).And(Selector::turns(turn))))
  448. {
  449. return 0;
  450. }
  451. return valOfBonuses(Selector::type(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  452. }
  453. bool IBonusBearer::isLiving() const //TODO: theoreticaly there exists "LIVING" bonus in stack experience documentation
  454. {
  455. std::stringstream cachingStr;
  456. cachingStr << "type_" << Bonus::UNDEAD << "s_-1Otype_" << Bonus::NON_LIVING << "s_-11type_" << Bonus::SIEGE_WEAPON; //I don't really get what string labels mean?
  457. return !hasBonus(Selector::type(Bonus::UNDEAD)
  458. .Or(Selector::type(Bonus::NON_LIVING))
  459. .Or(Selector::type(Bonus::SIEGE_WEAPON)), cachingStr.str());
  460. }
  461. const std::shared_ptr<Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  462. {
  463. auto bonuses = getAllBonuses(selector, Selector::all);
  464. return bonuses->getFirst(Selector::all);
  465. }
  466. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector &selector)
  467. {
  468. auto ret = bonuses.getFirst(selector);
  469. if(ret)
  470. return ret;
  471. FOREACH_PARENT(pname)
  472. {
  473. ret = pname->getBonusLocalFirst(selector);
  474. if (ret)
  475. return ret;
  476. }
  477. return nullptr;
  478. }
  479. const std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst( const CSelector &selector ) const
  480. {
  481. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  482. }
  483. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  484. {
  485. for (auto & elem : parents)
  486. {
  487. const CBonusSystemNode *parent = elem;
  488. out.insert(parent);
  489. }
  490. }
  491. void CBonusSystemNode::getParents(TNodes &out)
  492. {
  493. for (auto & elem : parents)
  494. {
  495. const CBonusSystemNode *parent = elem;
  496. out.insert(const_cast<CBonusSystemNode*>(parent));
  497. }
  498. }
  499. void CBonusSystemNode::getBonusesRec(BonusList &out, const CSelector &selector, const CSelector &limit) const
  500. {
  501. FOREACH_CPARENT(p)
  502. {
  503. p->getBonusesRec(out, selector, limit);
  504. }
  505. bonuses.getBonuses(out, selector, limit);
  506. }
  507. void CBonusSystemNode::getAllBonusesRec(BonusList &out) const
  508. {
  509. FOREACH_CPARENT(p)
  510. {
  511. p->getAllBonusesRec(out);
  512. }
  513. bonuses.getAllBonuses(out);
  514. }
  515. const TBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  516. {
  517. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  518. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  519. {
  520. // Exclusive access for one thread
  521. static boost::mutex m;
  522. boost::mutex::scoped_lock lock(m);
  523. // If the bonus system tree changes(state of a single node or the relations to each other) then
  524. // cache all bonus objects. Selector objects doesn't matter.
  525. if (cachedLast != treeChanged)
  526. {
  527. cachedBonuses.clear();
  528. cachedRequests.clear();
  529. BonusList allBonuses;
  530. getAllBonusesRec(allBonuses);
  531. allBonuses.eliminateDuplicates();
  532. limitBonuses(allBonuses, cachedBonuses);
  533. cachedLast = treeChanged;
  534. }
  535. // If a bonus system request comes with a caching string then look up in the map if there are any
  536. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  537. if (cachingStr != "")
  538. {
  539. auto it = cachedRequests.find(cachingStr);
  540. if(it != cachedRequests.end())
  541. {
  542. //Cached list contains bonuses for our query with applied limiters
  543. return it->second;
  544. }
  545. }
  546. //We still don't have the bonuses (didn't returned them from cache)
  547. //Perform bonus selection
  548. auto ret = std::make_shared<BonusList>();
  549. cachedBonuses.getBonuses(*ret, selector, limit);
  550. // Save the results in the cache
  551. if(cachingStr != "")
  552. cachedRequests[cachingStr] = ret;
  553. return ret;
  554. }
  555. else
  556. {
  557. return getAllBonusesWithoutCaching(selector, limit, root);
  558. }
  559. }
  560. const TBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  561. {
  562. auto ret = std::make_shared<BonusList>();
  563. // Get bonus results without caching enabled.
  564. BonusList beforeLimiting, afterLimiting;
  565. getAllBonusesRec(beforeLimiting);
  566. beforeLimiting.eliminateDuplicates();
  567. if(!root || root == this)
  568. {
  569. limitBonuses(beforeLimiting, afterLimiting);
  570. afterLimiting.getBonuses(*ret, selector, limit);
  571. }
  572. else if(root)
  573. {
  574. //We want to limit our query against an external node. We get all its bonuses,
  575. // add the ones we're considering and see if they're cut out by limiters
  576. BonusList rootBonuses, limitedRootBonuses;
  577. getAllBonusesRec(rootBonuses);
  578. for(auto b : beforeLimiting)
  579. rootBonuses.push_back(b);
  580. rootBonuses.eliminateDuplicates();
  581. root->limitBonuses(rootBonuses, limitedRootBonuses);
  582. for(auto b : beforeLimiting)
  583. if(vstd::contains(limitedRootBonuses, b))
  584. afterLimiting.push_back(b);
  585. afterLimiting.getBonuses(*ret, selector, limit);
  586. }
  587. return ret;
  588. }
  589. CBonusSystemNode::CBonusSystemNode()
  590. : bonuses(true),
  591. exportedBonuses(true),
  592. nodeType(UNKNOWN),
  593. cachedLast(0)
  594. {
  595. }
  596. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType)
  597. : bonuses(true),
  598. exportedBonuses(true),
  599. nodeType(NodeType),
  600. cachedLast(0)
  601. {
  602. }
  603. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other):
  604. bonuses(std::move(other.bonuses)),
  605. exportedBonuses(std::move(other.exportedBonuses)),
  606. nodeType(other.nodeType),
  607. description(other.description),
  608. cachedLast(0)
  609. {
  610. std::swap(parents, other.parents);
  611. std::swap(children, other.children);
  612. //fixing bonus tree without recalculation
  613. for(CBonusSystemNode * n : parents)
  614. {
  615. n->children -= &other;
  616. n->children.push_back(this);
  617. }
  618. for(CBonusSystemNode * n : children)
  619. {
  620. n->parents -= &other;
  621. n->parents.push_back(this);
  622. }
  623. //cache ignored
  624. //cachedBonuses
  625. //cachedRequests
  626. }
  627. CBonusSystemNode::~CBonusSystemNode()
  628. {
  629. detachFromAll();
  630. if(children.size())
  631. {
  632. while(children.size())
  633. children.front()->detachFrom(this);
  634. }
  635. }
  636. void CBonusSystemNode::attachTo(CBonusSystemNode *parent)
  637. {
  638. assert(!vstd::contains(parents, parent));
  639. parents.push_back(parent);
  640. if(parent->actsAsBonusSourceOnly())
  641. parent->newRedDescendant(this);
  642. else
  643. newRedDescendant(parent);
  644. parent->newChildAttached(this);
  645. CBonusSystemNode::treeHasChanged();
  646. }
  647. void CBonusSystemNode::detachFrom(CBonusSystemNode *parent)
  648. {
  649. assert(vstd::contains(parents, parent));
  650. if(parent->actsAsBonusSourceOnly())
  651. parent->removedRedDescendant(this);
  652. else
  653. removedRedDescendant(parent);
  654. parents -= parent;
  655. parent->childDetached(this);
  656. CBonusSystemNode::treeHasChanged();
  657. }
  658. void CBonusSystemNode::popBonuses(const CSelector &s)
  659. {
  660. BonusList bl;
  661. exportedBonuses.getBonuses(bl, s, Selector::all);
  662. for(auto b : bl)
  663. removeBonus(b);
  664. for(CBonusSystemNode *child : children)
  665. child->popBonuses(s);
  666. }
  667. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  668. {
  669. BonusList bl;
  670. exportedBonuses.getBonuses(bl, s, Selector::all);
  671. for(auto b : bl)
  672. {
  673. b->turnsRemain--;
  674. if(b->turnsRemain <= 0)
  675. removeBonus(b);
  676. }
  677. for(CBonusSystemNode *child : children)
  678. child->reduceBonusDurations(s);
  679. }
  680. void CBonusSystemNode::updateBonuses()
  681. {
  682. bool updated = bonuses.updateBonuses(*this);
  683. updated = exportedBonuses.updateBonuses(*this) || updated;
  684. if(updated)
  685. treeHasChanged();
  686. }
  687. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  688. {
  689. //turnsRemain shouldn't be zero for following durations
  690. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  691. {
  692. assert(b->turnsRemain);
  693. }
  694. assert(!vstd::contains(exportedBonuses, b));
  695. exportedBonuses.push_back(b);
  696. exportBonus(b);
  697. if(b->updater)
  698. b->updater->update(*b, *this);
  699. CBonusSystemNode::treeHasChanged();
  700. }
  701. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  702. {
  703. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  704. if(bonus)
  705. bonus->val += b->val;
  706. else
  707. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  708. }
  709. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  710. {
  711. exportedBonuses -= b;
  712. if(b->propagator)
  713. unpropagateBonus(b);
  714. else
  715. bonuses -= b;
  716. CBonusSystemNode::treeHasChanged();
  717. }
  718. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  719. {
  720. switch(nodeType)
  721. {
  722. case CREATURE:
  723. case ARTIFACT:
  724. case ARTIFACT_INSTANCE:
  725. return true;
  726. default:
  727. return false;
  728. }
  729. }
  730. void CBonusSystemNode::propagateBonus(std::shared_ptr<Bonus> b)
  731. {
  732. if(b->propagator->shouldBeAttached(this))
  733. {
  734. bonuses.push_back(b);
  735. logBonus->trace("#$# %s #propagated to# %s", b->Description(), nodeName());
  736. }
  737. FOREACH_RED_CHILD(child)
  738. child->propagateBonus(b);
  739. }
  740. void CBonusSystemNode::unpropagateBonus(std::shared_ptr<Bonus> b)
  741. {
  742. if(b->propagator->shouldBeAttached(this))
  743. {
  744. bonuses -= b;
  745. while(vstd::contains(bonuses, b))
  746. {
  747. logBonus->error("Bonus was duplicated (%s) at %s", b->Description(), nodeName());
  748. bonuses -= b;
  749. }
  750. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  751. }
  752. FOREACH_RED_CHILD(child)
  753. child->unpropagateBonus(b);
  754. }
  755. void CBonusSystemNode::newChildAttached(CBonusSystemNode *child)
  756. {
  757. assert(!vstd::contains(children, child));
  758. children.push_back(child);
  759. }
  760. void CBonusSystemNode::childDetached(CBonusSystemNode *child)
  761. {
  762. if (vstd::contains(children, child))
  763. children -= child;
  764. else
  765. {
  766. logBonus->error("Error! %s #cannot be detached from# %s", child->nodeName(), nodeName());
  767. throw std::runtime_error("internal error");
  768. }
  769. }
  770. void CBonusSystemNode::detachFromAll()
  771. {
  772. while(parents.size())
  773. detachFrom(parents.front());
  774. }
  775. bool CBonusSystemNode::isIndependentNode() const
  776. {
  777. return parents.empty() && children.empty();
  778. }
  779. std::string CBonusSystemNode::nodeName() const
  780. {
  781. return description.size()
  782. ? description
  783. : std::string("Bonus system node of type ") + typeid(*this).name();
  784. }
  785. void CBonusSystemNode::deserializationFix()
  786. {
  787. exportBonuses();
  788. }
  789. void CBonusSystemNode::getRedParents(TNodes &out)
  790. {
  791. FOREACH_PARENT(pname)
  792. {
  793. if(pname->actsAsBonusSourceOnly())
  794. {
  795. out.insert(pname);
  796. }
  797. }
  798. if(!actsAsBonusSourceOnly())
  799. {
  800. for(CBonusSystemNode *child : children)
  801. {
  802. out.insert(child);
  803. }
  804. }
  805. }
  806. void CBonusSystemNode::getRedChildren(TNodes &out)
  807. {
  808. FOREACH_PARENT(pname)
  809. {
  810. if(!pname->actsAsBonusSourceOnly())
  811. {
  812. out.insert(pname);
  813. }
  814. }
  815. if(actsAsBonusSourceOnly())
  816. {
  817. for(CBonusSystemNode *child : children)
  818. {
  819. out.insert(child);
  820. }
  821. }
  822. }
  823. void CBonusSystemNode::newRedDescendant(CBonusSystemNode *descendant)
  824. {
  825. for(auto b : exportedBonuses)
  826. if(b->propagator)
  827. descendant->propagateBonus(b);
  828. FOREACH_RED_PARENT(parent)
  829. parent->newRedDescendant(descendant);
  830. }
  831. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode *descendant)
  832. {
  833. for(auto b : exportedBonuses)
  834. if(b->propagator)
  835. descendant->unpropagateBonus(b);
  836. FOREACH_RED_PARENT(parent)
  837. parent->removedRedDescendant(descendant);
  838. }
  839. void CBonusSystemNode::getRedAncestors(TNodes &out)
  840. {
  841. getRedParents(out);
  842. FOREACH_RED_PARENT(p)
  843. p->getRedAncestors(out);
  844. }
  845. void CBonusSystemNode::getRedDescendants(TNodes &out)
  846. {
  847. getRedChildren(out);
  848. FOREACH_RED_CHILD(c)
  849. c->getRedChildren(out);
  850. }
  851. void CBonusSystemNode::exportBonus(std::shared_ptr<Bonus> b)
  852. {
  853. if(b->propagator)
  854. propagateBonus(b);
  855. else
  856. bonuses.push_back(b);
  857. CBonusSystemNode::treeHasChanged();
  858. }
  859. void CBonusSystemNode::exportBonuses()
  860. {
  861. for(auto b : exportedBonuses)
  862. exportBonus(b);
  863. }
  864. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  865. {
  866. return nodeType;
  867. }
  868. const BonusList& CBonusSystemNode::getBonusList() const
  869. {
  870. return bonuses;
  871. }
  872. const TNodesVector& CBonusSystemNode::getParentNodes() const
  873. {
  874. return parents;
  875. }
  876. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  877. {
  878. return children;
  879. }
  880. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  881. {
  882. nodeType = type;
  883. }
  884. BonusList& CBonusSystemNode::getExportedBonusList()
  885. {
  886. return exportedBonuses;
  887. }
  888. const std::string& CBonusSystemNode::getDescription() const
  889. {
  890. return description;
  891. }
  892. void CBonusSystemNode::setDescription(const std::string &description)
  893. {
  894. this->description = description;
  895. }
  896. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  897. {
  898. assert(&allBonuses != &out); //todo should it work in-place?
  899. BonusList undecided = allBonuses,
  900. &accepted = out;
  901. while(true)
  902. {
  903. int undecidedCount = undecided.size();
  904. for(int i = 0; i < undecided.size(); i++)
  905. {
  906. auto b = undecided[i];
  907. BonusLimitationContext context = {b, *this, out};
  908. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  909. if(decision == ILimiter::DISCARD)
  910. {
  911. undecided.erase(i);
  912. i--; continue;
  913. }
  914. else if(decision == ILimiter::ACCEPT)
  915. {
  916. accepted.push_back(b);
  917. undecided.erase(i);
  918. i--; continue;
  919. }
  920. else
  921. assert(decision == ILimiter::NOT_SURE);
  922. }
  923. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  924. return;
  925. }
  926. }
  927. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  928. {
  929. auto ret = std::make_shared<BonusList>();
  930. limitBonuses(allBonuses, *ret);
  931. return ret;
  932. }
  933. void CBonusSystemNode::treeHasChanged()
  934. {
  935. treeChanged++;
  936. }
  937. int64_t CBonusSystemNode::getTreeVersion() const
  938. {
  939. int64_t ret = treeChanged;
  940. return ret << 32;
  941. }
  942. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  943. {
  944. if(obj)
  945. return obj->valOfBonuses(type, subtype);
  946. return 0;
  947. }
  948. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  949. {
  950. if(obj)
  951. return obj->hasBonusOfType(type, subtype);
  952. return false;
  953. }
  954. std::string Bonus::Description() const
  955. {
  956. std::ostringstream str;
  957. if(description.empty())
  958. switch(source)
  959. {
  960. case ARTIFACT:
  961. str << VLC->arth->artifacts[sid]->Name();
  962. break;
  963. case SPELL_EFFECT:
  964. str << SpellID(sid).toSpell()->name;
  965. break;
  966. case CREATURE_ABILITY:
  967. str << VLC->creh->creatures[sid]->namePl;
  968. break;
  969. case SECONDARY_SKILL:
  970. str << VLC->skillh->skillName(sid);
  971. break;
  972. default:
  973. //todo: handle all possible sources
  974. str << "Unknown";
  975. break;
  976. }
  977. else
  978. str << description;
  979. if(val != 0)
  980. str << " " << std::showpos << val;
  981. return str.str();
  982. }
  983. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  984. {
  985. switch(type)
  986. {
  987. case Bonus::PRIMARY_SKILL:
  988. return JsonUtils::stringNode(PrimarySkill::names[subtype]);
  989. case Bonus::SECONDARY_SKILL_PREMY:
  990. return JsonUtils::stringNode(NSecondarySkill::names[subtype]);
  991. case Bonus::SPECIAL_SPELL_LEV:
  992. case Bonus::SPECIFIC_SPELL_DAMAGE:
  993. case Bonus::SPECIAL_BLESS_DAMAGE:
  994. case Bonus::MAXED_SPELL:
  995. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  996. return JsonUtils::stringNode((*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier);
  997. case Bonus::SPECIAL_UPGRADE:
  998. return JsonUtils::stringNode(CreatureID::encode(subtype));
  999. case Bonus::GENERATE_RESOURCE:
  1000. return JsonUtils::stringNode(GameConstants::RESOURCE_NAMES[subtype]);
  1001. default:
  1002. return JsonUtils::intNode(subtype);
  1003. }
  1004. }
  1005. JsonNode additionalInfoToJson(Bonus::BonusType type, int addInfo)
  1006. {
  1007. switch(type)
  1008. {
  1009. case Bonus::SPECIAL_UPGRADE:
  1010. return JsonUtils::stringNode(CreatureID::encode(addInfo));
  1011. default:
  1012. return JsonUtils::intNode(addInfo);
  1013. }
  1014. }
  1015. JsonNode Bonus::toJsonNode() const
  1016. {
  1017. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1018. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1019. if(subtype != -1)
  1020. root["subtype"] = subtypeToJson(type, subtype);
  1021. if(additionalInfo != -1)
  1022. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1023. if(val != 0)
  1024. root["val"].Integer() = val;
  1025. if(valType != ADDITIVE_VALUE)
  1026. root["valType"].String() = vstd::findKey(bonusValueMap, valType);
  1027. if(limiter)
  1028. root["limiter"] = limiter->toJsonNode();
  1029. if(updater)
  1030. root["updater"] = updater->toJsonNode();
  1031. return root;
  1032. }
  1033. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype)
  1034. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  1035. {
  1036. additionalInfo = -1;
  1037. turnsRemain = 0;
  1038. valType = ADDITIVE_VALUE;
  1039. effectRange = NO_LIMIT;
  1040. boost::algorithm::trim(description);
  1041. }
  1042. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType)
  1043. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  1044. {
  1045. additionalInfo = -1;
  1046. turnsRemain = 0;
  1047. effectRange = NO_LIMIT;
  1048. }
  1049. Bonus::Bonus()
  1050. {
  1051. duration = PERMANENT;
  1052. turnsRemain = 0;
  1053. type = NONE;
  1054. subtype = -1;
  1055. additionalInfo = -1;
  1056. valType = ADDITIVE_VALUE;
  1057. effectRange = NO_LIMIT;
  1058. val = 0;
  1059. source = OTHER;
  1060. sid = 0;
  1061. }
  1062. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  1063. {
  1064. propagator = Propagator;
  1065. return this->shared_from_this();
  1066. }
  1067. namespace Selector
  1068. {
  1069. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> type(&Bonus::type);
  1070. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> subtype(&Bonus::subtype);
  1071. DLL_LINKAGE CSelectFieldEqual<si32> info(&Bonus::additionalInfo);
  1072. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> sourceType(&Bonus::source);
  1073. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> effectRange(&Bonus::effectRange);
  1074. DLL_LINKAGE CWillLastTurns turns;
  1075. DLL_LINKAGE CWillLastDays days;
  1076. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1077. {
  1078. return type(Type).And(subtype(Subtype));
  1079. }
  1080. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, si32 info)
  1081. {
  1082. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1083. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1084. .And(CSelectFieldEqual<si32>(&Bonus::additionalInfo)(info));
  1085. }
  1086. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1087. {
  1088. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1089. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1090. }
  1091. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1092. {
  1093. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1094. }
  1095. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1096. {
  1097. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1098. }
  1099. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1100. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1101. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1102. {
  1103. Bonus dummy;
  1104. dummy.type = type;
  1105. return sel(&dummy);
  1106. }
  1107. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1108. {
  1109. Bonus dummy;
  1110. dummy.type = type;
  1111. dummy.subtype = subtype;
  1112. return sel(&dummy);
  1113. }
  1114. }
  1115. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  1116. {
  1117. switch(node->getNodeType())
  1118. {
  1119. case CBonusSystemNode::STACK_BATTLE:
  1120. return static_cast<const CStack*>(node);
  1121. default:
  1122. return nullptr;
  1123. }
  1124. }
  1125. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  1126. {
  1127. switch(node->getNodeType())
  1128. {
  1129. case CBonusSystemNode::STACK_INSTANCE:
  1130. return (static_cast<const CStackInstance *>(node));
  1131. case CBonusSystemNode::STACK_BATTLE:
  1132. return (static_cast<const CStack*>(node))->base;
  1133. default:
  1134. return nullptr;
  1135. }
  1136. }
  1137. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1138. {
  1139. switch(node->getNodeType())
  1140. {
  1141. case CBonusSystemNode::CREATURE:
  1142. return (static_cast<const CCreature *>(node));
  1143. case CBonusSystemNode::STACK_BATTLE:
  1144. return (static_cast<const CStack*>(node))->type;
  1145. default:
  1146. const CStackInstance * csi = retrieveStackInstance(node);
  1147. if(csi)
  1148. return csi->type;
  1149. return nullptr;
  1150. }
  1151. }
  1152. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1153. {
  1154. for (ui32 i = 0; i < bonusList.size(); i++)
  1155. {
  1156. auto b = bonusList[i];
  1157. out << "Bonus " << i << "\n" << *b << std::endl;
  1158. }
  1159. return out;
  1160. }
  1161. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1162. {
  1163. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1164. if(i->second == bonus.type)
  1165. out << "\tType: " << i->first << " \t";
  1166. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1167. printField(val);
  1168. printField(subtype);
  1169. printField(duration);
  1170. printField(source);
  1171. printField(sid);
  1172. printField(additionalInfo);
  1173. printField(turnsRemain);
  1174. printField(valType);
  1175. printField(effectRange);
  1176. #undef printField
  1177. if(bonus.limiter)
  1178. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1179. if(bonus.updater)
  1180. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1181. return out;
  1182. }
  1183. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1184. {
  1185. if (limiter)
  1186. {
  1187. //If we already have limiter list, retrieve it
  1188. auto limiterList = std::dynamic_pointer_cast<LimiterList>(limiter);
  1189. if(!limiterList)
  1190. {
  1191. //Create a new limiter list with old limiter and the new one will be pushed later
  1192. limiterList = std::make_shared<LimiterList>();
  1193. limiterList->add(limiter);
  1194. limiter = limiterList;
  1195. }
  1196. limiterList->add(Limiter);
  1197. }
  1198. else
  1199. {
  1200. limiter = Limiter;
  1201. }
  1202. return this->shared_from_this();
  1203. }
  1204. ILimiter::~ILimiter()
  1205. {
  1206. }
  1207. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1208. {
  1209. return false;
  1210. }
  1211. std::string ILimiter::toString() const
  1212. {
  1213. return typeid(*this).name();
  1214. }
  1215. JsonNode ILimiter::toJsonNode() const
  1216. {
  1217. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1218. root["type"].String() = toString();
  1219. return root;
  1220. }
  1221. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1222. {
  1223. const CCreature *c = retrieveCreature(&context.node);
  1224. if(!c)
  1225. return true;
  1226. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1227. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1228. }
  1229. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature &Creature, bool IncludeUpgrades)
  1230. :creature(&Creature), includeUpgrades(IncludeUpgrades)
  1231. {
  1232. }
  1233. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1234. {
  1235. creature = nullptr;
  1236. includeUpgrades = false;
  1237. }
  1238. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1239. {
  1240. creature = VLC->creh->creatures[id];
  1241. }
  1242. std::string CCreatureTypeLimiter::toString() const
  1243. {
  1244. char buf[100];
  1245. sprintf(buf, "CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)",
  1246. creature->identifier.c_str(),
  1247. (includeUpgrades ? "true" : "false"));
  1248. return std::string(buf);
  1249. }
  1250. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1251. {
  1252. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1253. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1254. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->identifier));
  1255. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1256. return root;
  1257. }
  1258. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1259. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1260. {
  1261. }
  1262. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1263. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1264. {
  1265. }
  1266. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1267. {
  1268. CSelector mySelector = isSubtypeRelevant
  1269. ? Selector::typeSubtype(type, subtype)
  1270. : Selector::type(type);
  1271. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1272. if(context.alreadyAccepted.getFirst(mySelector))
  1273. return ACCEPT;
  1274. //do not accept for now but it may change if more bonuses gets included
  1275. return NOT_SURE;
  1276. }
  1277. IPropagator::~IPropagator()
  1278. {
  1279. }
  1280. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1281. {
  1282. return false;
  1283. }
  1284. CPropagatorNodeType::CPropagatorNodeType()
  1285. :nodeType(0)
  1286. {
  1287. }
  1288. CPropagatorNodeType::CPropagatorNodeType(int NodeType)
  1289. : nodeType(NodeType)
  1290. {
  1291. }
  1292. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1293. {
  1294. return nodeType == dest->getNodeType();
  1295. }
  1296. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter(int TerrainType)
  1297. : terrainType(TerrainType)
  1298. {
  1299. }
  1300. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter()
  1301. : terrainType(-1)
  1302. {
  1303. }
  1304. int CreatureNativeTerrainLimiter::limit(const BonusLimitationContext &context) const
  1305. {
  1306. const CCreature *c = retrieveCreature(&context.node);
  1307. return !c || !c->isItNativeTerrain(terrainType); //drop bonus for non-creatures or non-native residents
  1308. //TODO neutral creatues
  1309. }
  1310. CreatureFactionLimiter::CreatureFactionLimiter(int Faction)
  1311. : faction(Faction)
  1312. {
  1313. }
  1314. CreatureFactionLimiter::CreatureFactionLimiter()
  1315. : faction(-1)
  1316. {
  1317. }
  1318. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1319. {
  1320. const CCreature *c = retrieveCreature(&context.node);
  1321. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1322. }
  1323. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1324. : alignment(-1)
  1325. {
  1326. }
  1327. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1328. : alignment(Alignment)
  1329. {
  1330. }
  1331. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1332. {
  1333. const CCreature *c = retrieveCreature(&context.node);
  1334. if(!c)
  1335. return true;
  1336. switch(alignment)
  1337. {
  1338. case EAlignment::GOOD:
  1339. return !c->isGood(); //if not good -> return true (drop bonus)
  1340. case EAlignment::NEUTRAL:
  1341. return c->isEvil() || c->isGood();
  1342. case EAlignment::EVIL:
  1343. return !c->isEvil();
  1344. default:
  1345. logBonus->warn("Warning: illegal alignment in limiter!");
  1346. return true;
  1347. }
  1348. }
  1349. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1350. :minRank(Min), maxRank(Max)
  1351. {
  1352. }
  1353. RankRangeLimiter::RankRangeLimiter()
  1354. {
  1355. minRank = maxRank = -1;
  1356. }
  1357. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1358. {
  1359. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1360. if(csi)
  1361. {
  1362. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1363. return true;
  1364. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1365. }
  1366. return true;
  1367. }
  1368. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1369. {
  1370. const CStack * s = retrieveStackBattle(&context.node);
  1371. if(s)
  1372. return s->owner != owner;
  1373. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1374. if(csi && csi->armyObj)
  1375. return csi->armyObj->tempOwner != owner;
  1376. return true;
  1377. }
  1378. StackOwnerLimiter::StackOwnerLimiter()
  1379. : owner(-1)
  1380. {
  1381. }
  1382. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1383. : owner(Owner)
  1384. {
  1385. }
  1386. int LimiterList::limit( const BonusLimitationContext &context ) const
  1387. {
  1388. bool wasntSure = false;
  1389. for(auto limiter : limiters)
  1390. {
  1391. auto result = limiter->limit(context);
  1392. if(result == ILimiter::DISCARD)
  1393. return result;
  1394. if(result == ILimiter::NOT_SURE)
  1395. wasntSure = true;
  1396. }
  1397. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1398. }
  1399. void LimiterList::add( TLimiterPtr limiter )
  1400. {
  1401. limiters.push_back(limiter);
  1402. }
  1403. // Updaters
  1404. std::shared_ptr<Bonus> Bonus::addUpdater(TUpdaterPtr Updater)
  1405. {
  1406. updater = Updater;
  1407. return this->shared_from_this();
  1408. }
  1409. IUpdater::~IUpdater()
  1410. {
  1411. }
  1412. std::string IUpdater::toString() const
  1413. {
  1414. return typeid(*this).name();
  1415. }
  1416. ScalingUpdater::ScalingUpdater() : valPer20(0), stepSize(1)
  1417. {
  1418. }
  1419. ScalingUpdater::ScalingUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  1420. {
  1421. }
  1422. bool ScalingUpdater::update(Bonus & b, const CBonusSystemNode & context) const
  1423. {
  1424. if(context.getNodeType() == CBonusSystemNode::HERO)
  1425. {
  1426. int level = static_cast<const CGHeroInstance &>(context).level;
  1427. int steps = stepSize ? level / stepSize : level;
  1428. //rounding follows format for HMM3 creature specialty bonus
  1429. int newVal = (valPer20 * steps + 19) / 20;
  1430. if(b.val != newVal)
  1431. {
  1432. b.val = newVal;
  1433. return true;
  1434. }
  1435. }
  1436. return false;
  1437. }
  1438. std::string ScalingUpdater::toString() const
  1439. {
  1440. char buf[100];
  1441. sprintf(buf, "ScalingUpdater(valPer20=%d, stepSize=%d)", valPer20, stepSize);
  1442. return std::string(buf);
  1443. }
  1444. JsonNode ScalingUpdater::toJsonNode() const
  1445. {
  1446. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1447. root["type"].String() = "GROWS_WITH_LEVEL";
  1448. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  1449. if(stepSize > 1)
  1450. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  1451. return root;
  1452. }