HeroBonus.cpp 39 KB

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