HeroBonus.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  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. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  986. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  987. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  988. {
  989. Bonus dummy;
  990. dummy.type = type;
  991. return sel(&dummy);
  992. }
  993. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  994. {
  995. Bonus dummy;
  996. dummy.type = type;
  997. dummy.subtype = subtype;
  998. return sel(&dummy);
  999. }
  1000. }
  1001. const CStack * retreiveStackBattle(const CBonusSystemNode *node)
  1002. {
  1003. switch(node->getNodeType())
  1004. {
  1005. case CBonusSystemNode::STACK_BATTLE:
  1006. return static_cast<const CStack*>(node);
  1007. default:
  1008. return nullptr;
  1009. }
  1010. }
  1011. const CStackInstance * retreiveStackInstance(const CBonusSystemNode *node)
  1012. {
  1013. switch(node->getNodeType())
  1014. {
  1015. case CBonusSystemNode::STACK_INSTANCE:
  1016. return (static_cast<const CStackInstance *>(node));
  1017. case CBonusSystemNode::STACK_BATTLE:
  1018. return (static_cast<const CStack*>(node))->base;
  1019. default:
  1020. return nullptr;
  1021. }
  1022. }
  1023. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1024. {
  1025. switch(node->getNodeType())
  1026. {
  1027. case CBonusSystemNode::CREATURE:
  1028. return (static_cast<const CCreature *>(node));
  1029. default:
  1030. const CStackInstance *csi = retreiveStackInstance(node);
  1031. if(csi)
  1032. return csi->type;
  1033. return nullptr;
  1034. }
  1035. }
  1036. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1037. {
  1038. for (ui32 i = 0; i < bonusList.size(); i++)
  1039. {
  1040. auto b = bonusList[i];
  1041. out << "Bonus " << i << "\n" << *b << std::endl;
  1042. }
  1043. return out;
  1044. }
  1045. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1046. {
  1047. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1048. if(i->second == bonus.type)
  1049. out << "\tType: " << i->first << " \t";
  1050. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1051. printField(val);
  1052. printField(subtype);
  1053. printField(duration);
  1054. printField(source);
  1055. printField(sid);
  1056. printField(additionalInfo);
  1057. printField(turnsRemain);
  1058. printField(valType);
  1059. printField(effectRange);
  1060. #undef printField
  1061. return out;
  1062. }
  1063. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1064. {
  1065. if (limiter)
  1066. {
  1067. //If we already have limiter list, retrieve it
  1068. auto limiterList = std::dynamic_pointer_cast<LimiterList>(limiter);
  1069. if(!limiterList)
  1070. {
  1071. //Create a new limiter list with old limiter and the new one will be pushed later
  1072. limiterList = std::make_shared<LimiterList>();
  1073. limiterList->add(limiter);
  1074. limiter = limiterList;
  1075. }
  1076. limiterList->add(Limiter);
  1077. }
  1078. else
  1079. {
  1080. limiter = Limiter;
  1081. }
  1082. return this->shared_from_this();
  1083. }
  1084. ILimiter::~ILimiter()
  1085. {
  1086. }
  1087. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1088. {
  1089. return false;
  1090. }
  1091. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1092. {
  1093. const CCreature *c = retrieveCreature(&context.node);
  1094. if(!c)
  1095. return true;
  1096. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1097. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1098. }
  1099. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature &Creature, bool IncludeUpgrades)
  1100. :creature(&Creature), includeUpgrades(IncludeUpgrades)
  1101. {
  1102. }
  1103. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1104. {
  1105. creature = nullptr;
  1106. includeUpgrades = false;
  1107. }
  1108. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1109. {
  1110. creature = VLC->creh->creatures[id];
  1111. }
  1112. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1113. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1114. {
  1115. }
  1116. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1117. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1118. {
  1119. }
  1120. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1121. {
  1122. CSelector mySelector = isSubtypeRelevant
  1123. ? Selector::typeSubtype(type, subtype)
  1124. : Selector::type(type);
  1125. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1126. if(context.alreadyAccepted.getFirst(mySelector))
  1127. return ACCEPT;
  1128. //do not accept for now but it may change if more bonuses gets included
  1129. return NOT_SURE;
  1130. }
  1131. IPropagator::~IPropagator()
  1132. {
  1133. }
  1134. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1135. {
  1136. return false;
  1137. }
  1138. CPropagatorNodeType::CPropagatorNodeType()
  1139. :nodeType(0)
  1140. {
  1141. }
  1142. CPropagatorNodeType::CPropagatorNodeType(int NodeType)
  1143. : nodeType(NodeType)
  1144. {
  1145. }
  1146. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1147. {
  1148. return nodeType == dest->getNodeType();
  1149. }
  1150. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter(int TerrainType)
  1151. : terrainType(TerrainType)
  1152. {
  1153. }
  1154. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter()
  1155. : terrainType(-1)
  1156. {
  1157. }
  1158. int CreatureNativeTerrainLimiter::limit(const BonusLimitationContext &context) const
  1159. {
  1160. const CCreature *c = retrieveCreature(&context.node);
  1161. return !c || !c->isItNativeTerrain(terrainType); //drop bonus for non-creatures or non-native residents
  1162. //TODO neutral creatues
  1163. }
  1164. CreatureFactionLimiter::CreatureFactionLimiter(int Faction)
  1165. : faction(Faction)
  1166. {
  1167. }
  1168. CreatureFactionLimiter::CreatureFactionLimiter()
  1169. : faction(-1)
  1170. {
  1171. }
  1172. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1173. {
  1174. const CCreature *c = retrieveCreature(&context.node);
  1175. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1176. }
  1177. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1178. : alignment(-1)
  1179. {
  1180. }
  1181. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1182. : alignment(Alignment)
  1183. {
  1184. }
  1185. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1186. {
  1187. const CCreature *c = retrieveCreature(&context.node);
  1188. if(!c)
  1189. return true;
  1190. switch(alignment)
  1191. {
  1192. case EAlignment::GOOD:
  1193. return !c->isGood(); //if not good -> return true (drop bonus)
  1194. case EAlignment::NEUTRAL:
  1195. return c->isEvil() || c->isGood();
  1196. case EAlignment::EVIL:
  1197. return !c->isEvil();
  1198. default:
  1199. logBonus->warn("Warning: illegal alignment in limiter!");
  1200. return true;
  1201. }
  1202. }
  1203. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1204. :minRank(Min), maxRank(Max)
  1205. {
  1206. }
  1207. RankRangeLimiter::RankRangeLimiter()
  1208. {
  1209. minRank = maxRank = -1;
  1210. }
  1211. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1212. {
  1213. const CStackInstance *csi = retreiveStackInstance(&context.node);
  1214. if(csi)
  1215. {
  1216. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1217. return true;
  1218. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1219. }
  1220. return true;
  1221. }
  1222. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1223. {
  1224. const CStack *s = retreiveStackBattle(&context.node);
  1225. if(s)
  1226. return s->owner != owner;
  1227. const CStackInstance *csi = retreiveStackInstance(&context.node);
  1228. if(csi && csi->armyObj)
  1229. return csi->armyObj->tempOwner != owner;
  1230. return true;
  1231. }
  1232. StackOwnerLimiter::StackOwnerLimiter()
  1233. : owner(-1)
  1234. {
  1235. }
  1236. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1237. : owner(Owner)
  1238. {
  1239. }
  1240. int LimiterList::limit( const BonusLimitationContext &context ) const
  1241. {
  1242. bool wasntSure = false;
  1243. for(auto limiter : limiters)
  1244. {
  1245. auto result = limiter->limit(context);
  1246. if(result == ILimiter::DISCARD)
  1247. return result;
  1248. if(result == ILimiter::NOT_SURE)
  1249. wasntSure = true;
  1250. }
  1251. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1252. }
  1253. void LimiterList::add( TLimiterPtr limiter )
  1254. {
  1255. limiters.push_back(limiter);
  1256. }