2
0

HeroBonus.cpp 38 KB

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