HeroBonus.cpp 38 KB

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