HeroBonus.cpp 48 KB

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