HeroBonus.cpp 43 KB

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