HeroBonus.cpp 39 KB

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