HeroBonus.cpp 38 KB

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