HeroBonus.cpp 39 KB

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