HeroBonus.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603
  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. bool BonusList::updateBonuses(const CBonusSystemNode & context)
  279. {
  280. bool updated = false;
  281. for(std::shared_ptr<Bonus> b : *this)
  282. {
  283. if(b->updater)
  284. updated = b->updater->update(*b, context) || updated;
  285. }
  286. return updated;
  287. }
  288. void BonusList::push_back(std::shared_ptr<Bonus> x)
  289. {
  290. bonuses.push_back(x);
  291. changed();
  292. }
  293. BonusList::TInternalContainer::iterator BonusList::erase(const int position)
  294. {
  295. changed();
  296. return bonuses.erase(bonuses.begin() + position);
  297. }
  298. void BonusList::clear()
  299. {
  300. bonuses.clear();
  301. changed();
  302. }
  303. std::vector<BonusList*>::size_type BonusList::operator-=(std::shared_ptr<Bonus> const &i)
  304. {
  305. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  306. if(itr == bonuses.end())
  307. return false;
  308. bonuses.erase(itr);
  309. changed();
  310. return true;
  311. }
  312. void BonusList::resize(BonusList::TInternalContainer::size_type sz, std::shared_ptr<Bonus> c )
  313. {
  314. bonuses.resize(sz, c);
  315. changed();
  316. }
  317. void BonusList::insert(BonusList::TInternalContainer::iterator position, BonusList::TInternalContainer::size_type n, std::shared_ptr<Bonus> const &x)
  318. {
  319. bonuses.insert(position, n, x);
  320. changed();
  321. }
  322. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  323. {
  324. return valOfBonuses(Selector::type(type).And(selector));
  325. }
  326. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype) const
  327. {
  328. std::stringstream cachingStr;
  329. cachingStr << "type_" << type << "s_" << subtype;
  330. CSelector s = Selector::type(type);
  331. if(subtype != -1)
  332. s = s.And(Selector::subtype(subtype));
  333. return valOfBonuses(s, cachingStr.str());
  334. }
  335. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  336. {
  337. CSelector limit = nullptr;
  338. TBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  339. return hlp->totalValue();
  340. }
  341. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  342. {
  343. return getBonuses(selector, cachingStr)->size() > 0;
  344. }
  345. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  346. {
  347. return getBonuses(selector, limit, cachingStr)->size() > 0;
  348. }
  349. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  350. {
  351. std::stringstream cachingStr;
  352. cachingStr << "type_" << type << "s_" << subtype;
  353. CSelector s = Selector::type(type);
  354. if(subtype != -1)
  355. s = s.And(Selector::subtype(subtype));
  356. return hasBonus(s, cachingStr.str());
  357. }
  358. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  359. {
  360. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  361. }
  362. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  363. {
  364. return getAllBonuses(selector, limit, nullptr, cachingStr);
  365. }
  366. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  367. {
  368. std::stringstream cachingStr;
  369. cachingStr << "source_" << source << "id_" << sourceID;
  370. return hasBonus(Selector::source(source,sourceID), cachingStr.str());
  371. }
  372. int IBonusBearer::MoraleVal() const
  373. {
  374. if(hasBonusOfType(Bonus::NON_LIVING) || hasBonusOfType(Bonus::UNDEAD) ||
  375. hasBonusOfType(Bonus::NO_MORALE) || hasBonusOfType(Bonus::SIEGE_WEAPON))
  376. return 0;
  377. int ret = valOfBonuses(Bonus::MORALE);
  378. if(hasBonusOfType(Bonus::SELF_MORALE)) //eg. minotaur
  379. vstd::amax(ret, +1);
  380. return vstd::abetween(ret, -3, +3);
  381. }
  382. int IBonusBearer::LuckVal() const
  383. {
  384. if(hasBonusOfType(Bonus::NO_LUCK))
  385. return 0;
  386. int ret = valOfBonuses(Bonus::LUCK);
  387. if(hasBonusOfType(Bonus::SELF_LUCK)) //eg. halfling
  388. vstd::amax(ret, +1);
  389. return vstd::abetween(ret, -3, +3);
  390. }
  391. ui32 IBonusBearer::MaxHealth() const
  392. {
  393. const std::string cachingStr = "type_STACK_HEALTH";
  394. static const auto selector = Selector::type(Bonus::STACK_HEALTH);
  395. auto value = valOfBonuses(selector, cachingStr);
  396. return std::max(1, value); //never 0
  397. }
  398. int IBonusBearer::getAttack(bool ranged) const
  399. {
  400. const std::string cachingStr = "type_PRIMARY_SKILLs_ATTACK";
  401. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  402. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  403. }
  404. int IBonusBearer::getDefence(bool ranged) const
  405. {
  406. const std::string cachingStr = "type_PRIMARY_SKILLs_DEFENSE";
  407. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  408. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  409. }
  410. int IBonusBearer::getMinDamage(bool ranged) const
  411. {
  412. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_1";
  413. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1));
  414. return valOfBonuses(selector, cachingStr);
  415. }
  416. int IBonusBearer::getMaxDamage(bool ranged) const
  417. {
  418. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_2";
  419. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2));
  420. return valOfBonuses(selector, cachingStr);
  421. }
  422. si32 IBonusBearer::manaLimit() const
  423. {
  424. return si32(getPrimSkillLevel(PrimarySkill::KNOWLEDGE)
  425. * (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::INTELLIGENCE))
  426. / 10.0);
  427. }
  428. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  429. {
  430. int ret = valOfBonuses(Bonus::PRIMARY_SKILL, id);
  431. vstd::amax(ret, id/2); //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  432. return ret;
  433. }
  434. si32 IBonusBearer::magicResistance() const
  435. {
  436. return valOfBonuses(Bonus::MAGIC_RESISTANCE);
  437. }
  438. ui32 IBonusBearer::Speed(int turn, bool useBind) const
  439. {
  440. //war machines cannot move
  441. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON).And(Selector::turns(turn))))
  442. {
  443. return 0;
  444. }
  445. //bind effect check - doesn't influence stack initiative
  446. if(useBind && hasBonus(Selector::type(Bonus::BIND_EFFECT).And(Selector::turns(turn))))
  447. {
  448. return 0;
  449. }
  450. return valOfBonuses(Selector::type(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  451. }
  452. bool IBonusBearer::isLiving() const //TODO: theoreticaly there exists "LIVING" bonus in stack experience documentation
  453. {
  454. std::stringstream cachingStr;
  455. cachingStr << "type_" << Bonus::UNDEAD << "s_-1Otype_" << Bonus::NON_LIVING << "s_-11type_" << Bonus::SIEGE_WEAPON; //I don't really get what string labels mean?
  456. return !hasBonus(Selector::type(Bonus::UNDEAD)
  457. .Or(Selector::type(Bonus::NON_LIVING))
  458. .Or(Selector::type(Bonus::SIEGE_WEAPON)), cachingStr.str());
  459. }
  460. const std::shared_ptr<Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  461. {
  462. auto bonuses = getAllBonuses(selector, Selector::all);
  463. return bonuses->getFirst(Selector::all);
  464. }
  465. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector &selector)
  466. {
  467. auto ret = bonuses.getFirst(selector);
  468. if(ret)
  469. return ret;
  470. FOREACH_PARENT(pname)
  471. {
  472. ret = pname->getBonusLocalFirst(selector);
  473. if (ret)
  474. return ret;
  475. }
  476. return nullptr;
  477. }
  478. const std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst( const CSelector &selector ) const
  479. {
  480. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  481. }
  482. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  483. {
  484. for (auto & elem : parents)
  485. {
  486. const CBonusSystemNode *parent = elem;
  487. out.insert(parent);
  488. }
  489. }
  490. void CBonusSystemNode::getParents(TNodes &out)
  491. {
  492. for (auto & elem : parents)
  493. {
  494. const CBonusSystemNode *parent = elem;
  495. out.insert(const_cast<CBonusSystemNode*>(parent));
  496. }
  497. }
  498. void CBonusSystemNode::getBonusesRec(BonusList &out, const CSelector &selector, const CSelector &limit) const
  499. {
  500. FOREACH_CPARENT(p)
  501. {
  502. p->getBonusesRec(out, selector, limit);
  503. }
  504. bonuses.getBonuses(out, selector, limit);
  505. }
  506. void CBonusSystemNode::getAllBonusesRec(BonusList &out) const
  507. {
  508. FOREACH_CPARENT(p)
  509. {
  510. p->getAllBonusesRec(out);
  511. }
  512. bonuses.getAllBonuses(out);
  513. }
  514. const TBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  515. {
  516. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  517. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  518. {
  519. // Exclusive access for one thread
  520. static boost::mutex m;
  521. boost::mutex::scoped_lock lock(m);
  522. // If the bonus system tree changes(state of a single node or the relations to each other) then
  523. // cache all bonus objects. Selector objects doesn't matter.
  524. if (cachedLast != treeChanged)
  525. {
  526. cachedBonuses.clear();
  527. cachedRequests.clear();
  528. BonusList allBonuses;
  529. getAllBonusesRec(allBonuses);
  530. allBonuses.eliminateDuplicates();
  531. limitBonuses(allBonuses, cachedBonuses);
  532. cachedLast = treeChanged;
  533. }
  534. // If a bonus system request comes with a caching string then look up in the map if there are any
  535. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  536. if (cachingStr != "")
  537. {
  538. auto it = cachedRequests.find(cachingStr);
  539. if(it != cachedRequests.end())
  540. {
  541. //Cached list contains bonuses for our query with applied limiters
  542. return it->second;
  543. }
  544. }
  545. //We still don't have the bonuses (didn't returned them from cache)
  546. //Perform bonus selection
  547. auto ret = std::make_shared<BonusList>();
  548. cachedBonuses.getBonuses(*ret, selector, limit);
  549. // Save the results in the cache
  550. if(cachingStr != "")
  551. cachedRequests[cachingStr] = ret;
  552. return ret;
  553. }
  554. else
  555. {
  556. return getAllBonusesWithoutCaching(selector, limit, root);
  557. }
  558. }
  559. const TBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  560. {
  561. auto ret = std::make_shared<BonusList>();
  562. // Get bonus results without caching enabled.
  563. BonusList beforeLimiting, afterLimiting;
  564. getAllBonusesRec(beforeLimiting);
  565. beforeLimiting.eliminateDuplicates();
  566. if(!root || root == this)
  567. {
  568. limitBonuses(beforeLimiting, afterLimiting);
  569. afterLimiting.getBonuses(*ret, selector, limit);
  570. }
  571. else if(root)
  572. {
  573. //We want to limit our query against an external node. We get all its bonuses,
  574. // add the ones we're considering and see if they're cut out by limiters
  575. BonusList rootBonuses, limitedRootBonuses;
  576. getAllBonusesRec(rootBonuses);
  577. for(auto b : beforeLimiting)
  578. rootBonuses.push_back(b);
  579. rootBonuses.eliminateDuplicates();
  580. root->limitBonuses(rootBonuses, limitedRootBonuses);
  581. for(auto b : beforeLimiting)
  582. if(vstd::contains(limitedRootBonuses, b))
  583. afterLimiting.push_back(b);
  584. afterLimiting.getBonuses(*ret, selector, limit);
  585. }
  586. return ret;
  587. }
  588. CBonusSystemNode::CBonusSystemNode()
  589. : bonuses(true),
  590. exportedBonuses(true),
  591. nodeType(UNKNOWN),
  592. cachedLast(0)
  593. {
  594. }
  595. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType)
  596. : bonuses(true),
  597. exportedBonuses(true),
  598. nodeType(NodeType),
  599. cachedLast(0)
  600. {
  601. }
  602. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other):
  603. bonuses(std::move(other.bonuses)),
  604. exportedBonuses(std::move(other.exportedBonuses)),
  605. nodeType(other.nodeType),
  606. description(other.description),
  607. cachedLast(0)
  608. {
  609. std::swap(parents, other.parents);
  610. std::swap(children, other.children);
  611. //fixing bonus tree without recalculation
  612. for(CBonusSystemNode * n : parents)
  613. {
  614. n->children -= &other;
  615. n->children.push_back(this);
  616. }
  617. for(CBonusSystemNode * n : children)
  618. {
  619. n->parents -= &other;
  620. n->parents.push_back(this);
  621. }
  622. //cache ignored
  623. //cachedBonuses
  624. //cachedRequests
  625. }
  626. CBonusSystemNode::~CBonusSystemNode()
  627. {
  628. detachFromAll();
  629. if(children.size())
  630. {
  631. while(children.size())
  632. children.front()->detachFrom(this);
  633. }
  634. }
  635. void CBonusSystemNode::attachTo(CBonusSystemNode *parent)
  636. {
  637. assert(!vstd::contains(parents, parent));
  638. parents.push_back(parent);
  639. if(parent->actsAsBonusSourceOnly())
  640. parent->newRedDescendant(this);
  641. else
  642. newRedDescendant(parent);
  643. parent->newChildAttached(this);
  644. CBonusSystemNode::treeHasChanged();
  645. }
  646. void CBonusSystemNode::detachFrom(CBonusSystemNode *parent)
  647. {
  648. assert(vstd::contains(parents, parent));
  649. if(parent->actsAsBonusSourceOnly())
  650. parent->removedRedDescendant(this);
  651. else
  652. removedRedDescendant(parent);
  653. parents -= parent;
  654. parent->childDetached(this);
  655. CBonusSystemNode::treeHasChanged();
  656. }
  657. void CBonusSystemNode::popBonuses(const CSelector &s)
  658. {
  659. BonusList bl;
  660. exportedBonuses.getBonuses(bl, s, Selector::all);
  661. for(auto b : bl)
  662. removeBonus(b);
  663. for(CBonusSystemNode *child : children)
  664. child->popBonuses(s);
  665. }
  666. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  667. {
  668. BonusList bl;
  669. exportedBonuses.getBonuses(bl, s, Selector::all);
  670. for(auto b : bl)
  671. {
  672. b->turnsRemain--;
  673. if(b->turnsRemain <= 0)
  674. removeBonus(b);
  675. }
  676. for(CBonusSystemNode *child : children)
  677. child->reduceBonusDurations(s);
  678. }
  679. void CBonusSystemNode::updateBonuses()
  680. {
  681. bool updated = bonuses.updateBonuses(*this);
  682. updated = exportedBonuses.updateBonuses(*this) || updated;
  683. if(updated)
  684. treeHasChanged();
  685. }
  686. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  687. {
  688. //turnsRemain shouldn't be zero for following durations
  689. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  690. {
  691. assert(b->turnsRemain);
  692. }
  693. assert(!vstd::contains(exportedBonuses, b));
  694. exportedBonuses.push_back(b);
  695. exportBonus(b);
  696. if(b->updater)
  697. b->updater->update(*b, *this);
  698. CBonusSystemNode::treeHasChanged();
  699. }
  700. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  701. {
  702. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  703. if(bonus)
  704. bonus->val += b->val;
  705. else
  706. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  707. }
  708. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  709. {
  710. exportedBonuses -= b;
  711. if(b->propagator)
  712. unpropagateBonus(b);
  713. else
  714. bonuses -= b;
  715. CBonusSystemNode::treeHasChanged();
  716. }
  717. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  718. {
  719. switch(nodeType)
  720. {
  721. case CREATURE:
  722. case ARTIFACT:
  723. case ARTIFACT_INSTANCE:
  724. return true;
  725. default:
  726. return false;
  727. }
  728. }
  729. void CBonusSystemNode::propagateBonus(std::shared_ptr<Bonus> b)
  730. {
  731. if(b->propagator->shouldBeAttached(this))
  732. {
  733. bonuses.push_back(b);
  734. logBonus->trace("#$# %s #propagated to# %s", b->Description(), nodeName());
  735. }
  736. FOREACH_RED_CHILD(child)
  737. child->propagateBonus(b);
  738. }
  739. void CBonusSystemNode::unpropagateBonus(std::shared_ptr<Bonus> b)
  740. {
  741. if(b->propagator->shouldBeAttached(this))
  742. {
  743. bonuses -= b;
  744. while(vstd::contains(bonuses, b))
  745. {
  746. logBonus->error("Bonus was duplicated (%s) at %s", b->Description(), nodeName());
  747. bonuses -= b;
  748. }
  749. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  750. }
  751. FOREACH_RED_CHILD(child)
  752. child->unpropagateBonus(b);
  753. }
  754. void CBonusSystemNode::newChildAttached(CBonusSystemNode *child)
  755. {
  756. assert(!vstd::contains(children, child));
  757. children.push_back(child);
  758. }
  759. void CBonusSystemNode::childDetached(CBonusSystemNode *child)
  760. {
  761. if (vstd::contains(children, child))
  762. children -= child;
  763. else
  764. {
  765. logBonus->error("Error! %s #cannot be detached from# %s", child->nodeName(), nodeName());
  766. throw std::runtime_error("internal error");
  767. }
  768. }
  769. void CBonusSystemNode::detachFromAll()
  770. {
  771. while(parents.size())
  772. detachFrom(parents.front());
  773. }
  774. bool CBonusSystemNode::isIndependentNode() const
  775. {
  776. return parents.empty() && children.empty();
  777. }
  778. std::string CBonusSystemNode::nodeName() const
  779. {
  780. return description.size()
  781. ? description
  782. : std::string("Bonus system node of type ") + typeid(*this).name();
  783. }
  784. void CBonusSystemNode::deserializationFix()
  785. {
  786. exportBonuses();
  787. }
  788. void CBonusSystemNode::getRedParents(TNodes &out)
  789. {
  790. FOREACH_PARENT(pname)
  791. {
  792. if(pname->actsAsBonusSourceOnly())
  793. {
  794. out.insert(pname);
  795. }
  796. }
  797. if(!actsAsBonusSourceOnly())
  798. {
  799. for(CBonusSystemNode *child : children)
  800. {
  801. out.insert(child);
  802. }
  803. }
  804. }
  805. void CBonusSystemNode::getRedChildren(TNodes &out)
  806. {
  807. FOREACH_PARENT(pname)
  808. {
  809. if(!pname->actsAsBonusSourceOnly())
  810. {
  811. out.insert(pname);
  812. }
  813. }
  814. if(actsAsBonusSourceOnly())
  815. {
  816. for(CBonusSystemNode *child : children)
  817. {
  818. out.insert(child);
  819. }
  820. }
  821. }
  822. void CBonusSystemNode::newRedDescendant(CBonusSystemNode *descendant)
  823. {
  824. for(auto b : exportedBonuses)
  825. if(b->propagator)
  826. descendant->propagateBonus(b);
  827. FOREACH_RED_PARENT(parent)
  828. parent->newRedDescendant(descendant);
  829. }
  830. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode *descendant)
  831. {
  832. for(auto b : exportedBonuses)
  833. if(b->propagator)
  834. descendant->unpropagateBonus(b);
  835. FOREACH_RED_PARENT(parent)
  836. parent->removedRedDescendant(descendant);
  837. }
  838. void CBonusSystemNode::getRedAncestors(TNodes &out)
  839. {
  840. getRedParents(out);
  841. FOREACH_RED_PARENT(p)
  842. p->getRedAncestors(out);
  843. }
  844. void CBonusSystemNode::getRedDescendants(TNodes &out)
  845. {
  846. getRedChildren(out);
  847. FOREACH_RED_CHILD(c)
  848. c->getRedChildren(out);
  849. }
  850. void CBonusSystemNode::exportBonus(std::shared_ptr<Bonus> b)
  851. {
  852. if(b->propagator)
  853. propagateBonus(b);
  854. else
  855. bonuses.push_back(b);
  856. CBonusSystemNode::treeHasChanged();
  857. }
  858. void CBonusSystemNode::exportBonuses()
  859. {
  860. for(auto b : exportedBonuses)
  861. exportBonus(b);
  862. }
  863. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  864. {
  865. return nodeType;
  866. }
  867. const BonusList& CBonusSystemNode::getBonusList() const
  868. {
  869. return bonuses;
  870. }
  871. const TNodesVector& CBonusSystemNode::getParentNodes() const
  872. {
  873. return parents;
  874. }
  875. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  876. {
  877. return children;
  878. }
  879. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  880. {
  881. nodeType = type;
  882. }
  883. BonusList& CBonusSystemNode::getExportedBonusList()
  884. {
  885. return exportedBonuses;
  886. }
  887. const std::string& CBonusSystemNode::getDescription() const
  888. {
  889. return description;
  890. }
  891. void CBonusSystemNode::setDescription(const std::string &description)
  892. {
  893. this->description = description;
  894. }
  895. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  896. {
  897. assert(&allBonuses != &out); //todo should it work in-place?
  898. BonusList undecided = allBonuses,
  899. &accepted = out;
  900. while(true)
  901. {
  902. int undecidedCount = undecided.size();
  903. for(int i = 0; i < undecided.size(); i++)
  904. {
  905. auto b = undecided[i];
  906. BonusLimitationContext context = {b, *this, out};
  907. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  908. if(decision == ILimiter::DISCARD)
  909. {
  910. undecided.erase(i);
  911. i--; continue;
  912. }
  913. else if(decision == ILimiter::ACCEPT)
  914. {
  915. accepted.push_back(b);
  916. undecided.erase(i);
  917. i--; continue;
  918. }
  919. else
  920. assert(decision == ILimiter::NOT_SURE);
  921. }
  922. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  923. return;
  924. }
  925. }
  926. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  927. {
  928. auto ret = std::make_shared<BonusList>();
  929. limitBonuses(allBonuses, *ret);
  930. return ret;
  931. }
  932. void CBonusSystemNode::treeHasChanged()
  933. {
  934. treeChanged++;
  935. }
  936. int64_t CBonusSystemNode::getTreeVersion() const
  937. {
  938. int64_t ret = treeChanged;
  939. return ret << 32;
  940. }
  941. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  942. {
  943. if(obj)
  944. return obj->valOfBonuses(type, subtype);
  945. return 0;
  946. }
  947. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  948. {
  949. if(obj)
  950. return obj->hasBonusOfType(type, subtype);
  951. return false;
  952. }
  953. std::string Bonus::Description() const
  954. {
  955. std::ostringstream str;
  956. if(description.empty())
  957. switch(source)
  958. {
  959. case ARTIFACT:
  960. str << VLC->arth->artifacts[sid]->Name();
  961. break;
  962. case SPELL_EFFECT:
  963. str << SpellID(sid).toSpell()->name;
  964. break;
  965. case CREATURE_ABILITY:
  966. str << VLC->creh->creatures[sid]->namePl;
  967. break;
  968. case SECONDARY_SKILL:
  969. str << VLC->skillh->skillName(sid);
  970. break;
  971. default:
  972. //todo: handle all possible sources
  973. str << "Unknown";
  974. break;
  975. }
  976. else
  977. str << description;
  978. if(val != 0)
  979. str << " " << std::showpos << val;
  980. return str.str();
  981. }
  982. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype)
  983. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  984. {
  985. additionalInfo = -1;
  986. turnsRemain = 0;
  987. valType = ADDITIVE_VALUE;
  988. effectRange = NO_LIMIT;
  989. boost::algorithm::trim(description);
  990. }
  991. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType)
  992. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  993. {
  994. additionalInfo = -1;
  995. turnsRemain = 0;
  996. effectRange = NO_LIMIT;
  997. }
  998. Bonus::Bonus()
  999. {
  1000. duration = PERMANENT;
  1001. turnsRemain = 0;
  1002. type = NONE;
  1003. subtype = -1;
  1004. additionalInfo = -1;
  1005. valType = ADDITIVE_VALUE;
  1006. effectRange = NO_LIMIT;
  1007. val = 0;
  1008. source = OTHER;
  1009. sid = 0;
  1010. }
  1011. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  1012. {
  1013. propagator = Propagator;
  1014. return this->shared_from_this();
  1015. }
  1016. namespace Selector
  1017. {
  1018. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> type(&Bonus::type);
  1019. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> subtype(&Bonus::subtype);
  1020. DLL_LINKAGE CSelectFieldEqual<si32> info(&Bonus::additionalInfo);
  1021. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> sourceType(&Bonus::source);
  1022. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> effectRange(&Bonus::effectRange);
  1023. DLL_LINKAGE CWillLastTurns turns;
  1024. DLL_LINKAGE CWillLastDays days;
  1025. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1026. {
  1027. return type(Type).And(subtype(Subtype));
  1028. }
  1029. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, si32 info)
  1030. {
  1031. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1032. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1033. .And(CSelectFieldEqual<si32>(&Bonus::additionalInfo)(info));
  1034. }
  1035. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1036. {
  1037. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1038. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1039. }
  1040. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1041. {
  1042. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1043. }
  1044. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1045. {
  1046. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1047. }
  1048. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1049. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1050. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1051. {
  1052. Bonus dummy;
  1053. dummy.type = type;
  1054. return sel(&dummy);
  1055. }
  1056. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1057. {
  1058. Bonus dummy;
  1059. dummy.type = type;
  1060. dummy.subtype = subtype;
  1061. return sel(&dummy);
  1062. }
  1063. }
  1064. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  1065. {
  1066. switch(node->getNodeType())
  1067. {
  1068. case CBonusSystemNode::STACK_BATTLE:
  1069. return static_cast<const CStack*>(node);
  1070. default:
  1071. return nullptr;
  1072. }
  1073. }
  1074. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  1075. {
  1076. switch(node->getNodeType())
  1077. {
  1078. case CBonusSystemNode::STACK_INSTANCE:
  1079. return (static_cast<const CStackInstance *>(node));
  1080. case CBonusSystemNode::STACK_BATTLE:
  1081. return (static_cast<const CStack*>(node))->base;
  1082. default:
  1083. return nullptr;
  1084. }
  1085. }
  1086. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1087. {
  1088. switch(node->getNodeType())
  1089. {
  1090. case CBonusSystemNode::CREATURE:
  1091. return (static_cast<const CCreature *>(node));
  1092. case CBonusSystemNode::STACK_BATTLE:
  1093. return (static_cast<const CStack*>(node))->type;
  1094. default:
  1095. const CStackInstance * csi = retrieveStackInstance(node);
  1096. if(csi)
  1097. return csi->type;
  1098. return nullptr;
  1099. }
  1100. }
  1101. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1102. {
  1103. for (ui32 i = 0; i < bonusList.size(); i++)
  1104. {
  1105. auto b = bonusList[i];
  1106. out << "Bonus " << i << "\n" << *b << std::endl;
  1107. }
  1108. return out;
  1109. }
  1110. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1111. {
  1112. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1113. if(i->second == bonus.type)
  1114. out << "\tType: " << i->first << " \t";
  1115. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1116. printField(val);
  1117. printField(subtype);
  1118. printField(duration);
  1119. printField(source);
  1120. printField(sid);
  1121. printField(additionalInfo);
  1122. printField(turnsRemain);
  1123. printField(valType);
  1124. printField(effectRange);
  1125. #undef printField
  1126. return out;
  1127. }
  1128. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1129. {
  1130. if (limiter)
  1131. {
  1132. //If we already have limiter list, retrieve it
  1133. auto limiterList = std::dynamic_pointer_cast<LimiterList>(limiter);
  1134. if(!limiterList)
  1135. {
  1136. //Create a new limiter list with old limiter and the new one will be pushed later
  1137. limiterList = std::make_shared<LimiterList>();
  1138. limiterList->add(limiter);
  1139. limiter = limiterList;
  1140. }
  1141. limiterList->add(Limiter);
  1142. }
  1143. else
  1144. {
  1145. limiter = Limiter;
  1146. }
  1147. return this->shared_from_this();
  1148. }
  1149. ILimiter::~ILimiter()
  1150. {
  1151. }
  1152. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1153. {
  1154. return false;
  1155. }
  1156. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1157. {
  1158. const CCreature *c = retrieveCreature(&context.node);
  1159. if(!c)
  1160. return true;
  1161. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1162. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1163. }
  1164. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature &Creature, bool IncludeUpgrades)
  1165. :creature(&Creature), includeUpgrades(IncludeUpgrades)
  1166. {
  1167. }
  1168. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1169. {
  1170. creature = nullptr;
  1171. includeUpgrades = false;
  1172. }
  1173. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1174. {
  1175. creature = VLC->creh->creatures[id];
  1176. }
  1177. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1178. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1179. {
  1180. }
  1181. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1182. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1183. {
  1184. }
  1185. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1186. {
  1187. CSelector mySelector = isSubtypeRelevant
  1188. ? Selector::typeSubtype(type, subtype)
  1189. : Selector::type(type);
  1190. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1191. if(context.alreadyAccepted.getFirst(mySelector))
  1192. return ACCEPT;
  1193. //do not accept for now but it may change if more bonuses gets included
  1194. return NOT_SURE;
  1195. }
  1196. IPropagator::~IPropagator()
  1197. {
  1198. }
  1199. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1200. {
  1201. return false;
  1202. }
  1203. CPropagatorNodeType::CPropagatorNodeType()
  1204. :nodeType(0)
  1205. {
  1206. }
  1207. CPropagatorNodeType::CPropagatorNodeType(int NodeType)
  1208. : nodeType(NodeType)
  1209. {
  1210. }
  1211. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1212. {
  1213. return nodeType == dest->getNodeType();
  1214. }
  1215. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter(int TerrainType)
  1216. : terrainType(TerrainType)
  1217. {
  1218. }
  1219. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter()
  1220. : terrainType(-1)
  1221. {
  1222. }
  1223. int CreatureNativeTerrainLimiter::limit(const BonusLimitationContext &context) const
  1224. {
  1225. const CCreature *c = retrieveCreature(&context.node);
  1226. return !c || !c->isItNativeTerrain(terrainType); //drop bonus for non-creatures or non-native residents
  1227. //TODO neutral creatues
  1228. }
  1229. CreatureFactionLimiter::CreatureFactionLimiter(int Faction)
  1230. : faction(Faction)
  1231. {
  1232. }
  1233. CreatureFactionLimiter::CreatureFactionLimiter()
  1234. : faction(-1)
  1235. {
  1236. }
  1237. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1238. {
  1239. const CCreature *c = retrieveCreature(&context.node);
  1240. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1241. }
  1242. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1243. : alignment(-1)
  1244. {
  1245. }
  1246. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1247. : alignment(Alignment)
  1248. {
  1249. }
  1250. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1251. {
  1252. const CCreature *c = retrieveCreature(&context.node);
  1253. if(!c)
  1254. return true;
  1255. switch(alignment)
  1256. {
  1257. case EAlignment::GOOD:
  1258. return !c->isGood(); //if not good -> return true (drop bonus)
  1259. case EAlignment::NEUTRAL:
  1260. return c->isEvil() || c->isGood();
  1261. case EAlignment::EVIL:
  1262. return !c->isEvil();
  1263. default:
  1264. logBonus->warn("Warning: illegal alignment in limiter!");
  1265. return true;
  1266. }
  1267. }
  1268. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1269. :minRank(Min), maxRank(Max)
  1270. {
  1271. }
  1272. RankRangeLimiter::RankRangeLimiter()
  1273. {
  1274. minRank = maxRank = -1;
  1275. }
  1276. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1277. {
  1278. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1279. if(csi)
  1280. {
  1281. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1282. return true;
  1283. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1284. }
  1285. return true;
  1286. }
  1287. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1288. {
  1289. const CStack * s = retrieveStackBattle(&context.node);
  1290. if(s)
  1291. return s->owner != owner;
  1292. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1293. if(csi && csi->armyObj)
  1294. return csi->armyObj->tempOwner != owner;
  1295. return true;
  1296. }
  1297. StackOwnerLimiter::StackOwnerLimiter()
  1298. : owner(-1)
  1299. {
  1300. }
  1301. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1302. : owner(Owner)
  1303. {
  1304. }
  1305. int LimiterList::limit( const BonusLimitationContext &context ) const
  1306. {
  1307. bool wasntSure = false;
  1308. for(auto limiter : limiters)
  1309. {
  1310. auto result = limiter->limit(context);
  1311. if(result == ILimiter::DISCARD)
  1312. return result;
  1313. if(result == ILimiter::NOT_SURE)
  1314. wasntSure = true;
  1315. }
  1316. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1317. }
  1318. void LimiterList::add( TLimiterPtr limiter )
  1319. {
  1320. limiters.push_back(limiter);
  1321. }
  1322. // Updaters
  1323. IUpdater::~IUpdater()
  1324. {
  1325. }
  1326. ScalingUpdater::ScalingUpdater() : valPer20(0), stepSize(1)
  1327. {
  1328. }
  1329. ScalingUpdater::ScalingUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  1330. {
  1331. }
  1332. bool ScalingUpdater::update(Bonus & b, const CBonusSystemNode & context) const
  1333. {
  1334. if(context.getNodeType() == CBonusSystemNode::HERO)
  1335. {
  1336. int level = static_cast<const CGHeroInstance &>(context).level;
  1337. int steps = stepSize ? level / stepSize : level;
  1338. //rounding follows format for HMM3 creature specialty bonus
  1339. int newVal = (valPer20 * steps + 19) / 20;
  1340. if(b.val != newVal)
  1341. {
  1342. b.val = newVal;
  1343. return true;
  1344. }
  1345. }
  1346. return false;
  1347. }
  1348. std::shared_ptr<Bonus> Bonus::addUpdater(TUpdaterPtr Updater)
  1349. {
  1350. updater = Updater;
  1351. return this->shared_from_this();
  1352. }