2
0

HeroBonus.cpp 42 KB

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