HeroBonus.cpp 39 KB

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