HeroBonus.cpp 39 KB

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