HeroBonus.cpp 39 KB

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