HeroBonus.cpp 37 KB

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