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