HeroBonus.cpp 39 KB

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