HeroBonus.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588
  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 "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::incrementTreeChangedNum();
  237. }
  238. std::vector<Bonus*>::iterator BonusList::erase(const int position)
  239. {
  240. if (belongsToTree)
  241. CBonusSystemNode::incrementTreeChangedNum();
  242. return bonuses.erase(bonuses.begin() + position);
  243. }
  244. void BonusList::clear()
  245. {
  246. bonuses.clear();
  247. if (belongsToTree)
  248. CBonusSystemNode::incrementTreeChangedNum();
  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::incrementTreeChangedNum();
  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::incrementTreeChangedNum();
  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::incrementTreeChangedNum();
  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::treeChanged++;
  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::treeChanged++;
  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::treeChanged++;
  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::treeChanged++;
  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::treeChanged++;
  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::incrementTreeChangedNum()
  880. {
  881. treeChanged++;
  882. }
  883. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  884. {
  885. assert(&allBonuses != &out); //todo should it work in-place?
  886. BonusList undecided = allBonuses,
  887. &accepted = out;
  888. while(true)
  889. {
  890. int undecidedCount = undecided.size();
  891. for(int i = 0; i < undecided.size(); i++)
  892. {
  893. Bonus *b = undecided[i];
  894. BonusLimitationContext context = {b, *this, out};
  895. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  896. if(decision == ILimiter::DISCARD)
  897. {
  898. undecided.erase(i);
  899. i--; continue;
  900. }
  901. else if(decision == ILimiter::ACCEPT)
  902. {
  903. accepted.push_back(b);
  904. undecided.erase(i);
  905. i--; continue;
  906. }
  907. else
  908. assert(decision == ILimiter::NOT_SURE);
  909. }
  910. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  911. return;
  912. }
  913. }
  914. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  915. {
  916. auto ret = make_shared<BonusList>();
  917. limitBonuses(allBonuses, *ret);
  918. return ret;
  919. }
  920. void CBonusSystemNode::treeHasChanged()
  921. {
  922. treeChanged++;
  923. }
  924. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype /*= -1*/)
  925. {
  926. if(obj)
  927. return obj->valOfBonuses(type, subtype);
  928. return 0;
  929. }
  930. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype /*= -1*/)
  931. {
  932. if(obj)
  933. return obj->hasBonusOfType(type, subtype);
  934. return false;
  935. }
  936. void NBonus::getModifiersWDescr(const CBonusSystemNode *obj, TModDescr &out, Bonus::BonusType type, int subtype /*= -1 */)
  937. {
  938. if(obj)
  939. return obj->getModifiersWDescr(out, type, subtype);
  940. }
  941. int NBonus::getCount(const CBonusSystemNode *obj, Bonus::BonusSource from, int id)
  942. {
  943. if(obj)
  944. return obj->getBonusesCount(from, id);
  945. return 0;
  946. }
  947. const CSpell * Bonus::sourceSpell() const
  948. {
  949. if(source == SPELL_EFFECT)
  950. return SpellID(sid).toSpell();
  951. return nullptr;
  952. }
  953. std::string Bonus::Description() const
  954. {
  955. if(description.size())
  956. return description;
  957. std::ostringstream str;
  958. str << std::showpos << val << " ";
  959. switch(source)
  960. {
  961. case ARTIFACT:
  962. str << VLC->arth->artifacts[sid]->Name();
  963. break;;
  964. case SPELL_EFFECT:
  965. str << SpellID(sid).toSpell()->name;
  966. break;
  967. case CREATURE_ABILITY:
  968. str << VLC->creh->creatures[sid]->namePl;
  969. break;
  970. case SECONDARY_SKILL:
  971. str << VLC->generaltexth->skillName[sid]/* << " secondary skill"*/;
  972. break;
  973. }
  974. return str.str();
  975. }
  976. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype/*=-1*/)
  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/*=-1*/, ValueType ValType /*= ADDITIVE_VALUE*/)
  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. }
  1004. Bonus::~Bonus()
  1005. {
  1006. }
  1007. Bonus * Bonus::addPropagator(TPropagatorPtr Propagator)
  1008. {
  1009. propagator = Propagator;
  1010. return this;
  1011. }
  1012. namespace Selector
  1013. {
  1014. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> type(&Bonus::type);
  1015. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> subtype(&Bonus::subtype);
  1016. DLL_LINKAGE CSelectFieldEqual<si32> info(&Bonus::additionalInfo);
  1017. DLL_LINKAGE CSelectFieldEqual<ui16> duration(&Bonus::duration);
  1018. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> sourceType(&Bonus::source);
  1019. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> effectRange(&Bonus::effectRange);
  1020. DLL_LINKAGE CWillLastTurns turns;
  1021. DLL_LINKAGE CSelectFieldAny<Bonus::LimitEffect> anyRange(&Bonus::effectRange);
  1022. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1023. {
  1024. return type(Type).And(subtype(Subtype));
  1025. }
  1026. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, si32 info)
  1027. {
  1028. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1029. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1030. .And(CSelectFieldEqual<si32>(&Bonus::additionalInfo)(info));
  1031. }
  1032. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1033. {
  1034. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1035. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1036. }
  1037. CSelector DLL_EXPORT durationType(ui16 duration)
  1038. {
  1039. return CSelectFieldEqual<ui16>(&Bonus::duration)(duration);
  1040. }
  1041. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1042. {
  1043. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1044. }
  1045. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1046. {
  1047. Bonus dummy;
  1048. dummy.type = type;
  1049. return sel(&dummy);
  1050. }
  1051. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1052. {
  1053. Bonus dummy;
  1054. dummy.type = type;
  1055. dummy.subtype = subtype;
  1056. return sel(&dummy);
  1057. }
  1058. bool DLL_LINKAGE positiveSpellEffects(const Bonus *b)
  1059. {
  1060. if(b->source == Bonus::SPELL_EFFECT)
  1061. {
  1062. CSpell *sp = SpellID(b->sid).toSpell();
  1063. return sp->isPositive();
  1064. }
  1065. return false; //not a spell effect
  1066. }
  1067. }
  1068. const CStack * retreiveStackBattle(const CBonusSystemNode *node)
  1069. {
  1070. switch(node->getNodeType())
  1071. {
  1072. case CBonusSystemNode::STACK_BATTLE:
  1073. return static_cast<const CStack*>(node);
  1074. default:
  1075. return nullptr;
  1076. }
  1077. }
  1078. const CStackInstance * retreiveStackInstance(const CBonusSystemNode *node)
  1079. {
  1080. switch(node->getNodeType())
  1081. {
  1082. case CBonusSystemNode::STACK_INSTANCE:
  1083. return (static_cast<const CStackInstance *>(node));
  1084. case CBonusSystemNode::STACK_BATTLE:
  1085. return (static_cast<const CStack*>(node))->base;
  1086. default:
  1087. return nullptr;
  1088. }
  1089. }
  1090. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1091. {
  1092. switch(node->getNodeType())
  1093. {
  1094. case CBonusSystemNode::CREATURE:
  1095. return (static_cast<const CCreature *>(node));
  1096. default:
  1097. const CStackInstance *csi = retreiveStackInstance(node);
  1098. if(csi)
  1099. return csi->type;
  1100. return nullptr;
  1101. }
  1102. }
  1103. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1104. {
  1105. for (ui32 i = 0; i < bonusList.size(); i++)
  1106. {
  1107. Bonus *b = bonusList[i];
  1108. out << "Bonus " << i << "\n" << *b << std::endl;
  1109. }
  1110. return out;
  1111. }
  1112. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1113. {
  1114. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1115. if(i->second == bonus.type)
  1116. out << "\tType: " << i->first << " \t";
  1117. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1118. printField(val);
  1119. printField(subtype);
  1120. printField(duration);
  1121. printField(source);
  1122. printField(sid);
  1123. printField(additionalInfo);
  1124. printField(turnsRemain);
  1125. printField(valType);
  1126. printField(effectRange);
  1127. #undef printField
  1128. return out;
  1129. }
  1130. Bonus * Bonus::addLimiter(TLimiterPtr Limiter)
  1131. {
  1132. if (limiter)
  1133. {
  1134. //If we already have limiter list, retrieve it
  1135. auto limiterList = std::dynamic_pointer_cast<LimiterList>(limiter);
  1136. if(!limiterList)
  1137. {
  1138. //Create a new limiter list with old limiter and the new one will be pushed later
  1139. limiterList = make_shared<LimiterList>();
  1140. limiterList->add(limiter);
  1141. limiter = limiterList;
  1142. }
  1143. limiterList->add(Limiter);
  1144. }
  1145. else
  1146. {
  1147. limiter = Limiter;
  1148. }
  1149. return this;
  1150. }
  1151. ILimiter::~ILimiter()
  1152. {
  1153. }
  1154. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1155. {
  1156. return false;
  1157. }
  1158. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1159. {
  1160. const CCreature *c = retrieveCreature(&context.node);
  1161. if(!c)
  1162. return true;
  1163. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1164. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1165. }
  1166. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature &Creature, bool IncludeUpgrades /*= true*/)
  1167. :creature(&Creature), includeUpgrades(IncludeUpgrades)
  1168. {
  1169. }
  1170. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1171. {
  1172. creature = nullptr;
  1173. includeUpgrades = false;
  1174. }
  1175. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1176. {
  1177. creature = VLC->creh->creatures[id];
  1178. }
  1179. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1180. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1181. {
  1182. }
  1183. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1184. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1185. {
  1186. }
  1187. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1188. {
  1189. CSelector mySelector = isSubtypeRelevant
  1190. ? Selector::typeSubtype(type, subtype)
  1191. : Selector::type(type);
  1192. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1193. if(context.alreadyAccepted.getFirst(mySelector))
  1194. return ACCEPT;
  1195. //do not accept for now but it may change if more bonuses gets included
  1196. return NOT_SURE;
  1197. }
  1198. IPropagator::~IPropagator()
  1199. {
  1200. }
  1201. // CBonusSystemNode * IPropagator::getDestNode(CBonusSystemNode *source, CBonusSystemNode *redParent, CBonusSystemNode *redChild)
  1202. // {
  1203. // return source;
  1204. // }
  1205. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1206. {
  1207. return false;
  1208. }
  1209. // CBonusSystemNode * CPropagatorNodeType::getDestNode(CBonusSystemNode *source, CBonusSystemNode *redParent, CBonusSystemNode *redChild)
  1210. // {
  1211. // return nullptr;
  1212. // }
  1213. CPropagatorNodeType::CPropagatorNodeType()
  1214. {
  1215. }
  1216. CPropagatorNodeType::CPropagatorNodeType(int NodeType)
  1217. : nodeType(NodeType)
  1218. {
  1219. }
  1220. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1221. {
  1222. return nodeType == dest->getNodeType();
  1223. }
  1224. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter(int TerrainType)
  1225. : terrainType(TerrainType)
  1226. {
  1227. }
  1228. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter()
  1229. {
  1230. }
  1231. int CreatureNativeTerrainLimiter::limit(const BonusLimitationContext &context) const
  1232. {
  1233. const CCreature *c = retrieveCreature(&context.node);
  1234. return !c || !c->isItNativeTerrain(terrainType); //drop bonus for non-creatures or non-native residents
  1235. //TODO neutral creatues
  1236. }
  1237. CreatureFactionLimiter::CreatureFactionLimiter(int Faction)
  1238. : faction(Faction)
  1239. {
  1240. }
  1241. CreatureFactionLimiter::CreatureFactionLimiter()
  1242. {
  1243. }
  1244. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1245. {
  1246. const CCreature *c = retrieveCreature(&context.node);
  1247. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1248. }
  1249. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1250. {
  1251. }
  1252. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1253. : alignment(Alignment)
  1254. {
  1255. }
  1256. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1257. {
  1258. const CCreature *c = retrieveCreature(&context.node);
  1259. if(!c)
  1260. return true;
  1261. switch(alignment)
  1262. {
  1263. case EAlignment::GOOD:
  1264. return !c->isGood(); //if not good -> return true (drop bonus)
  1265. case EAlignment::NEUTRAL:
  1266. return c->isEvil() || c->isGood();
  1267. case EAlignment::EVIL:
  1268. return !c->isEvil();
  1269. default:
  1270. logBonus->warnStream() << "Warning: illegal alignment in limiter!";
  1271. return true;
  1272. }
  1273. }
  1274. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1275. :minRank(Min), maxRank(Max)
  1276. {
  1277. }
  1278. RankRangeLimiter::RankRangeLimiter()
  1279. {
  1280. minRank = maxRank = -1;
  1281. }
  1282. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1283. {
  1284. const CStackInstance *csi = retreiveStackInstance(&context.node);
  1285. if(csi)
  1286. {
  1287. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1288. return true;
  1289. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1290. }
  1291. return true;
  1292. }
  1293. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1294. {
  1295. const CStack *s = retreiveStackBattle(&context.node);
  1296. if(s)
  1297. return s->owner != owner;
  1298. const CStackInstance *csi = retreiveStackInstance(&context.node);
  1299. if(csi && csi->armyObj)
  1300. return csi->armyObj->tempOwner != owner;
  1301. return true;
  1302. }
  1303. StackOwnerLimiter::StackOwnerLimiter()
  1304. : owner(-1)
  1305. {
  1306. }
  1307. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1308. : owner(Owner)
  1309. {
  1310. }
  1311. // int Bonus::limit(const BonusLimitationContext &context) const
  1312. // 1162 {
  1313. // 1163 if (limiter)
  1314. // 1164 return limiter->callNext(context);
  1315. // 1165 else
  1316. // 1166 return ILimiter::ACCEPT; //accept if there's no limiter
  1317. // 1167 }
  1318. //1168
  1319. int LimiterList::limit( const BonusLimitationContext &context ) const
  1320. {
  1321. bool wasntSure = false;
  1322. for(auto limiter : limiters)
  1323. {
  1324. auto result = limiter->limit(context);
  1325. if(result == ILimiter::DISCARD)
  1326. return result;
  1327. if(result == ILimiter::NOT_SURE)
  1328. wasntSure = true;
  1329. }
  1330. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1331. }
  1332. void LimiterList::add( TLimiterPtr limiter )
  1333. {
  1334. limiters.push_back(limiter);
  1335. }