HeroBonus.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378
  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 "CTownHandler.h"
  18. #include "CGeneralTextHandler.h"
  19. #include "CSkillHandler.h"
  20. #include "CStack.h"
  21. #include "CArtHandler.h"
  22. #include "CModHandler.h"
  23. #include "StringConstants.h"
  24. #include "battle/BattleInfo.h"
  25. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  26. #define FOREACH_CPARENT(pname) TCNodes lparents; getParents(lparents); for(const CBonusSystemNode *pname : lparents)
  27. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  28. #define FOREACH_RED_PARENT(pname) TNodes lparents; getRedParents(lparents); for(CBonusSystemNode *pname : lparents)
  29. #define BONUS_NAME(x) { #x, Bonus::x },
  30. const std::map<std::string, Bonus::BonusType> bonusNameMap = { BONUS_LIST };
  31. #undef BONUS_NAME
  32. #define BONUS_VALUE(x) { #x, Bonus::x },
  33. const std::map<std::string, Bonus::ValueType> bonusValueMap = { BONUS_VALUE_LIST };
  34. #undef BONUS_VALUE
  35. #define BONUS_SOURCE(x) { #x, Bonus::x },
  36. const std::map<std::string, Bonus::BonusSource> bonusSourceMap = { BONUS_SOURCE_LIST };
  37. #undef BONUS_SOURCE
  38. #define BONUS_ITEM(x) { #x, Bonus::x },
  39. const std::map<std::string, ui16> bonusDurationMap =
  40. {
  41. BONUS_ITEM(PERMANENT)
  42. BONUS_ITEM(ONE_BATTLE)
  43. BONUS_ITEM(ONE_DAY)
  44. BONUS_ITEM(ONE_WEEK)
  45. BONUS_ITEM(N_TURNS)
  46. BONUS_ITEM(N_DAYS)
  47. BONUS_ITEM(UNTIL_BEING_ATTACKED)
  48. BONUS_ITEM(UNTIL_ATTACK)
  49. BONUS_ITEM(STACK_GETS_TURN)
  50. BONUS_ITEM(COMMANDER_KILLED)
  51. { "UNITL_BEING_ATTACKED", Bonus::UNTIL_BEING_ATTACKED }//typo, but used in some mods
  52. };
  53. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  54. {
  55. BONUS_ITEM(NO_LIMIT)
  56. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  57. BONUS_ITEM(ONLY_MELEE_FIGHT)
  58. BONUS_ITEM(ONLY_ENEMY_ARMY)
  59. };
  60. const std::map<std::string, TLimiterPtr> bonusLimiterMap =
  61. {
  62. {"SHOOTER_ONLY", std::make_shared<HasAnotherBonusLimiter>(Bonus::SHOOTER)},
  63. {"DRAGON_NATURE", std::make_shared<HasAnotherBonusLimiter>(Bonus::DRAGON_NATURE)},
  64. {"IS_UNDEAD", std::make_shared<HasAnotherBonusLimiter>(Bonus::UNDEAD)},
  65. {"CREATURE_NATIVE_TERRAIN", std::make_shared<CreatureTerrainLimiter>()},
  66. {"CREATURE_FACTION", std::make_shared<CreatureFactionLimiter>()}
  67. };
  68. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  69. {
  70. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  71. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  72. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  73. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  74. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  75. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)},
  76. {"ALL_CREATURES", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::ALL_CREATURES)}
  77. }; //untested
  78. const std::map<std::string, TUpdaterPtr> bonusUpdaterMap =
  79. {
  80. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>()},
  81. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>()}
  82. };
  83. ///CBonusProxy
  84. CBonusProxy::CBonusProxy(const IBonusBearer * Target, CSelector Selector)
  85. : bonusListCachedLast(0),
  86. target(Target),
  87. selector(Selector),
  88. bonusList()
  89. {
  90. }
  91. CBonusProxy::CBonusProxy(const CBonusProxy & other)
  92. : bonusListCachedLast(other.bonusListCachedLast),
  93. target(other.target),
  94. selector(other.selector),
  95. bonusList(other.bonusList)
  96. {
  97. }
  98. CBonusProxy::CBonusProxy(CBonusProxy && other)
  99. : bonusListCachedLast(0),
  100. target(other.target),
  101. selector(),
  102. bonusList()
  103. {
  104. std::swap(bonusListCachedLast, other.bonusListCachedLast);
  105. std::swap(selector, other.selector);
  106. std::swap(bonusList, other.bonusList);
  107. }
  108. CBonusProxy & CBonusProxy::operator=(const CBonusProxy & other)
  109. {
  110. bonusListCachedLast = other.bonusListCachedLast;
  111. selector = other.selector;
  112. bonusList = other.bonusList;
  113. return *this;
  114. }
  115. CBonusProxy & CBonusProxy::operator=(CBonusProxy && other)
  116. {
  117. std::swap(bonusListCachedLast, other.bonusListCachedLast);
  118. std::swap(selector, other.selector);
  119. std::swap(bonusList, other.bonusList);
  120. return *this;
  121. }
  122. TConstBonusListPtr CBonusProxy::getBonusList() const
  123. {
  124. if(target->getTreeVersion() != bonusListCachedLast || !bonusList)
  125. {
  126. //TODO: support limiters
  127. bonusList = target->getAllBonuses(selector, Selector::all);
  128. bonusListCachedLast = target->getTreeVersion();
  129. }
  130. return bonusList;
  131. }
  132. const BonusList * CBonusProxy::operator->() const
  133. {
  134. return getBonusList().get();
  135. }
  136. CTotalsProxy::CTotalsProxy(const IBonusBearer * Target, CSelector Selector, int InitialValue)
  137. : CBonusProxy(Target, Selector),
  138. initialValue(InitialValue),
  139. meleeCachedLast(0),
  140. meleeValue(0),
  141. rangedCachedLast(0),
  142. rangedValue(0),
  143. value(0),
  144. valueCachedLast(0)
  145. {
  146. }
  147. CTotalsProxy::CTotalsProxy(const CTotalsProxy & other)
  148. : CBonusProxy(other),
  149. initialValue(other.initialValue),
  150. meleeCachedLast(other.meleeCachedLast),
  151. meleeValue(other.meleeValue),
  152. rangedCachedLast(other.rangedCachedLast),
  153. rangedValue(other.rangedValue)
  154. {
  155. }
  156. CTotalsProxy & CTotalsProxy::operator=(const CTotalsProxy & other)
  157. {
  158. CBonusProxy::operator=(other);
  159. initialValue = other.initialValue;
  160. meleeCachedLast = other.meleeCachedLast;
  161. meleeValue = other.meleeValue;
  162. rangedCachedLast = other.rangedCachedLast;
  163. rangedValue = other.rangedValue;
  164. value = other.value;
  165. valueCachedLast = other.valueCachedLast;
  166. return *this;
  167. }
  168. int CTotalsProxy::getValue() const
  169. {
  170. const auto treeVersion = target->getTreeVersion();
  171. if(treeVersion != valueCachedLast)
  172. {
  173. auto bonuses = getBonusList();
  174. value = initialValue + bonuses->totalValue();
  175. valueCachedLast = treeVersion;
  176. }
  177. return value;
  178. }
  179. int CTotalsProxy::getValueAndList(TConstBonusListPtr & outBonusList) const
  180. {
  181. const auto treeVersion = target->getTreeVersion();
  182. outBonusList = getBonusList();
  183. if(treeVersion != valueCachedLast)
  184. {
  185. value = initialValue + outBonusList->totalValue();
  186. valueCachedLast = treeVersion;
  187. }
  188. return value;
  189. }
  190. int CTotalsProxy::getMeleeValue() const
  191. {
  192. static const auto limit = Selector::effectRange()(Bonus::NO_LIMIT).Or(Selector::effectRange()(Bonus::ONLY_MELEE_FIGHT));
  193. const auto treeVersion = target->getTreeVersion();
  194. if(treeVersion != meleeCachedLast)
  195. {
  196. auto bonuses = target->getBonuses(selector, limit);
  197. meleeValue = initialValue + bonuses->totalValue();
  198. meleeCachedLast = treeVersion;
  199. }
  200. return meleeValue;
  201. }
  202. int CTotalsProxy::getRangedValue() const
  203. {
  204. static const auto limit = Selector::effectRange()(Bonus::NO_LIMIT).Or(Selector::effectRange()(Bonus::ONLY_DISTANCE_FIGHT));
  205. const auto treeVersion = target->getTreeVersion();
  206. if(treeVersion != rangedCachedLast)
  207. {
  208. auto bonuses = target->getBonuses(selector, limit);
  209. rangedValue = initialValue + bonuses->totalValue();
  210. rangedCachedLast = treeVersion;
  211. }
  212. return rangedValue;
  213. }
  214. ///CCheckProxy
  215. CCheckProxy::CCheckProxy(const IBonusBearer * Target, CSelector Selector)
  216. : target(Target),
  217. selector(Selector),
  218. cachedLast(0),
  219. hasBonus(false)
  220. {
  221. }
  222. CCheckProxy::CCheckProxy(const CCheckProxy & other)
  223. : target(other.target),
  224. selector(other.selector),
  225. cachedLast(other.cachedLast),
  226. hasBonus(other.hasBonus)
  227. {
  228. }
  229. bool CCheckProxy::getHasBonus() const
  230. {
  231. const auto treeVersion = target->getTreeVersion();
  232. if(treeVersion != cachedLast)
  233. {
  234. hasBonus = target->hasBonus(selector);
  235. cachedLast = treeVersion;
  236. }
  237. return hasBonus;
  238. }
  239. CAddInfo::CAddInfo()
  240. {
  241. }
  242. CAddInfo::CAddInfo(si32 value)
  243. {
  244. if(value != CAddInfo::NONE)
  245. push_back(value);
  246. }
  247. bool CAddInfo::operator==(si32 value) const
  248. {
  249. switch(size())
  250. {
  251. case 0:
  252. return value == CAddInfo::NONE;
  253. case 1:
  254. return operator[](0) == value;
  255. default:
  256. return false;
  257. }
  258. }
  259. bool CAddInfo::operator!=(si32 value) const
  260. {
  261. return !operator==(value);
  262. }
  263. si32 & CAddInfo::operator[](size_type pos)
  264. {
  265. if(pos >= size())
  266. resize(pos + 1, CAddInfo::NONE);
  267. return vector::operator[](pos);
  268. }
  269. si32 CAddInfo::operator[](size_type pos) const
  270. {
  271. return pos < size() ? vector::operator[](pos) : CAddInfo::NONE;
  272. }
  273. std::string CAddInfo::toString() const
  274. {
  275. return toJsonNode().toJson(true);
  276. }
  277. JsonNode CAddInfo::toJsonNode() const
  278. {
  279. if(size() < 2)
  280. {
  281. return JsonUtils::intNode(operator[](0));
  282. }
  283. else
  284. {
  285. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  286. for(si32 value : *this)
  287. node.Vector().push_back(JsonUtils::intNode(value));
  288. return node;
  289. }
  290. }
  291. std::atomic<int32_t> CBonusSystemNode::treeChanged(1);
  292. const bool CBonusSystemNode::cachingEnabled = true;
  293. BonusList::BonusList(bool BelongsToTree) : belongsToTree(BelongsToTree)
  294. {
  295. }
  296. BonusList::BonusList(const BonusList &bonusList)
  297. {
  298. bonuses.resize(bonusList.size());
  299. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  300. belongsToTree = false;
  301. }
  302. BonusList::BonusList(BonusList&& other):
  303. belongsToTree(false)
  304. {
  305. std::swap(belongsToTree, other.belongsToTree);
  306. std::swap(bonuses, other.bonuses);
  307. }
  308. BonusList& BonusList::operator=(const BonusList &bonusList)
  309. {
  310. bonuses.resize(bonusList.size());
  311. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  312. belongsToTree = false;
  313. return *this;
  314. }
  315. void BonusList::changed()
  316. {
  317. if(belongsToTree)
  318. CBonusSystemNode::treeHasChanged();
  319. }
  320. void BonusList::stackBonuses()
  321. {
  322. boost::sort(bonuses, [](std::shared_ptr<Bonus> b1, std::shared_ptr<Bonus> b2) -> bool
  323. {
  324. if(b1 == b2)
  325. return false;
  326. #define COMPARE_ATT(ATT) if(b1->ATT != b2->ATT) return b1->ATT < b2->ATT
  327. COMPARE_ATT(stacking);
  328. COMPARE_ATT(type);
  329. COMPARE_ATT(subtype);
  330. COMPARE_ATT(valType);
  331. #undef COMPARE_ATT
  332. return b1->val > b2->val;
  333. });
  334. // remove non-stacking
  335. size_t next = 1;
  336. while(next < bonuses.size())
  337. {
  338. bool remove;
  339. std::shared_ptr<Bonus> last = bonuses[next-1];
  340. std::shared_ptr<Bonus> current = bonuses[next];
  341. if(current->stacking.empty())
  342. remove = current == last;
  343. else if(current->stacking == "ALWAYS")
  344. remove = false;
  345. else
  346. remove = current->stacking == last->stacking
  347. && current->type == last->type
  348. && current->subtype == last->subtype
  349. && current->valType == last->valType;
  350. if(remove)
  351. bonuses.erase(bonuses.begin() + next);
  352. else
  353. next++;
  354. }
  355. }
  356. int BonusList::totalValue() const
  357. {
  358. int base = 0;
  359. int percentToBase = 0;
  360. int percentToAll = 0;
  361. int additive = 0;
  362. int indepMax = 0;
  363. bool hasIndepMax = false;
  364. int indepMin = 0;
  365. bool hasIndepMin = false;
  366. for(std::shared_ptr<Bonus> b : bonuses)
  367. {
  368. switch(b->valType)
  369. {
  370. case Bonus::BASE_NUMBER:
  371. base += b->val;
  372. break;
  373. case Bonus::PERCENT_TO_ALL:
  374. percentToAll += b->val;
  375. break;
  376. case Bonus::PERCENT_TO_BASE:
  377. percentToBase += b->val;
  378. break;
  379. case Bonus::ADDITIVE_VALUE:
  380. additive += b->val;
  381. break;
  382. case Bonus::INDEPENDENT_MAX:
  383. if (!hasIndepMax)
  384. {
  385. indepMax = b->val;
  386. hasIndepMax = true;
  387. }
  388. else
  389. {
  390. vstd::amax(indepMax, b->val);
  391. }
  392. break;
  393. case Bonus::INDEPENDENT_MIN:
  394. if (!hasIndepMin)
  395. {
  396. indepMin = b->val;
  397. hasIndepMin = true;
  398. }
  399. else
  400. {
  401. vstd::amin(indepMin, b->val);
  402. }
  403. break;
  404. }
  405. }
  406. int modifiedBase = base + (base * percentToBase) / 100;
  407. modifiedBase += additive;
  408. int valFirst = (modifiedBase * (100 + percentToAll)) / 100;
  409. if(hasIndepMin && hasIndepMax)
  410. assert(indepMin < indepMax);
  411. const int notIndepBonuses = (int)boost::count_if(bonuses, [](const std::shared_ptr<Bonus>& b)
  412. {
  413. return b->valType != Bonus::INDEPENDENT_MAX && b->valType != Bonus::INDEPENDENT_MIN;
  414. });
  415. if (hasIndepMax)
  416. {
  417. if(notIndepBonuses)
  418. vstd::amax(valFirst, indepMax);
  419. else
  420. valFirst = indepMax;
  421. }
  422. if (hasIndepMin)
  423. {
  424. if(notIndepBonuses)
  425. vstd::amin(valFirst, indepMin);
  426. else
  427. valFirst = indepMin;
  428. }
  429. return valFirst;
  430. }
  431. std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &select)
  432. {
  433. for (auto & b : bonuses)
  434. {
  435. if(select(b.get()))
  436. return b;
  437. }
  438. return nullptr;
  439. }
  440. std::shared_ptr<const Bonus> BonusList::getFirst(const CSelector &selector) const
  441. {
  442. for (auto & b : bonuses)
  443. {
  444. if(selector(b.get()))
  445. return b;
  446. }
  447. return nullptr;
  448. }
  449. void BonusList::getBonuses(BonusList & out, const CSelector &selector) const
  450. {
  451. getBonuses(out, selector, nullptr);
  452. }
  453. void BonusList::getBonuses(BonusList & out, const CSelector &selector, const CSelector &limit) const
  454. {
  455. for (auto & b : bonuses)
  456. {
  457. //add matching bonuses that matches limit predicate or have NO_LIMIT if no given predicate
  458. if(selector(b.get()) && ((!limit && b->effectRange == Bonus::NO_LIMIT) || ((bool)limit && limit(b.get()))))
  459. out.push_back(b);
  460. }
  461. }
  462. void BonusList::getAllBonuses(BonusList &out) const
  463. {
  464. for(auto & b : bonuses)
  465. out.push_back(b);
  466. }
  467. int BonusList::valOfBonuses(const CSelector &select) const
  468. {
  469. BonusList ret;
  470. CSelector limit = nullptr;
  471. getBonuses(ret, select, limit);
  472. return ret.totalValue();
  473. }
  474. JsonNode BonusList::toJsonNode() const
  475. {
  476. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  477. for(std::shared_ptr<Bonus> b : bonuses)
  478. node.Vector().push_back(b->toJsonNode());
  479. return node;
  480. }
  481. void BonusList::push_back(std::shared_ptr<Bonus> x)
  482. {
  483. bonuses.push_back(x);
  484. changed();
  485. }
  486. BonusList::TInternalContainer::iterator BonusList::erase(const int position)
  487. {
  488. changed();
  489. return bonuses.erase(bonuses.begin() + position);
  490. }
  491. void BonusList::clear()
  492. {
  493. bonuses.clear();
  494. changed();
  495. }
  496. std::vector<BonusList*>::size_type BonusList::operator-=(std::shared_ptr<Bonus> const &i)
  497. {
  498. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  499. if(itr == bonuses.end())
  500. return false;
  501. bonuses.erase(itr);
  502. changed();
  503. return true;
  504. }
  505. void BonusList::resize(BonusList::TInternalContainer::size_type sz, std::shared_ptr<Bonus> c )
  506. {
  507. bonuses.resize(sz, c);
  508. changed();
  509. }
  510. void BonusList::insert(BonusList::TInternalContainer::iterator position, BonusList::TInternalContainer::size_type n, std::shared_ptr<Bonus> const &x)
  511. {
  512. bonuses.insert(position, n, x);
  513. changed();
  514. }
  515. CSelector IBonusBearer::anaffectedByMoraleSelector
  516. = Selector::type()(Bonus::NON_LIVING)
  517. .Or(Selector::type()(Bonus::UNDEAD))
  518. .Or(Selector::type()(Bonus::NO_MORALE))
  519. .Or(Selector::type()(Bonus::SIEGE_WEAPON));
  520. CSelector IBonusBearer::moraleSelector = Selector::type()(Bonus::MORALE);
  521. CSelector IBonusBearer::luckSelector = Selector::type()(Bonus::LUCK);
  522. CSelector IBonusBearer::selfMoraleSelector = Selector::type()(Bonus::SELF_MORALE);
  523. CSelector IBonusBearer::selfLuckSelector = Selector::type()(Bonus::SELF_LUCK);
  524. IBonusBearer::IBonusBearer()
  525. :anaffectedByMorale(this, anaffectedByMoraleSelector),
  526. moraleValue(this, moraleSelector, 0),
  527. luckValue(this, luckSelector, 0),
  528. selfMorale(this, selfMoraleSelector),
  529. selfLuck(this, selfLuckSelector)
  530. {
  531. }
  532. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  533. {
  534. return valOfBonuses(Selector::type()(type).And(selector));
  535. }
  536. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype) const
  537. {
  538. boost::format fmt("type_%ds_%d");
  539. fmt % (int)type % subtype;
  540. CSelector s = Selector::type()(type);
  541. if(subtype != -1)
  542. s = s.And(Selector::subtype()(subtype));
  543. return valOfBonuses(s, fmt.str());
  544. }
  545. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  546. {
  547. CSelector limit = nullptr;
  548. TConstBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  549. return hlp->totalValue();
  550. }
  551. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  552. {
  553. return getBonuses(selector, cachingStr)->size() > 0;
  554. }
  555. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  556. {
  557. return getBonuses(selector, limit, cachingStr)->size() > 0;
  558. }
  559. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  560. {
  561. boost::format fmt("type_%ds_%d");
  562. fmt % (int)type % subtype;
  563. CSelector s = Selector::type()(type);
  564. if(subtype != -1)
  565. s = s.And(Selector::subtype()(subtype));
  566. return hasBonus(s, fmt.str());
  567. }
  568. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  569. {
  570. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  571. }
  572. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  573. {
  574. return getAllBonuses(selector, limit, nullptr, cachingStr);
  575. }
  576. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  577. {
  578. boost::format fmt("source_%did_%d");
  579. fmt % (int)source % sourceID;
  580. return hasBonus(Selector::source(source,sourceID), fmt.str());
  581. }
  582. int IBonusBearer::MoraleVal() const
  583. {
  584. if(anaffectedByMorale.getHasBonus())
  585. return 0;
  586. int ret = moraleValue.getValue();
  587. if(selfMorale.getHasBonus()) //eg. minotaur
  588. vstd::amax(ret, +1);
  589. return vstd::abetween(ret, -3, +3);
  590. }
  591. int IBonusBearer::LuckVal() const
  592. {
  593. if(hasBonusOfType(Bonus::NO_LUCK))
  594. return 0;
  595. int ret = luckValue.getValue();
  596. if(selfLuck.getHasBonus()) //eg. halfling
  597. vstd::amax(ret, +1);
  598. return vstd::abetween(ret, -3, +3);
  599. }
  600. int IBonusBearer::MoraleValAndBonusList(TConstBonusListPtr & bonusList) const
  601. {
  602. if(anaffectedByMorale.getHasBonus())
  603. {
  604. if(!bonusList->empty())
  605. bonusList = std::make_shared<const BonusList>();
  606. return 0;
  607. }
  608. int ret = moraleValue.getValueAndList(bonusList);
  609. if(selfMorale.getHasBonus()) //eg. minotaur
  610. vstd::amax(ret, +1);
  611. return vstd::abetween(ret, -3, +3);
  612. }
  613. int IBonusBearer::LuckValAndBonusList(TConstBonusListPtr & bonusList) const
  614. {
  615. if(hasBonusOfType(Bonus::NO_LUCK))
  616. {
  617. if(!bonusList->empty())
  618. bonusList = std::make_shared<const BonusList>();
  619. return 0;
  620. }
  621. int ret = luckValue.getValueAndList(bonusList);
  622. if(selfLuck.getHasBonus()) //eg. halfling
  623. vstd::amax(ret, +1);
  624. return vstd::abetween(ret, -3, +3);
  625. }
  626. ui32 IBonusBearer::MaxHealth() const
  627. {
  628. const std::string cachingStr = "type_STACK_HEALTH";
  629. static const auto selector = Selector::type()(Bonus::STACK_HEALTH);
  630. auto value = valOfBonuses(selector, cachingStr);
  631. return std::max(1, value); //never 0
  632. }
  633. int IBonusBearer::getAttack(bool ranged) const
  634. {
  635. const std::string cachingStr = "type_PRIMARY_SKILLs_ATTACK";
  636. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  637. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  638. }
  639. int IBonusBearer::getDefense(bool ranged) const
  640. {
  641. const std::string cachingStr = "type_PRIMARY_SKILLs_DEFENSE";
  642. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  643. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  644. }
  645. int IBonusBearer::getMinDamage(bool ranged) const
  646. {
  647. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_1";
  648. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1));
  649. return valOfBonuses(selector, cachingStr);
  650. }
  651. int IBonusBearer::getMaxDamage(bool ranged) const
  652. {
  653. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_2";
  654. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2));
  655. return valOfBonuses(selector, cachingStr);
  656. }
  657. si32 IBonusBearer::manaLimit() const
  658. {
  659. return si32(getPrimSkillLevel(PrimarySkill::KNOWLEDGE)
  660. * (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::INTELLIGENCE))
  661. / 10.0);
  662. }
  663. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  664. {
  665. static const CSelector selectorAllSkills = Selector::type()(Bonus::PRIMARY_SKILL);
  666. static const std::string keyAllSkills = "type_PRIMARY_SKILL";
  667. auto allSkills = getBonuses(selectorAllSkills, keyAllSkills);
  668. auto ret = allSkills->valOfBonuses(Selector::subtype()(id));
  669. return ret; //sp=0 works in old saves
  670. }
  671. si32 IBonusBearer::magicResistance() const
  672. {
  673. return valOfBonuses(Bonus::MAGIC_RESISTANCE);
  674. }
  675. ui32 IBonusBearer::Speed(int turn, bool useBind) const
  676. {
  677. //war machines cannot move
  678. if(hasBonus(Selector::type()(Bonus::SIEGE_WEAPON).And(Selector::turns(turn))))
  679. {
  680. return 0;
  681. }
  682. //bind effect check - doesn't influence stack initiative
  683. if(useBind && hasBonus(Selector::type()(Bonus::BIND_EFFECT).And(Selector::turns(turn))))
  684. {
  685. return 0;
  686. }
  687. return valOfBonuses(Selector::type()(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  688. }
  689. bool IBonusBearer::isLiving() const //TODO: theoreticaly there exists "LIVING" bonus in stack experience documentation
  690. {
  691. static const std::string cachingStr = "IBonusBearer::isLiving";
  692. static const CSelector selector = Selector::type()(Bonus::UNDEAD)
  693. .Or(Selector::type()(Bonus::NON_LIVING))
  694. .Or(Selector::type()(Bonus::GARGOYLE))
  695. .Or(Selector::type()(Bonus::SIEGE_WEAPON));
  696. return !hasBonus(selector, cachingStr);
  697. }
  698. std::shared_ptr<const Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  699. {
  700. auto bonuses = getAllBonuses(selector, Selector::all);
  701. return bonuses->getFirst(Selector::all);
  702. }
  703. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector &selector)
  704. {
  705. auto ret = bonuses.getFirst(selector);
  706. if(ret)
  707. return ret;
  708. FOREACH_PARENT(pname)
  709. {
  710. ret = pname->getBonusLocalFirst(selector);
  711. if (ret)
  712. return ret;
  713. }
  714. return nullptr;
  715. }
  716. std::shared_ptr<const Bonus> CBonusSystemNode::getBonusLocalFirst( const CSelector &selector ) const
  717. {
  718. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  719. }
  720. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  721. {
  722. for (auto & elem : parents)
  723. {
  724. const CBonusSystemNode *parent = elem;
  725. out.insert(parent);
  726. }
  727. }
  728. void CBonusSystemNode::getParents(TNodes &out)
  729. {
  730. for (auto & elem : parents)
  731. {
  732. const CBonusSystemNode *parent = elem;
  733. out.insert(const_cast<CBonusSystemNode*>(parent));
  734. }
  735. }
  736. void CBonusSystemNode::getBonusesRec(BonusList &out, const CSelector &selector, const CSelector &limit) const
  737. {
  738. BonusList beforeUpdate;
  739. FOREACH_CPARENT(p)
  740. {
  741. p->getBonusesRec(beforeUpdate, selector, limit);
  742. }
  743. bonuses.getBonuses(beforeUpdate, selector, limit);
  744. for(auto b : beforeUpdate)
  745. out.push_back(update(b));
  746. }
  747. void CBonusSystemNode::getAllBonusesRec(BonusList &out) const
  748. {
  749. BonusList beforeUpdate;
  750. FOREACH_CPARENT(p)
  751. {
  752. p->getAllBonusesRec(beforeUpdate);
  753. }
  754. bonuses.getAllBonuses(beforeUpdate);
  755. for(auto b : beforeUpdate)
  756. out.push_back(update(b));
  757. }
  758. TConstBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  759. {
  760. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  761. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  762. {
  763. // Exclusive access for one thread
  764. boost::lock_guard<boost::mutex> lock(sync);
  765. // If the bonus system tree changes(state of a single node or the relations to each other) then
  766. // cache all bonus objects. Selector objects doesn't matter.
  767. if (cachedLast != treeChanged)
  768. {
  769. cachedBonuses.clear();
  770. cachedRequests.clear();
  771. BonusList allBonuses;
  772. getAllBonusesRec(allBonuses);
  773. limitBonuses(allBonuses, cachedBonuses);
  774. cachedBonuses.stackBonuses();
  775. cachedLast = treeChanged;
  776. }
  777. // If a bonus system request comes with a caching string then look up in the map if there are any
  778. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  779. if (cachingStr != "")
  780. {
  781. auto it = cachedRequests.find(cachingStr);
  782. if(it != cachedRequests.end())
  783. {
  784. //Cached list contains bonuses for our query with applied limiters
  785. return it->second;
  786. }
  787. }
  788. //We still don't have the bonuses (didn't returned them from cache)
  789. //Perform bonus selection
  790. auto ret = std::make_shared<BonusList>();
  791. cachedBonuses.getBonuses(*ret, selector, limit);
  792. // Save the results in the cache
  793. if(cachingStr != "")
  794. cachedRequests[cachingStr] = ret;
  795. return ret;
  796. }
  797. else
  798. {
  799. return getAllBonusesWithoutCaching(selector, limit, root);
  800. }
  801. }
  802. TConstBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  803. {
  804. auto ret = std::make_shared<BonusList>();
  805. // Get bonus results without caching enabled.
  806. BonusList beforeLimiting, afterLimiting;
  807. getAllBonusesRec(beforeLimiting);
  808. if(!root || root == this)
  809. {
  810. limitBonuses(beforeLimiting, afterLimiting);
  811. }
  812. else if(root)
  813. {
  814. //We want to limit our query against an external node. We get all its bonuses,
  815. // add the ones we're considering and see if they're cut out by limiters
  816. BonusList rootBonuses, limitedRootBonuses;
  817. getAllBonusesRec(rootBonuses);
  818. for(auto b : beforeLimiting)
  819. rootBonuses.push_back(b);
  820. root->limitBonuses(rootBonuses, limitedRootBonuses);
  821. for(auto b : beforeLimiting)
  822. if(vstd::contains(limitedRootBonuses, b))
  823. afterLimiting.push_back(b);
  824. }
  825. afterLimiting.getBonuses(*ret, selector, limit);
  826. ret->stackBonuses();
  827. return ret;
  828. }
  829. std::shared_ptr<Bonus> CBonusSystemNode::update(const std::shared_ptr<Bonus> & b) const
  830. {
  831. if(b->updater)
  832. return b->updater->update(b, *this);
  833. return b;
  834. }
  835. CBonusSystemNode::CBonusSystemNode()
  836. :CBonusSystemNode(false)
  837. {
  838. }
  839. CBonusSystemNode::CBonusSystemNode(bool isHypotetic)
  840. : bonuses(true),
  841. exportedBonuses(true),
  842. nodeType(UNKNOWN),
  843. cachedLast(0),
  844. sync(),
  845. isHypotheticNode(isHypotetic)
  846. {
  847. }
  848. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType)
  849. : bonuses(true),
  850. exportedBonuses(true),
  851. nodeType(NodeType),
  852. cachedLast(0),
  853. sync(),
  854. isHypotheticNode(false)
  855. {
  856. }
  857. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other):
  858. bonuses(std::move(other.bonuses)),
  859. exportedBonuses(std::move(other.exportedBonuses)),
  860. nodeType(other.nodeType),
  861. description(other.description),
  862. cachedLast(0),
  863. sync(),
  864. isHypotheticNode(other.isHypotheticNode)
  865. {
  866. std::swap(parents, other.parents);
  867. std::swap(children, other.children);
  868. //fixing bonus tree without recalculation
  869. if(!isHypothetic())
  870. {
  871. for(CBonusSystemNode * n : parents)
  872. {
  873. n->children -= &other;
  874. n->children.push_back(this);
  875. }
  876. }
  877. for(CBonusSystemNode * n : children)
  878. {
  879. n->parents -= &other;
  880. n->parents.push_back(this);
  881. }
  882. //cache ignored
  883. //cachedBonuses
  884. //cachedRequests
  885. }
  886. CBonusSystemNode::~CBonusSystemNode()
  887. {
  888. detachFromAll();
  889. if(children.size())
  890. {
  891. while(children.size())
  892. children.front()->detachFrom(this);
  893. }
  894. }
  895. void CBonusSystemNode::attachTo(CBonusSystemNode *parent)
  896. {
  897. assert(!vstd::contains(parents, parent));
  898. parents.push_back(parent);
  899. if(!isHypothetic())
  900. {
  901. if(parent->actsAsBonusSourceOnly())
  902. parent->newRedDescendant(this);
  903. else
  904. newRedDescendant(parent);
  905. parent->newChildAttached(this);
  906. }
  907. CBonusSystemNode::treeHasChanged();
  908. }
  909. void CBonusSystemNode::detachFrom(CBonusSystemNode *parent)
  910. {
  911. assert(vstd::contains(parents, parent));
  912. if(!isHypothetic())
  913. {
  914. if(parent->actsAsBonusSourceOnly())
  915. parent->removedRedDescendant(this);
  916. else
  917. removedRedDescendant(parent);
  918. }
  919. parents -= parent;
  920. if(!isHypothetic())
  921. {
  922. parent->childDetached(this);
  923. }
  924. CBonusSystemNode::treeHasChanged();
  925. }
  926. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  927. {
  928. removeBonuses(s);
  929. for(CBonusSystemNode * child : children)
  930. child->removeBonusesRecursive(s);
  931. }
  932. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  933. {
  934. BonusList bl;
  935. exportedBonuses.getBonuses(bl, s, Selector::all);
  936. for(auto b : bl)
  937. {
  938. b->turnsRemain--;
  939. if(b->turnsRemain <= 0)
  940. removeBonus(b);
  941. }
  942. for(CBonusSystemNode *child : children)
  943. child->reduceBonusDurations(s);
  944. }
  945. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  946. {
  947. //turnsRemain shouldn't be zero for following durations
  948. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  949. {
  950. assert(b->turnsRemain);
  951. }
  952. assert(!vstd::contains(exportedBonuses, b));
  953. exportedBonuses.push_back(b);
  954. exportBonus(b);
  955. CBonusSystemNode::treeHasChanged();
  956. }
  957. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  958. {
  959. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  960. if(bonus)
  961. bonus->val += b->val;
  962. else
  963. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  964. }
  965. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  966. {
  967. exportedBonuses -= b;
  968. if(b->propagator)
  969. unpropagateBonus(b);
  970. else
  971. bonuses -= b;
  972. CBonusSystemNode::treeHasChanged();
  973. }
  974. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  975. {
  976. BonusList toRemove;
  977. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  978. for(auto bonus : toRemove)
  979. removeBonus(bonus);
  980. }
  981. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  982. {
  983. switch(nodeType)
  984. {
  985. case CREATURE:
  986. case ARTIFACT:
  987. case ARTIFACT_INSTANCE:
  988. return true;
  989. default:
  990. return false;
  991. }
  992. }
  993. void CBonusSystemNode::propagateBonus(std::shared_ptr<Bonus> b)
  994. {
  995. if(b->propagator->shouldBeAttached(this))
  996. {
  997. bonuses.push_back(b);
  998. logBonus->trace("#$# %s #propagated to# %s", b->Description(), nodeName());
  999. }
  1000. FOREACH_RED_CHILD(child)
  1001. child->propagateBonus(b);
  1002. }
  1003. void CBonusSystemNode::unpropagateBonus(std::shared_ptr<Bonus> b)
  1004. {
  1005. if(b->propagator->shouldBeAttached(this))
  1006. {
  1007. bonuses -= b;
  1008. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  1009. }
  1010. FOREACH_RED_CHILD(child)
  1011. child->unpropagateBonus(b);
  1012. }
  1013. void CBonusSystemNode::newChildAttached(CBonusSystemNode *child)
  1014. {
  1015. assert(!vstd::contains(children, child));
  1016. children.push_back(child);
  1017. }
  1018. void CBonusSystemNode::childDetached(CBonusSystemNode *child)
  1019. {
  1020. if (vstd::contains(children, child))
  1021. children -= child;
  1022. else
  1023. {
  1024. logBonus->error("Error! %s #cannot be detached from# %s", child->nodeName(), nodeName());
  1025. throw std::runtime_error("internal error");
  1026. }
  1027. }
  1028. void CBonusSystemNode::detachFromAll()
  1029. {
  1030. while(parents.size())
  1031. detachFrom(parents.front());
  1032. }
  1033. bool CBonusSystemNode::isIndependentNode() const
  1034. {
  1035. return parents.empty() && children.empty();
  1036. }
  1037. std::string CBonusSystemNode::nodeName() const
  1038. {
  1039. return description.size()
  1040. ? description
  1041. : std::string("Bonus system node of type ") + typeid(*this).name();
  1042. }
  1043. void CBonusSystemNode::deserializationFix()
  1044. {
  1045. exportBonuses();
  1046. }
  1047. void CBonusSystemNode::getRedParents(TNodes &out)
  1048. {
  1049. FOREACH_PARENT(pname)
  1050. {
  1051. if(pname->actsAsBonusSourceOnly())
  1052. {
  1053. out.insert(pname);
  1054. }
  1055. }
  1056. if(!actsAsBonusSourceOnly())
  1057. {
  1058. for(CBonusSystemNode *child : children)
  1059. {
  1060. out.insert(child);
  1061. }
  1062. }
  1063. }
  1064. void CBonusSystemNode::getRedChildren(TNodes &out)
  1065. {
  1066. FOREACH_PARENT(pname)
  1067. {
  1068. if(!pname->actsAsBonusSourceOnly())
  1069. {
  1070. out.insert(pname);
  1071. }
  1072. }
  1073. if(actsAsBonusSourceOnly())
  1074. {
  1075. for(CBonusSystemNode *child : children)
  1076. {
  1077. out.insert(child);
  1078. }
  1079. }
  1080. }
  1081. void CBonusSystemNode::newRedDescendant(CBonusSystemNode *descendant)
  1082. {
  1083. for(auto b : exportedBonuses)
  1084. if(b->propagator)
  1085. descendant->propagateBonus(b);
  1086. FOREACH_RED_PARENT(parent)
  1087. parent->newRedDescendant(descendant);
  1088. }
  1089. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode *descendant)
  1090. {
  1091. for(auto b : exportedBonuses)
  1092. if(b->propagator)
  1093. descendant->unpropagateBonus(b);
  1094. FOREACH_RED_PARENT(parent)
  1095. parent->removedRedDescendant(descendant);
  1096. }
  1097. void CBonusSystemNode::getRedAncestors(TNodes &out)
  1098. {
  1099. getRedParents(out);
  1100. FOREACH_RED_PARENT(p)
  1101. p->getRedAncestors(out);
  1102. }
  1103. void CBonusSystemNode::getRedDescendants(TNodes &out)
  1104. {
  1105. getRedChildren(out);
  1106. FOREACH_RED_CHILD(c)
  1107. c->getRedChildren(out);
  1108. }
  1109. void CBonusSystemNode::exportBonus(std::shared_ptr<Bonus> b)
  1110. {
  1111. if(b->propagator)
  1112. propagateBonus(b);
  1113. else
  1114. bonuses.push_back(b);
  1115. CBonusSystemNode::treeHasChanged();
  1116. }
  1117. void CBonusSystemNode::exportBonuses()
  1118. {
  1119. for(auto b : exportedBonuses)
  1120. exportBonus(b);
  1121. }
  1122. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  1123. {
  1124. return nodeType;
  1125. }
  1126. const BonusList& CBonusSystemNode::getBonusList() const
  1127. {
  1128. return bonuses;
  1129. }
  1130. const TNodesVector& CBonusSystemNode::getParentNodes() const
  1131. {
  1132. return parents;
  1133. }
  1134. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  1135. {
  1136. return children;
  1137. }
  1138. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  1139. {
  1140. nodeType = type;
  1141. }
  1142. BonusList & CBonusSystemNode::getExportedBonusList()
  1143. {
  1144. return exportedBonuses;
  1145. }
  1146. const BonusList & CBonusSystemNode::getExportedBonusList() const
  1147. {
  1148. return exportedBonuses;
  1149. }
  1150. const std::string& CBonusSystemNode::getDescription() const
  1151. {
  1152. return description;
  1153. }
  1154. void CBonusSystemNode::setDescription(const std::string &description)
  1155. {
  1156. this->description = description;
  1157. }
  1158. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  1159. {
  1160. assert(&allBonuses != &out); //todo should it work in-place?
  1161. BonusList undecided = allBonuses,
  1162. &accepted = out;
  1163. while(true)
  1164. {
  1165. int undecidedCount = static_cast<int>(undecided.size());
  1166. for(int i = 0; i < undecided.size(); i++)
  1167. {
  1168. auto b = undecided[i];
  1169. BonusLimitationContext context = {b, *this, out, undecided};
  1170. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  1171. if(decision == ILimiter::DISCARD)
  1172. {
  1173. undecided.erase(i);
  1174. i--; continue;
  1175. }
  1176. else if(decision == ILimiter::ACCEPT)
  1177. {
  1178. accepted.push_back(b);
  1179. undecided.erase(i);
  1180. i--; continue;
  1181. }
  1182. else
  1183. assert(decision == ILimiter::NOT_SURE);
  1184. }
  1185. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  1186. return;
  1187. }
  1188. }
  1189. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  1190. {
  1191. auto ret = std::make_shared<BonusList>();
  1192. limitBonuses(allBonuses, *ret);
  1193. return ret;
  1194. }
  1195. void CBonusSystemNode::treeHasChanged()
  1196. {
  1197. treeChanged++;
  1198. }
  1199. int64_t CBonusSystemNode::getTreeVersion() const
  1200. {
  1201. int64_t ret = treeChanged;
  1202. return ret << 32;
  1203. }
  1204. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1205. {
  1206. if(obj)
  1207. return obj->valOfBonuses(type, subtype);
  1208. return 0;
  1209. }
  1210. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1211. {
  1212. if(obj)
  1213. return obj->hasBonusOfType(type, subtype);
  1214. return false;
  1215. }
  1216. std::string Bonus::Description() const
  1217. {
  1218. std::ostringstream str;
  1219. if(description.empty())
  1220. {
  1221. if(stacking.empty() || stacking == "ALWAYS")
  1222. {
  1223. switch(source)
  1224. {
  1225. case ARTIFACT:
  1226. str << ArtifactID(sid).toArtifact(VLC->artifacts())->getName();
  1227. break;
  1228. case SPELL_EFFECT:
  1229. str << SpellID(sid).toSpell(VLC->spells())->getName();
  1230. break;
  1231. case CREATURE_ABILITY:
  1232. str << VLC->creh->objects[sid]->namePl;
  1233. break;
  1234. case SECONDARY_SKILL:
  1235. str << VLC->skillh->skillName(sid);
  1236. break;
  1237. case HERO_SPECIAL:
  1238. str << VLC->heroh->objects[sid]->name;
  1239. break;
  1240. default:
  1241. //todo: handle all possible sources
  1242. str << "Unknown";
  1243. break;
  1244. }
  1245. }
  1246. else
  1247. str << stacking;
  1248. }
  1249. else
  1250. {
  1251. str << description;
  1252. }
  1253. if(val != 0)
  1254. str << " " << std::showpos << val;
  1255. return str.str();
  1256. }
  1257. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  1258. {
  1259. switch(type)
  1260. {
  1261. case Bonus::PRIMARY_SKILL:
  1262. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  1263. case Bonus::SECONDARY_SKILL_PREMY:
  1264. return JsonUtils::stringNode(CSkillHandler::encodeSkillWithType(subtype));
  1265. case Bonus::SPECIAL_SPELL_LEV:
  1266. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1267. case Bonus::SPECIAL_BLESS_DAMAGE:
  1268. case Bonus::MAXED_SPELL:
  1269. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1270. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1271. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1272. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "spell", SpellID::encode(subtype)));
  1273. case Bonus::IMPROVED_NECROMANCY:
  1274. case Bonus::SPECIAL_UPGRADE:
  1275. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(subtype)));
  1276. case Bonus::GENERATE_RESOURCE:
  1277. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1278. default:
  1279. return JsonUtils::intNode(subtype);
  1280. }
  1281. }
  1282. JsonNode additionalInfoToJson(Bonus::BonusType type, CAddInfo addInfo)
  1283. {
  1284. switch(type)
  1285. {
  1286. case Bonus::SPECIAL_UPGRADE:
  1287. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(addInfo[0])));
  1288. default:
  1289. return addInfo.toJsonNode();
  1290. }
  1291. }
  1292. JsonNode durationToJson(ui16 duration)
  1293. {
  1294. std::vector<std::string> durationNames;
  1295. for(ui16 durBit = 1; durBit; durBit = durBit << 1)
  1296. {
  1297. if(duration & durBit)
  1298. durationNames.push_back(vstd::findKey(bonusDurationMap, durBit));
  1299. }
  1300. if(durationNames.size() == 1)
  1301. {
  1302. return JsonUtils::stringNode(durationNames[0]);
  1303. }
  1304. else
  1305. {
  1306. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  1307. for(std::string dur : durationNames)
  1308. node.Vector().push_back(JsonUtils::stringNode(dur));
  1309. return node;
  1310. }
  1311. }
  1312. JsonNode Bonus::toJsonNode() const
  1313. {
  1314. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1315. // only add values that might reasonably be found in config files
  1316. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1317. if(subtype != -1)
  1318. root["subtype"] = subtypeToJson(type, subtype);
  1319. if(additionalInfo != CAddInfo::NONE)
  1320. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1321. if(duration != 0)
  1322. {
  1323. JsonNode durationVec(JsonNode::JsonType::DATA_VECTOR);
  1324. for(auto & kv : bonusDurationMap)
  1325. {
  1326. if(duration & kv.second)
  1327. durationVec.Vector().push_back(JsonUtils::stringNode(kv.first));
  1328. }
  1329. root["duration"] = durationVec;
  1330. }
  1331. if(turnsRemain != 0)
  1332. root["turns"].Integer() = turnsRemain;
  1333. if(source != OTHER)
  1334. root["source"].String() = vstd::findKey(bonusSourceMap, source);
  1335. if(sid != 0)
  1336. root["sourceID"].Integer() = sid;
  1337. if(val != 0)
  1338. root["val"].Integer() = val;
  1339. if(valType != ADDITIVE_VALUE)
  1340. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1341. if(stacking != "")
  1342. root["stacking"].String() = stacking;
  1343. if(description != "")
  1344. root["description"].String() = description;
  1345. if(effectRange != NO_LIMIT)
  1346. root["effectRange"].String() = vstd::findKey(bonusLimitEffect, effectRange);
  1347. if(duration != PERMANENT)
  1348. root["duration"] = durationToJson(duration);
  1349. if(turnsRemain)
  1350. root["turns"].Integer() = turnsRemain;
  1351. if(limiter)
  1352. root["limiters"] = limiter->toJsonNode();
  1353. if(updater)
  1354. root["updater"] = updater->toJsonNode();
  1355. if(propagator)
  1356. root["propagator"].String() = vstd::findKey(bonusPropagatorMap, propagator);
  1357. return root;
  1358. }
  1359. std::string Bonus::nameForBonus() const
  1360. {
  1361. switch(type)
  1362. {
  1363. case Bonus::PRIMARY_SKILL:
  1364. return PrimarySkill::names[subtype];
  1365. case Bonus::SECONDARY_SKILL_PREMY:
  1366. return CSkillHandler::encodeSkill(subtype);
  1367. case Bonus::SPECIAL_SPELL_LEV:
  1368. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1369. case Bonus::SPECIAL_BLESS_DAMAGE:
  1370. case Bonus::MAXED_SPELL:
  1371. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1372. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1373. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1374. return (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier;
  1375. case Bonus::SPECIAL_UPGRADE:
  1376. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo[0]);
  1377. case Bonus::GENERATE_RESOURCE:
  1378. return GameConstants::RESOURCE_NAMES[subtype];
  1379. case Bonus::STACKS_SPEED:
  1380. return "speed";
  1381. default:
  1382. return vstd::findKey(bonusNameMap, type);
  1383. }
  1384. }
  1385. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype)
  1386. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  1387. {
  1388. turnsRemain = 0;
  1389. valType = ADDITIVE_VALUE;
  1390. effectRange = NO_LIMIT;
  1391. boost::algorithm::trim(description);
  1392. }
  1393. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType)
  1394. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  1395. {
  1396. turnsRemain = 0;
  1397. effectRange = NO_LIMIT;
  1398. }
  1399. Bonus::Bonus()
  1400. {
  1401. duration = PERMANENT;
  1402. turnsRemain = 0;
  1403. type = NONE;
  1404. subtype = -1;
  1405. valType = ADDITIVE_VALUE;
  1406. effectRange = NO_LIMIT;
  1407. val = 0;
  1408. source = OTHER;
  1409. sid = 0;
  1410. }
  1411. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  1412. {
  1413. propagator = Propagator;
  1414. return this->shared_from_this();
  1415. }
  1416. namespace Selector
  1417. {
  1418. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type()
  1419. {
  1420. static CSelectFieldEqual<Bonus::BonusType> stype(&Bonus::type);
  1421. return stype;
  1422. }
  1423. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype()
  1424. {
  1425. static CSelectFieldEqual<TBonusSubtype> ssubtype(&Bonus::subtype);
  1426. return ssubtype;
  1427. }
  1428. DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info()
  1429. {
  1430. static CSelectFieldEqual<CAddInfo> sinfo(&Bonus::additionalInfo);
  1431. return sinfo;
  1432. }
  1433. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType()
  1434. {
  1435. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::source);
  1436. return ssourceType;
  1437. }
  1438. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange()
  1439. {
  1440. static CSelectFieldEqual<Bonus::LimitEffect> seffectRange(&Bonus::effectRange);
  1441. return seffectRange;
  1442. }
  1443. DLL_LINKAGE CWillLastTurns turns;
  1444. DLL_LINKAGE CWillLastDays days;
  1445. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1446. {
  1447. return type()(Type).And(subtype()(Subtype));
  1448. }
  1449. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, CAddInfo info)
  1450. {
  1451. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1452. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1453. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1454. }
  1455. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1456. {
  1457. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1458. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1459. }
  1460. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1461. {
  1462. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1463. }
  1464. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1465. {
  1466. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1467. }
  1468. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1469. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1470. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1471. {
  1472. Bonus dummy;
  1473. dummy.type = type;
  1474. return sel(&dummy);
  1475. }
  1476. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1477. {
  1478. Bonus dummy;
  1479. dummy.type = type;
  1480. dummy.subtype = subtype;
  1481. return sel(&dummy);
  1482. }
  1483. }
  1484. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  1485. {
  1486. switch(node->getNodeType())
  1487. {
  1488. case CBonusSystemNode::STACK_BATTLE:
  1489. return static_cast<const CStack*>(node);
  1490. default:
  1491. return nullptr;
  1492. }
  1493. }
  1494. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  1495. {
  1496. switch(node->getNodeType())
  1497. {
  1498. case CBonusSystemNode::STACK_INSTANCE:
  1499. return (static_cast<const CStackInstance *>(node));
  1500. case CBonusSystemNode::STACK_BATTLE:
  1501. return (static_cast<const CStack*>(node))->base;
  1502. default:
  1503. return nullptr;
  1504. }
  1505. }
  1506. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1507. {
  1508. switch(node->getNodeType())
  1509. {
  1510. case CBonusSystemNode::CREATURE:
  1511. return (static_cast<const CCreature *>(node));
  1512. case CBonusSystemNode::STACK_BATTLE:
  1513. return (static_cast<const CStack*>(node))->type;
  1514. default:
  1515. const CStackInstance * csi = retrieveStackInstance(node);
  1516. if(csi)
  1517. return csi->type;
  1518. return nullptr;
  1519. }
  1520. }
  1521. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1522. {
  1523. for (ui32 i = 0; i < bonusList.size(); i++)
  1524. {
  1525. auto b = bonusList[i];
  1526. out << "Bonus " << i << "\n" << *b << std::endl;
  1527. }
  1528. return out;
  1529. }
  1530. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1531. {
  1532. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1533. if(i->second == bonus.type)
  1534. out << "\tType: " << i->first << " \t";
  1535. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1536. printField(val);
  1537. printField(subtype);
  1538. printField(duration);
  1539. printField(source);
  1540. printField(sid);
  1541. if(bonus.additionalInfo != CAddInfo::NONE)
  1542. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1543. printField(turnsRemain);
  1544. printField(valType);
  1545. if(!bonus.stacking.empty())
  1546. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1547. printField(effectRange);
  1548. #undef printField
  1549. if(bonus.limiter)
  1550. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1551. if(bonus.updater)
  1552. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1553. return out;
  1554. }
  1555. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1556. {
  1557. if (limiter)
  1558. {
  1559. //If we already have limiter list, retrieve it
  1560. auto limiterList = std::dynamic_pointer_cast<AllOfLimiter>(limiter);
  1561. if(!limiterList)
  1562. {
  1563. //Create a new limiter list with old limiter and the new one will be pushed later
  1564. limiterList = std::make_shared<AllOfLimiter>();
  1565. limiterList->add(limiter);
  1566. limiter = limiterList;
  1567. }
  1568. limiterList->add(Limiter);
  1569. }
  1570. else
  1571. {
  1572. limiter = Limiter;
  1573. }
  1574. return this->shared_from_this();
  1575. }
  1576. ILimiter::~ILimiter()
  1577. {
  1578. }
  1579. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1580. {
  1581. return false;
  1582. }
  1583. std::string ILimiter::toString() const
  1584. {
  1585. return typeid(*this).name();
  1586. }
  1587. JsonNode ILimiter::toJsonNode() const
  1588. {
  1589. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1590. root["type"].String() = toString();
  1591. return root;
  1592. }
  1593. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1594. {
  1595. const CCreature *c = retrieveCreature(&context.node);
  1596. if(!c)
  1597. return true;
  1598. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1599. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1600. }
  1601. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature & creature_, bool IncludeUpgrades)
  1602. : creature(&creature_), includeUpgrades(IncludeUpgrades)
  1603. {
  1604. }
  1605. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1606. {
  1607. creature = nullptr;
  1608. includeUpgrades = false;
  1609. }
  1610. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1611. {
  1612. creature = VLC->creh->objects[id];
  1613. }
  1614. std::string CCreatureTypeLimiter::toString() const
  1615. {
  1616. boost::format fmt("CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)");
  1617. fmt % creature->identifier % (includeUpgrades ? "true" : "false");
  1618. return fmt.str();
  1619. }
  1620. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1621. {
  1622. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1623. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1624. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->identifier));
  1625. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1626. return root;
  1627. }
  1628. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1629. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1630. {
  1631. }
  1632. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1633. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1634. {
  1635. }
  1636. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1637. {
  1638. CSelector mySelector = isSubtypeRelevant
  1639. ? Selector::typeSubtype(type, subtype)
  1640. : Selector::type()(type);
  1641. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1642. if(context.alreadyAccepted.getFirst(mySelector))
  1643. return ACCEPT;
  1644. //if there are no matching bonuses pending, we can (and must) reject right away
  1645. if(!context.stillUndecided.getFirst(mySelector))
  1646. return DISCARD;
  1647. //do not accept for now but it may change if more bonuses gets included
  1648. return NOT_SURE;
  1649. }
  1650. std::string HasAnotherBonusLimiter::toString() const
  1651. {
  1652. std::string typeName = vstd::findKey(bonusNameMap, type);
  1653. if(isSubtypeRelevant)
  1654. {
  1655. boost::format fmt("HasAnotherBonusLimiter(type=%s, subtype=%d)");
  1656. fmt % typeName % subtype;
  1657. return fmt.str();
  1658. }
  1659. else
  1660. {
  1661. boost::format fmt("HasAnotherBonusLimiter(type=%s)");
  1662. fmt % typeName;
  1663. return fmt.str();
  1664. }
  1665. }
  1666. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  1667. {
  1668. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1669. std::string typeName = vstd::findKey(bonusNameMap, type);
  1670. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  1671. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  1672. if(isSubtypeRelevant)
  1673. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  1674. return root;
  1675. }
  1676. IPropagator::~IPropagator()
  1677. {
  1678. }
  1679. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1680. {
  1681. return false;
  1682. }
  1683. CBonusSystemNode::ENodeTypes IPropagator::getPropagatorType() const
  1684. {
  1685. return CBonusSystemNode::ENodeTypes::NONE;
  1686. }
  1687. CPropagatorNodeType::CPropagatorNodeType()
  1688. :nodeType(CBonusSystemNode::ENodeTypes::UNKNOWN)
  1689. {
  1690. }
  1691. CPropagatorNodeType::CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType)
  1692. : nodeType(NodeType)
  1693. {
  1694. }
  1695. CBonusSystemNode::ENodeTypes CPropagatorNodeType::getPropagatorType() const
  1696. {
  1697. return nodeType;
  1698. }
  1699. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1700. {
  1701. return nodeType == dest->getNodeType();
  1702. }
  1703. CreatureTerrainLimiter::CreatureTerrainLimiter(int TerrainType)
  1704. : terrainType(TerrainType)
  1705. {
  1706. }
  1707. CreatureTerrainLimiter::CreatureTerrainLimiter()
  1708. : terrainType(-1)
  1709. {
  1710. }
  1711. int CreatureTerrainLimiter::limit(const BonusLimitationContext &context) const
  1712. {
  1713. const CStack *stack = retrieveStackBattle(&context.node);
  1714. if(stack)
  1715. {
  1716. if(terrainType == -1)//terrainType not specified = native
  1717. return !stack->isOnNativeTerrain();
  1718. return !stack->isOnTerrain(terrainType);
  1719. }
  1720. return true;
  1721. //TODO neutral creatues
  1722. }
  1723. std::string CreatureTerrainLimiter::toString() const
  1724. {
  1725. boost::format fmt("CreatureTerrainLimiter(terrainType=%s)");
  1726. fmt % (terrainType >= 0 ? GameConstants::TERRAIN_NAMES[terrainType] : "native");
  1727. return fmt.str();
  1728. }
  1729. JsonNode CreatureTerrainLimiter::toJsonNode() const
  1730. {
  1731. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1732. root["type"].String() = "CREATURE_TERRAIN_LIMITER";
  1733. if(terrainType >= 0)
  1734. root["parameters"].Vector().push_back(JsonUtils::stringNode(GameConstants::TERRAIN_NAMES[terrainType]));
  1735. return root;
  1736. }
  1737. CreatureFactionLimiter::CreatureFactionLimiter(TFaction creatureFaction)
  1738. : faction(creatureFaction)
  1739. {
  1740. }
  1741. CreatureFactionLimiter::CreatureFactionLimiter()
  1742. : faction((TFaction)-1)
  1743. {
  1744. }
  1745. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1746. {
  1747. const CCreature *c = retrieveCreature(&context.node);
  1748. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1749. }
  1750. std::string CreatureFactionLimiter::toString() const
  1751. {
  1752. boost::format fmt("CreatureFactionLimiter(faction=%s)");
  1753. fmt % VLC->factions()->getByIndex(faction)->getJsonKey();
  1754. return fmt.str();
  1755. }
  1756. JsonNode CreatureFactionLimiter::toJsonNode() const
  1757. {
  1758. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1759. root["type"].String() = "CREATURE_FACTION_LIMITER";
  1760. root["parameters"].Vector().push_back(JsonUtils::stringNode(VLC->factions()->getByIndex(faction)->getJsonKey()));
  1761. return root;
  1762. }
  1763. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1764. : alignment(-1)
  1765. {
  1766. }
  1767. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1768. : alignment(Alignment)
  1769. {
  1770. }
  1771. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1772. {
  1773. const CCreature *c = retrieveCreature(&context.node);
  1774. if(!c)
  1775. return true;
  1776. switch(alignment)
  1777. {
  1778. case EAlignment::GOOD:
  1779. return !c->isGood(); //if not good -> return true (drop bonus)
  1780. case EAlignment::NEUTRAL:
  1781. return c->isEvil() || c->isGood();
  1782. case EAlignment::EVIL:
  1783. return !c->isEvil();
  1784. default:
  1785. logBonus->warn("Warning: illegal alignment in limiter!");
  1786. return true;
  1787. }
  1788. }
  1789. std::string CreatureAlignmentLimiter::toString() const
  1790. {
  1791. boost::format fmt("CreatureAlignmentLimiter(alignment=%s)");
  1792. fmt % EAlignment::names[alignment];
  1793. return fmt.str();
  1794. }
  1795. JsonNode CreatureAlignmentLimiter::toJsonNode() const
  1796. {
  1797. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1798. root["type"].String() = "CREATURE_ALIGNMENT_LIMITER";
  1799. root["parameters"].Vector().push_back(JsonUtils::stringNode(EAlignment::names[alignment]));
  1800. return root;
  1801. }
  1802. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1803. :minRank(Min), maxRank(Max)
  1804. {
  1805. }
  1806. RankRangeLimiter::RankRangeLimiter()
  1807. {
  1808. minRank = maxRank = -1;
  1809. }
  1810. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1811. {
  1812. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1813. if(csi)
  1814. {
  1815. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1816. return true;
  1817. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1818. }
  1819. return true;
  1820. }
  1821. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1822. {
  1823. const CStack * s = retrieveStackBattle(&context.node);
  1824. if(s)
  1825. return s->owner != owner;
  1826. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1827. if(csi && csi->armyObj)
  1828. return csi->armyObj->tempOwner != owner;
  1829. return true;
  1830. }
  1831. StackOwnerLimiter::StackOwnerLimiter()
  1832. : owner(-1)
  1833. {
  1834. }
  1835. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1836. : owner(Owner)
  1837. {
  1838. }
  1839. // Aggregate/Boolean Limiters
  1840. void AggregateLimiter::add(TLimiterPtr limiter)
  1841. {
  1842. if(limiter)
  1843. limiters.push_back(limiter);
  1844. }
  1845. JsonNode AggregateLimiter::toJsonNode() const
  1846. {
  1847. JsonNode result(JsonNode::JsonType::DATA_VECTOR);
  1848. result.Vector().push_back(JsonUtils::stringNode(getAggregator()));
  1849. for(auto l : limiters)
  1850. result.Vector().push_back(l->toJsonNode());
  1851. return result;
  1852. }
  1853. const std::string AllOfLimiter::aggregator = "allOf";
  1854. const std::string & AllOfLimiter::getAggregator() const
  1855. {
  1856. return aggregator;
  1857. }
  1858. int AllOfLimiter::limit(const BonusLimitationContext & context) const
  1859. {
  1860. bool wasntSure = false;
  1861. for(auto limiter : limiters)
  1862. {
  1863. auto result = limiter->limit(context);
  1864. if(result == ILimiter::DISCARD)
  1865. return result;
  1866. if(result == ILimiter::NOT_SURE)
  1867. wasntSure = true;
  1868. }
  1869. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1870. }
  1871. const std::string AnyOfLimiter::aggregator = "anyOf";
  1872. const std::string & AnyOfLimiter::getAggregator() const
  1873. {
  1874. return aggregator;
  1875. }
  1876. int AnyOfLimiter::limit(const BonusLimitationContext & context) const
  1877. {
  1878. bool wasntSure = false;
  1879. for(auto limiter : limiters)
  1880. {
  1881. auto result = limiter->limit(context);
  1882. if(result == ILimiter::ACCEPT)
  1883. return result;
  1884. if(result == ILimiter::NOT_SURE)
  1885. wasntSure = true;
  1886. }
  1887. return wasntSure ? ILimiter::NOT_SURE : ILimiter::DISCARD;
  1888. }
  1889. const std::string NoneOfLimiter::aggregator = "noneOf";
  1890. const std::string & NoneOfLimiter::getAggregator() const
  1891. {
  1892. return aggregator;
  1893. }
  1894. int NoneOfLimiter::limit(const BonusLimitationContext & context) const
  1895. {
  1896. bool wasntSure = false;
  1897. for(auto limiter : limiters)
  1898. {
  1899. auto result = limiter->limit(context);
  1900. if(result == ILimiter::ACCEPT)
  1901. return ILimiter::DISCARD;
  1902. if(result == ILimiter::NOT_SURE)
  1903. wasntSure = true;
  1904. }
  1905. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1906. }
  1907. // Updaters
  1908. std::shared_ptr<Bonus> Bonus::addUpdater(TUpdaterPtr Updater)
  1909. {
  1910. updater = Updater;
  1911. return this->shared_from_this();
  1912. }
  1913. IUpdater::~IUpdater()
  1914. {
  1915. }
  1916. std::shared_ptr<Bonus> IUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1917. {
  1918. return b;
  1919. }
  1920. std::string IUpdater::toString() const
  1921. {
  1922. return typeid(*this).name();
  1923. }
  1924. JsonNode IUpdater::toJsonNode() const
  1925. {
  1926. return JsonNode(JsonNode::JsonType::DATA_NULL);
  1927. }
  1928. GrowsWithLevelUpdater::GrowsWithLevelUpdater() : valPer20(0), stepSize(1)
  1929. {
  1930. }
  1931. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  1932. {
  1933. }
  1934. std::shared_ptr<Bonus> GrowsWithLevelUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1935. {
  1936. if(context.getNodeType() == CBonusSystemNode::HERO)
  1937. {
  1938. int level = static_cast<const CGHeroInstance &>(context).level;
  1939. int steps = stepSize ? level / stepSize : level;
  1940. //rounding follows format for HMM3 creature specialty bonus
  1941. int newVal = (valPer20 * steps + 19) / 20;
  1942. //return copy of bonus with updated val
  1943. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1944. newBonus->val = newVal;
  1945. return newBonus;
  1946. }
  1947. return b;
  1948. }
  1949. std::string GrowsWithLevelUpdater::toString() const
  1950. {
  1951. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  1952. }
  1953. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  1954. {
  1955. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1956. root["type"].String() = "GROWS_WITH_LEVEL";
  1957. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  1958. if(stepSize > 1)
  1959. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  1960. return root;
  1961. }
  1962. TimesHeroLevelUpdater::TimesHeroLevelUpdater()
  1963. {
  1964. }
  1965. std::shared_ptr<Bonus> TimesHeroLevelUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1966. {
  1967. if(context.getNodeType() == CBonusSystemNode::HERO)
  1968. {
  1969. int level = static_cast<const CGHeroInstance &>(context).level;
  1970. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1971. newBonus->val *= level;
  1972. return newBonus;
  1973. }
  1974. return b;
  1975. }
  1976. std::string TimesHeroLevelUpdater::toString() const
  1977. {
  1978. return "TimesHeroLevelUpdater";
  1979. }
  1980. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  1981. {
  1982. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  1983. }
  1984. TimesStackLevelUpdater::TimesStackLevelUpdater()
  1985. {
  1986. }
  1987. std::shared_ptr<Bonus> TimesStackLevelUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1988. {
  1989. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  1990. {
  1991. int level = static_cast<const CStackInstance &>(context).getLevel();
  1992. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1993. newBonus->val *= level;
  1994. return newBonus;
  1995. }
  1996. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  1997. {
  1998. const CStack & stack = static_cast<const CStack &>(context);
  1999. //only update if stack doesn't have an instance (summons, war machines)
  2000. //otherwise we'd end up multiplying twice
  2001. if(stack.base == nullptr)
  2002. {
  2003. int level = stack.type->level;
  2004. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2005. newBonus->val *= level;
  2006. return newBonus;
  2007. }
  2008. }
  2009. return b;
  2010. }
  2011. std::string TimesStackLevelUpdater::toString() const
  2012. {
  2013. return "TimesStackLevelUpdater";
  2014. }
  2015. JsonNode TimesStackLevelUpdater::toJsonNode() const
  2016. {
  2017. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  2018. }