HeroBonus.cpp 37 KB

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