HeroBonus.cpp 39 KB

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