HeroBonus.cpp 43 KB

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