HeroBonus.cpp 45 KB

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