HeroBonus.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355
  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. : bonuses(true),
  837. exportedBonuses(true),
  838. nodeType(UNKNOWN),
  839. cachedLast(0),
  840. sync()
  841. {
  842. }
  843. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType)
  844. : bonuses(true),
  845. exportedBonuses(true),
  846. nodeType(NodeType),
  847. cachedLast(0),
  848. sync()
  849. {
  850. }
  851. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other):
  852. bonuses(std::move(other.bonuses)),
  853. exportedBonuses(std::move(other.exportedBonuses)),
  854. nodeType(other.nodeType),
  855. description(other.description),
  856. cachedLast(0),
  857. sync()
  858. {
  859. std::swap(parents, other.parents);
  860. std::swap(children, other.children);
  861. //fixing bonus tree without recalculation
  862. for(CBonusSystemNode * n : parents)
  863. {
  864. n->children -= &other;
  865. n->children.push_back(this);
  866. }
  867. for(CBonusSystemNode * n : children)
  868. {
  869. n->parents -= &other;
  870. n->parents.push_back(this);
  871. }
  872. //cache ignored
  873. //cachedBonuses
  874. //cachedRequests
  875. }
  876. CBonusSystemNode::~CBonusSystemNode()
  877. {
  878. detachFromAll();
  879. if(children.size())
  880. {
  881. while(children.size())
  882. children.front()->detachFrom(this);
  883. }
  884. }
  885. void CBonusSystemNode::attachTo(CBonusSystemNode *parent)
  886. {
  887. assert(!vstd::contains(parents, parent));
  888. parents.push_back(parent);
  889. if(parent->actsAsBonusSourceOnly())
  890. parent->newRedDescendant(this);
  891. else
  892. newRedDescendant(parent);
  893. parent->newChildAttached(this);
  894. CBonusSystemNode::treeHasChanged();
  895. }
  896. void CBonusSystemNode::detachFrom(CBonusSystemNode *parent)
  897. {
  898. assert(vstd::contains(parents, parent));
  899. if(parent->actsAsBonusSourceOnly())
  900. parent->removedRedDescendant(this);
  901. else
  902. removedRedDescendant(parent);
  903. parents -= parent;
  904. parent->childDetached(this);
  905. CBonusSystemNode::treeHasChanged();
  906. }
  907. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  908. {
  909. removeBonuses(s);
  910. for(CBonusSystemNode * child : children)
  911. child->removeBonusesRecursive(s);
  912. }
  913. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  914. {
  915. BonusList bl;
  916. exportedBonuses.getBonuses(bl, s, Selector::all);
  917. for(auto b : bl)
  918. {
  919. b->turnsRemain--;
  920. if(b->turnsRemain <= 0)
  921. removeBonus(b);
  922. }
  923. for(CBonusSystemNode *child : children)
  924. child->reduceBonusDurations(s);
  925. }
  926. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  927. {
  928. //turnsRemain shouldn't be zero for following durations
  929. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  930. {
  931. assert(b->turnsRemain);
  932. }
  933. assert(!vstd::contains(exportedBonuses, b));
  934. exportedBonuses.push_back(b);
  935. exportBonus(b);
  936. CBonusSystemNode::treeHasChanged();
  937. }
  938. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  939. {
  940. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  941. if(bonus)
  942. bonus->val += b->val;
  943. else
  944. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  945. }
  946. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  947. {
  948. exportedBonuses -= b;
  949. if(b->propagator)
  950. unpropagateBonus(b);
  951. else
  952. bonuses -= b;
  953. CBonusSystemNode::treeHasChanged();
  954. }
  955. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  956. {
  957. BonusList toRemove;
  958. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  959. for(auto bonus : toRemove)
  960. removeBonus(bonus);
  961. }
  962. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  963. {
  964. switch(nodeType)
  965. {
  966. case CREATURE:
  967. case ARTIFACT:
  968. case ARTIFACT_INSTANCE:
  969. return true;
  970. default:
  971. return false;
  972. }
  973. }
  974. void CBonusSystemNode::propagateBonus(std::shared_ptr<Bonus> b)
  975. {
  976. if(b->propagator->shouldBeAttached(this))
  977. {
  978. bonuses.push_back(b);
  979. logBonus->trace("#$# %s #propagated to# %s", b->Description(), nodeName());
  980. }
  981. FOREACH_RED_CHILD(child)
  982. child->propagateBonus(b);
  983. }
  984. void CBonusSystemNode::unpropagateBonus(std::shared_ptr<Bonus> b)
  985. {
  986. if(b->propagator->shouldBeAttached(this))
  987. {
  988. bonuses -= b;
  989. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  990. }
  991. FOREACH_RED_CHILD(child)
  992. child->unpropagateBonus(b);
  993. }
  994. void CBonusSystemNode::newChildAttached(CBonusSystemNode *child)
  995. {
  996. assert(!vstd::contains(children, child));
  997. children.push_back(child);
  998. }
  999. void CBonusSystemNode::childDetached(CBonusSystemNode *child)
  1000. {
  1001. if (vstd::contains(children, child))
  1002. children -= child;
  1003. else
  1004. {
  1005. logBonus->error("Error! %s #cannot be detached from# %s", child->nodeName(), nodeName());
  1006. throw std::runtime_error("internal error");
  1007. }
  1008. }
  1009. void CBonusSystemNode::detachFromAll()
  1010. {
  1011. while(parents.size())
  1012. detachFrom(parents.front());
  1013. }
  1014. bool CBonusSystemNode::isIndependentNode() const
  1015. {
  1016. return parents.empty() && children.empty();
  1017. }
  1018. std::string CBonusSystemNode::nodeName() const
  1019. {
  1020. return description.size()
  1021. ? description
  1022. : std::string("Bonus system node of type ") + typeid(*this).name();
  1023. }
  1024. void CBonusSystemNode::deserializationFix()
  1025. {
  1026. exportBonuses();
  1027. }
  1028. void CBonusSystemNode::getRedParents(TNodes &out)
  1029. {
  1030. FOREACH_PARENT(pname)
  1031. {
  1032. if(pname->actsAsBonusSourceOnly())
  1033. {
  1034. out.insert(pname);
  1035. }
  1036. }
  1037. if(!actsAsBonusSourceOnly())
  1038. {
  1039. for(CBonusSystemNode *child : children)
  1040. {
  1041. out.insert(child);
  1042. }
  1043. }
  1044. }
  1045. void CBonusSystemNode::getRedChildren(TNodes &out)
  1046. {
  1047. FOREACH_PARENT(pname)
  1048. {
  1049. if(!pname->actsAsBonusSourceOnly())
  1050. {
  1051. out.insert(pname);
  1052. }
  1053. }
  1054. if(actsAsBonusSourceOnly())
  1055. {
  1056. for(CBonusSystemNode *child : children)
  1057. {
  1058. out.insert(child);
  1059. }
  1060. }
  1061. }
  1062. void CBonusSystemNode::newRedDescendant(CBonusSystemNode *descendant)
  1063. {
  1064. for(auto b : exportedBonuses)
  1065. if(b->propagator)
  1066. descendant->propagateBonus(b);
  1067. FOREACH_RED_PARENT(parent)
  1068. parent->newRedDescendant(descendant);
  1069. }
  1070. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode *descendant)
  1071. {
  1072. for(auto b : exportedBonuses)
  1073. if(b->propagator)
  1074. descendant->unpropagateBonus(b);
  1075. FOREACH_RED_PARENT(parent)
  1076. parent->removedRedDescendant(descendant);
  1077. }
  1078. void CBonusSystemNode::getRedAncestors(TNodes &out)
  1079. {
  1080. getRedParents(out);
  1081. FOREACH_RED_PARENT(p)
  1082. p->getRedAncestors(out);
  1083. }
  1084. void CBonusSystemNode::getRedDescendants(TNodes &out)
  1085. {
  1086. getRedChildren(out);
  1087. FOREACH_RED_CHILD(c)
  1088. c->getRedChildren(out);
  1089. }
  1090. void CBonusSystemNode::exportBonus(std::shared_ptr<Bonus> b)
  1091. {
  1092. if(b->propagator)
  1093. propagateBonus(b);
  1094. else
  1095. bonuses.push_back(b);
  1096. CBonusSystemNode::treeHasChanged();
  1097. }
  1098. void CBonusSystemNode::exportBonuses()
  1099. {
  1100. for(auto b : exportedBonuses)
  1101. exportBonus(b);
  1102. }
  1103. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  1104. {
  1105. return nodeType;
  1106. }
  1107. const BonusList& CBonusSystemNode::getBonusList() const
  1108. {
  1109. return bonuses;
  1110. }
  1111. const TNodesVector& CBonusSystemNode::getParentNodes() const
  1112. {
  1113. return parents;
  1114. }
  1115. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  1116. {
  1117. return children;
  1118. }
  1119. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  1120. {
  1121. nodeType = type;
  1122. }
  1123. BonusList & CBonusSystemNode::getExportedBonusList()
  1124. {
  1125. return exportedBonuses;
  1126. }
  1127. const BonusList & CBonusSystemNode::getExportedBonusList() const
  1128. {
  1129. return exportedBonuses;
  1130. }
  1131. const std::string& CBonusSystemNode::getDescription() const
  1132. {
  1133. return description;
  1134. }
  1135. void CBonusSystemNode::setDescription(const std::string &description)
  1136. {
  1137. this->description = description;
  1138. }
  1139. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  1140. {
  1141. assert(&allBonuses != &out); //todo should it work in-place?
  1142. BonusList undecided = allBonuses,
  1143. &accepted = out;
  1144. while(true)
  1145. {
  1146. int undecidedCount = static_cast<int>(undecided.size());
  1147. for(int i = 0; i < undecided.size(); i++)
  1148. {
  1149. auto b = undecided[i];
  1150. BonusLimitationContext context = {b, *this, out, undecided};
  1151. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  1152. if(decision == ILimiter::DISCARD)
  1153. {
  1154. undecided.erase(i);
  1155. i--; continue;
  1156. }
  1157. else if(decision == ILimiter::ACCEPT)
  1158. {
  1159. accepted.push_back(b);
  1160. undecided.erase(i);
  1161. i--; continue;
  1162. }
  1163. else
  1164. assert(decision == ILimiter::NOT_SURE);
  1165. }
  1166. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  1167. return;
  1168. }
  1169. }
  1170. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  1171. {
  1172. auto ret = std::make_shared<BonusList>();
  1173. limitBonuses(allBonuses, *ret);
  1174. return ret;
  1175. }
  1176. void CBonusSystemNode::treeHasChanged()
  1177. {
  1178. treeChanged++;
  1179. }
  1180. int64_t CBonusSystemNode::getTreeVersion() const
  1181. {
  1182. int64_t ret = treeChanged;
  1183. return ret << 32;
  1184. }
  1185. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1186. {
  1187. if(obj)
  1188. return obj->valOfBonuses(type, subtype);
  1189. return 0;
  1190. }
  1191. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1192. {
  1193. if(obj)
  1194. return obj->hasBonusOfType(type, subtype);
  1195. return false;
  1196. }
  1197. std::string Bonus::Description() const
  1198. {
  1199. std::ostringstream str;
  1200. if(description.empty())
  1201. {
  1202. if(stacking.empty() || stacking == "ALWAYS")
  1203. {
  1204. switch(source)
  1205. {
  1206. case ARTIFACT:
  1207. str << ArtifactID(sid).toArtifact(VLC->artifacts())->getName();
  1208. break;
  1209. case SPELL_EFFECT:
  1210. str << SpellID(sid).toSpell(VLC->spells())->getName();
  1211. break;
  1212. case CREATURE_ABILITY:
  1213. str << VLC->creh->objects[sid]->namePl;
  1214. break;
  1215. case SECONDARY_SKILL:
  1216. str << VLC->skillh->skillName(sid);
  1217. break;
  1218. case HERO_SPECIAL:
  1219. str << VLC->heroh->objects[sid]->name;
  1220. break;
  1221. default:
  1222. //todo: handle all possible sources
  1223. str << "Unknown";
  1224. break;
  1225. }
  1226. }
  1227. else
  1228. str << stacking;
  1229. }
  1230. else
  1231. {
  1232. str << description;
  1233. }
  1234. if(val != 0)
  1235. str << " " << std::showpos << val;
  1236. return str.str();
  1237. }
  1238. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  1239. {
  1240. switch(type)
  1241. {
  1242. case Bonus::PRIMARY_SKILL:
  1243. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  1244. case Bonus::SECONDARY_SKILL_PREMY:
  1245. return JsonUtils::stringNode(CSkillHandler::encodeSkillWithType(subtype));
  1246. case Bonus::SPECIAL_SPELL_LEV:
  1247. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1248. case Bonus::SPECIAL_BLESS_DAMAGE:
  1249. case Bonus::MAXED_SPELL:
  1250. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1251. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1252. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1253. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "spell", SpellID::encode(subtype)));
  1254. case Bonus::IMPROVED_NECROMANCY:
  1255. case Bonus::SPECIAL_UPGRADE:
  1256. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(subtype)));
  1257. case Bonus::GENERATE_RESOURCE:
  1258. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1259. default:
  1260. return JsonUtils::intNode(subtype);
  1261. }
  1262. }
  1263. JsonNode additionalInfoToJson(Bonus::BonusType type, CAddInfo addInfo)
  1264. {
  1265. switch(type)
  1266. {
  1267. case Bonus::SPECIAL_UPGRADE:
  1268. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(addInfo[0])));
  1269. default:
  1270. return addInfo.toJsonNode();
  1271. }
  1272. }
  1273. JsonNode durationToJson(ui16 duration)
  1274. {
  1275. std::vector<std::string> durationNames;
  1276. for(ui16 durBit = 1; durBit; durBit = durBit << 1)
  1277. {
  1278. if(duration & durBit)
  1279. durationNames.push_back(vstd::findKey(bonusDurationMap, durBit));
  1280. }
  1281. if(durationNames.size() == 1)
  1282. {
  1283. return JsonUtils::stringNode(durationNames[0]);
  1284. }
  1285. else
  1286. {
  1287. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  1288. for(std::string dur : durationNames)
  1289. node.Vector().push_back(JsonUtils::stringNode(dur));
  1290. return node;
  1291. }
  1292. }
  1293. JsonNode Bonus::toJsonNode() const
  1294. {
  1295. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1296. // only add values that might reasonably be found in config files
  1297. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1298. if(subtype != -1)
  1299. root["subtype"] = subtypeToJson(type, subtype);
  1300. if(additionalInfo != CAddInfo::NONE)
  1301. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1302. if(duration != 0)
  1303. {
  1304. JsonNode durationVec(JsonNode::JsonType::DATA_VECTOR);
  1305. for(auto & kv : bonusDurationMap)
  1306. {
  1307. if(duration & kv.second)
  1308. durationVec.Vector().push_back(JsonUtils::stringNode(kv.first));
  1309. }
  1310. root["duration"] = durationVec;
  1311. }
  1312. if(turnsRemain != 0)
  1313. root["turns"].Integer() = turnsRemain;
  1314. if(source != OTHER)
  1315. root["source"].String() = vstd::findKey(bonusSourceMap, source);
  1316. if(sid != 0)
  1317. root["sourceID"].Integer() = sid;
  1318. if(val != 0)
  1319. root["val"].Integer() = val;
  1320. if(valType != ADDITIVE_VALUE)
  1321. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1322. if(stacking != "")
  1323. root["stacking"].String() = stacking;
  1324. if(description != "")
  1325. root["description"].String() = description;
  1326. if(effectRange != NO_LIMIT)
  1327. root["effectRange"].String() = vstd::findKey(bonusLimitEffect, effectRange);
  1328. if(duration != PERMANENT)
  1329. root["duration"] = durationToJson(duration);
  1330. if(turnsRemain)
  1331. root["turns"].Integer() = turnsRemain;
  1332. if(limiter)
  1333. root["limiters"] = limiter->toJsonNode();
  1334. if(updater)
  1335. root["updater"] = updater->toJsonNode();
  1336. if(propagator)
  1337. root["propagator"].String() = vstd::findKey(bonusPropagatorMap, propagator);
  1338. return root;
  1339. }
  1340. std::string Bonus::nameForBonus() const
  1341. {
  1342. switch(type)
  1343. {
  1344. case Bonus::PRIMARY_SKILL:
  1345. return PrimarySkill::names[subtype];
  1346. case Bonus::SECONDARY_SKILL_PREMY:
  1347. return CSkillHandler::encodeSkill(subtype);
  1348. case Bonus::SPECIAL_SPELL_LEV:
  1349. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1350. case Bonus::SPECIAL_BLESS_DAMAGE:
  1351. case Bonus::MAXED_SPELL:
  1352. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1353. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1354. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1355. return (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier;
  1356. case Bonus::SPECIAL_UPGRADE:
  1357. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo[0]);
  1358. case Bonus::GENERATE_RESOURCE:
  1359. return GameConstants::RESOURCE_NAMES[subtype];
  1360. case Bonus::STACKS_SPEED:
  1361. return "speed";
  1362. default:
  1363. return vstd::findKey(bonusNameMap, type);
  1364. }
  1365. }
  1366. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype)
  1367. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  1368. {
  1369. turnsRemain = 0;
  1370. valType = ADDITIVE_VALUE;
  1371. effectRange = NO_LIMIT;
  1372. boost::algorithm::trim(description);
  1373. }
  1374. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType)
  1375. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  1376. {
  1377. turnsRemain = 0;
  1378. effectRange = NO_LIMIT;
  1379. }
  1380. Bonus::Bonus()
  1381. {
  1382. duration = PERMANENT;
  1383. turnsRemain = 0;
  1384. type = NONE;
  1385. subtype = -1;
  1386. valType = ADDITIVE_VALUE;
  1387. effectRange = NO_LIMIT;
  1388. val = 0;
  1389. source = OTHER;
  1390. sid = 0;
  1391. }
  1392. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  1393. {
  1394. propagator = Propagator;
  1395. return this->shared_from_this();
  1396. }
  1397. namespace Selector
  1398. {
  1399. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type()
  1400. {
  1401. static CSelectFieldEqual<Bonus::BonusType> stype(&Bonus::type);
  1402. return stype;
  1403. }
  1404. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype()
  1405. {
  1406. static CSelectFieldEqual<TBonusSubtype> ssubtype(&Bonus::subtype);
  1407. return ssubtype;
  1408. }
  1409. DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info()
  1410. {
  1411. static CSelectFieldEqual<CAddInfo> sinfo(&Bonus::additionalInfo);
  1412. return sinfo;
  1413. }
  1414. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType()
  1415. {
  1416. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::source);
  1417. return ssourceType;
  1418. }
  1419. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange()
  1420. {
  1421. static CSelectFieldEqual<Bonus::LimitEffect> seffectRange(&Bonus::effectRange);
  1422. return seffectRange;
  1423. }
  1424. DLL_LINKAGE CWillLastTurns turns;
  1425. DLL_LINKAGE CWillLastDays days;
  1426. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1427. {
  1428. return type()(Type).And(subtype()(Subtype));
  1429. }
  1430. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, CAddInfo info)
  1431. {
  1432. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1433. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1434. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1435. }
  1436. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1437. {
  1438. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1439. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1440. }
  1441. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1442. {
  1443. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1444. }
  1445. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1446. {
  1447. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1448. }
  1449. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1450. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1451. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1452. {
  1453. Bonus dummy;
  1454. dummy.type = type;
  1455. return sel(&dummy);
  1456. }
  1457. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1458. {
  1459. Bonus dummy;
  1460. dummy.type = type;
  1461. dummy.subtype = subtype;
  1462. return sel(&dummy);
  1463. }
  1464. }
  1465. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  1466. {
  1467. switch(node->getNodeType())
  1468. {
  1469. case CBonusSystemNode::STACK_BATTLE:
  1470. return static_cast<const CStack*>(node);
  1471. default:
  1472. return nullptr;
  1473. }
  1474. }
  1475. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  1476. {
  1477. switch(node->getNodeType())
  1478. {
  1479. case CBonusSystemNode::STACK_INSTANCE:
  1480. return (static_cast<const CStackInstance *>(node));
  1481. case CBonusSystemNode::STACK_BATTLE:
  1482. return (static_cast<const CStack*>(node))->base;
  1483. default:
  1484. return nullptr;
  1485. }
  1486. }
  1487. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1488. {
  1489. switch(node->getNodeType())
  1490. {
  1491. case CBonusSystemNode::CREATURE:
  1492. return (static_cast<const CCreature *>(node));
  1493. case CBonusSystemNode::STACK_BATTLE:
  1494. return (static_cast<const CStack*>(node))->type;
  1495. default:
  1496. const CStackInstance * csi = retrieveStackInstance(node);
  1497. if(csi)
  1498. return csi->type;
  1499. return nullptr;
  1500. }
  1501. }
  1502. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1503. {
  1504. for (ui32 i = 0; i < bonusList.size(); i++)
  1505. {
  1506. auto b = bonusList[i];
  1507. out << "Bonus " << i << "\n" << *b << std::endl;
  1508. }
  1509. return out;
  1510. }
  1511. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1512. {
  1513. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1514. if(i->second == bonus.type)
  1515. out << "\tType: " << i->first << " \t";
  1516. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1517. printField(val);
  1518. printField(subtype);
  1519. printField(duration);
  1520. printField(source);
  1521. printField(sid);
  1522. if(bonus.additionalInfo != CAddInfo::NONE)
  1523. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1524. printField(turnsRemain);
  1525. printField(valType);
  1526. if(!bonus.stacking.empty())
  1527. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1528. printField(effectRange);
  1529. #undef printField
  1530. if(bonus.limiter)
  1531. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1532. if(bonus.updater)
  1533. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1534. return out;
  1535. }
  1536. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1537. {
  1538. if (limiter)
  1539. {
  1540. //If we already have limiter list, retrieve it
  1541. auto limiterList = std::dynamic_pointer_cast<AllOfLimiter>(limiter);
  1542. if(!limiterList)
  1543. {
  1544. //Create a new limiter list with old limiter and the new one will be pushed later
  1545. limiterList = std::make_shared<AllOfLimiter>();
  1546. limiterList->add(limiter);
  1547. limiter = limiterList;
  1548. }
  1549. limiterList->add(Limiter);
  1550. }
  1551. else
  1552. {
  1553. limiter = Limiter;
  1554. }
  1555. return this->shared_from_this();
  1556. }
  1557. ILimiter::~ILimiter()
  1558. {
  1559. }
  1560. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1561. {
  1562. return false;
  1563. }
  1564. std::string ILimiter::toString() const
  1565. {
  1566. return typeid(*this).name();
  1567. }
  1568. JsonNode ILimiter::toJsonNode() const
  1569. {
  1570. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1571. root["type"].String() = toString();
  1572. return root;
  1573. }
  1574. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1575. {
  1576. const CCreature *c = retrieveCreature(&context.node);
  1577. if(!c)
  1578. return true;
  1579. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1580. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1581. }
  1582. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature & creature_, bool IncludeUpgrades)
  1583. : creature(&creature_), includeUpgrades(IncludeUpgrades)
  1584. {
  1585. }
  1586. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1587. {
  1588. creature = nullptr;
  1589. includeUpgrades = false;
  1590. }
  1591. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1592. {
  1593. creature = VLC->creh->objects[id];
  1594. }
  1595. std::string CCreatureTypeLimiter::toString() const
  1596. {
  1597. boost::format fmt("CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)");
  1598. fmt % creature->identifier % (includeUpgrades ? "true" : "false");
  1599. return fmt.str();
  1600. }
  1601. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1602. {
  1603. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1604. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1605. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->identifier));
  1606. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1607. return root;
  1608. }
  1609. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1610. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1611. {
  1612. }
  1613. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1614. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1615. {
  1616. }
  1617. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1618. {
  1619. CSelector mySelector = isSubtypeRelevant
  1620. ? Selector::typeSubtype(type, subtype)
  1621. : Selector::type()(type);
  1622. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1623. if(context.alreadyAccepted.getFirst(mySelector))
  1624. return ACCEPT;
  1625. //if there are no matching bonuses pending, we can (and must) reject right away
  1626. if(!context.stillUndecided.getFirst(mySelector))
  1627. return DISCARD;
  1628. //do not accept for now but it may change if more bonuses gets included
  1629. return NOT_SURE;
  1630. }
  1631. std::string HasAnotherBonusLimiter::toString() const
  1632. {
  1633. std::string typeName = vstd::findKey(bonusNameMap, type);
  1634. if(isSubtypeRelevant)
  1635. {
  1636. boost::format fmt("HasAnotherBonusLimiter(type=%s, subtype=%d)");
  1637. fmt % typeName % subtype;
  1638. return fmt.str();
  1639. }
  1640. else
  1641. {
  1642. boost::format fmt("HasAnotherBonusLimiter(type=%s)");
  1643. fmt % typeName;
  1644. return fmt.str();
  1645. }
  1646. }
  1647. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  1648. {
  1649. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1650. std::string typeName = vstd::findKey(bonusNameMap, type);
  1651. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  1652. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  1653. if(isSubtypeRelevant)
  1654. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  1655. return root;
  1656. }
  1657. IPropagator::~IPropagator()
  1658. {
  1659. }
  1660. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1661. {
  1662. return false;
  1663. }
  1664. CBonusSystemNode::ENodeTypes IPropagator::getPropagatorType() const
  1665. {
  1666. return CBonusSystemNode::ENodeTypes::NONE;
  1667. }
  1668. CPropagatorNodeType::CPropagatorNodeType()
  1669. :nodeType(CBonusSystemNode::ENodeTypes::UNKNOWN)
  1670. {
  1671. }
  1672. CPropagatorNodeType::CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType)
  1673. : nodeType(NodeType)
  1674. {
  1675. }
  1676. CBonusSystemNode::ENodeTypes CPropagatorNodeType::getPropagatorType() const
  1677. {
  1678. return nodeType;
  1679. }
  1680. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1681. {
  1682. return nodeType == dest->getNodeType();
  1683. }
  1684. CreatureTerrainLimiter::CreatureTerrainLimiter(int TerrainType)
  1685. : terrainType(TerrainType)
  1686. {
  1687. }
  1688. CreatureTerrainLimiter::CreatureTerrainLimiter()
  1689. : terrainType(-1)
  1690. {
  1691. }
  1692. int CreatureTerrainLimiter::limit(const BonusLimitationContext &context) const
  1693. {
  1694. const CStack *stack = retrieveStackBattle(&context.node);
  1695. if(stack)
  1696. {
  1697. if(terrainType == -1)//terrainType not specified = native
  1698. return !stack->isOnNativeTerrain();
  1699. return !stack->isOnTerrain(terrainType);
  1700. }
  1701. return true;
  1702. //TODO neutral creatues
  1703. }
  1704. std::string CreatureTerrainLimiter::toString() const
  1705. {
  1706. boost::format fmt("CreatureTerrainLimiter(terrainType=%s)");
  1707. fmt % (terrainType >= 0 ? GameConstants::TERRAIN_NAMES[terrainType] : "native");
  1708. return fmt.str();
  1709. }
  1710. JsonNode CreatureTerrainLimiter::toJsonNode() const
  1711. {
  1712. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1713. root["type"].String() = "CREATURE_TERRAIN_LIMITER";
  1714. if(terrainType >= 0)
  1715. root["parameters"].Vector().push_back(JsonUtils::stringNode(GameConstants::TERRAIN_NAMES[terrainType]));
  1716. return root;
  1717. }
  1718. CreatureFactionLimiter::CreatureFactionLimiter(TFaction creatureFaction)
  1719. : faction(creatureFaction)
  1720. {
  1721. }
  1722. CreatureFactionLimiter::CreatureFactionLimiter()
  1723. : faction((TFaction)-1)
  1724. {
  1725. }
  1726. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1727. {
  1728. const CCreature *c = retrieveCreature(&context.node);
  1729. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1730. }
  1731. std::string CreatureFactionLimiter::toString() const
  1732. {
  1733. boost::format fmt("CreatureFactionLimiter(faction=%s)");
  1734. fmt % VLC->factions()->getByIndex(faction)->getJsonKey();
  1735. return fmt.str();
  1736. }
  1737. JsonNode CreatureFactionLimiter::toJsonNode() const
  1738. {
  1739. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1740. root["type"].String() = "CREATURE_FACTION_LIMITER";
  1741. root["parameters"].Vector().push_back(JsonUtils::stringNode(VLC->factions()->getByIndex(faction)->getJsonKey()));
  1742. return root;
  1743. }
  1744. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1745. : alignment(-1)
  1746. {
  1747. }
  1748. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1749. : alignment(Alignment)
  1750. {
  1751. }
  1752. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1753. {
  1754. const CCreature *c = retrieveCreature(&context.node);
  1755. if(!c)
  1756. return true;
  1757. switch(alignment)
  1758. {
  1759. case EAlignment::GOOD:
  1760. return !c->isGood(); //if not good -> return true (drop bonus)
  1761. case EAlignment::NEUTRAL:
  1762. return c->isEvil() || c->isGood();
  1763. case EAlignment::EVIL:
  1764. return !c->isEvil();
  1765. default:
  1766. logBonus->warn("Warning: illegal alignment in limiter!");
  1767. return true;
  1768. }
  1769. }
  1770. std::string CreatureAlignmentLimiter::toString() const
  1771. {
  1772. boost::format fmt("CreatureAlignmentLimiter(alignment=%s)");
  1773. fmt % EAlignment::names[alignment];
  1774. return fmt.str();
  1775. }
  1776. JsonNode CreatureAlignmentLimiter::toJsonNode() const
  1777. {
  1778. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1779. root["type"].String() = "CREATURE_ALIGNMENT_LIMITER";
  1780. root["parameters"].Vector().push_back(JsonUtils::stringNode(EAlignment::names[alignment]));
  1781. return root;
  1782. }
  1783. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1784. :minRank(Min), maxRank(Max)
  1785. {
  1786. }
  1787. RankRangeLimiter::RankRangeLimiter()
  1788. {
  1789. minRank = maxRank = -1;
  1790. }
  1791. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1792. {
  1793. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1794. if(csi)
  1795. {
  1796. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1797. return true;
  1798. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1799. }
  1800. return true;
  1801. }
  1802. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1803. {
  1804. const CStack * s = retrieveStackBattle(&context.node);
  1805. if(s)
  1806. return s->owner != owner;
  1807. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1808. if(csi && csi->armyObj)
  1809. return csi->armyObj->tempOwner != owner;
  1810. return true;
  1811. }
  1812. StackOwnerLimiter::StackOwnerLimiter()
  1813. : owner(-1)
  1814. {
  1815. }
  1816. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1817. : owner(Owner)
  1818. {
  1819. }
  1820. // Aggregate/Boolean Limiters
  1821. void AggregateLimiter::add(TLimiterPtr limiter)
  1822. {
  1823. if(limiter)
  1824. limiters.push_back(limiter);
  1825. }
  1826. JsonNode AggregateLimiter::toJsonNode() const
  1827. {
  1828. JsonNode result(JsonNode::JsonType::DATA_VECTOR);
  1829. result.Vector().push_back(JsonUtils::stringNode(getAggregator()));
  1830. for(auto l : limiters)
  1831. result.Vector().push_back(l->toJsonNode());
  1832. return result;
  1833. }
  1834. const std::string AllOfLimiter::aggregator = "allOf";
  1835. const std::string & AllOfLimiter::getAggregator() const
  1836. {
  1837. return aggregator;
  1838. }
  1839. int AllOfLimiter::limit(const BonusLimitationContext & context) const
  1840. {
  1841. bool wasntSure = false;
  1842. for(auto limiter : limiters)
  1843. {
  1844. auto result = limiter->limit(context);
  1845. if(result == ILimiter::DISCARD)
  1846. return result;
  1847. if(result == ILimiter::NOT_SURE)
  1848. wasntSure = true;
  1849. }
  1850. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1851. }
  1852. const std::string AnyOfLimiter::aggregator = "anyOf";
  1853. const std::string & AnyOfLimiter::getAggregator() const
  1854. {
  1855. return aggregator;
  1856. }
  1857. int AnyOfLimiter::limit(const BonusLimitationContext & context) const
  1858. {
  1859. bool wasntSure = false;
  1860. for(auto limiter : limiters)
  1861. {
  1862. auto result = limiter->limit(context);
  1863. if(result == ILimiter::ACCEPT)
  1864. return result;
  1865. if(result == ILimiter::NOT_SURE)
  1866. wasntSure = true;
  1867. }
  1868. return wasntSure ? ILimiter::NOT_SURE : ILimiter::DISCARD;
  1869. }
  1870. const std::string NoneOfLimiter::aggregator = "noneOf";
  1871. const std::string & NoneOfLimiter::getAggregator() const
  1872. {
  1873. return aggregator;
  1874. }
  1875. int NoneOfLimiter::limit(const BonusLimitationContext & context) const
  1876. {
  1877. bool wasntSure = false;
  1878. for(auto limiter : limiters)
  1879. {
  1880. auto result = limiter->limit(context);
  1881. if(result == ILimiter::ACCEPT)
  1882. return ILimiter::DISCARD;
  1883. if(result == ILimiter::NOT_SURE)
  1884. wasntSure = true;
  1885. }
  1886. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1887. }
  1888. // Updaters
  1889. std::shared_ptr<Bonus> Bonus::addUpdater(TUpdaterPtr Updater)
  1890. {
  1891. updater = Updater;
  1892. return this->shared_from_this();
  1893. }
  1894. IUpdater::~IUpdater()
  1895. {
  1896. }
  1897. std::shared_ptr<Bonus> IUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1898. {
  1899. return b;
  1900. }
  1901. std::string IUpdater::toString() const
  1902. {
  1903. return typeid(*this).name();
  1904. }
  1905. JsonNode IUpdater::toJsonNode() const
  1906. {
  1907. return JsonNode(JsonNode::JsonType::DATA_NULL);
  1908. }
  1909. GrowsWithLevelUpdater::GrowsWithLevelUpdater() : valPer20(0), stepSize(1)
  1910. {
  1911. }
  1912. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  1913. {
  1914. }
  1915. std::shared_ptr<Bonus> GrowsWithLevelUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1916. {
  1917. if(context.getNodeType() == CBonusSystemNode::HERO)
  1918. {
  1919. int level = static_cast<const CGHeroInstance &>(context).level;
  1920. int steps = stepSize ? level / stepSize : level;
  1921. //rounding follows format for HMM3 creature specialty bonus
  1922. int newVal = (valPer20 * steps + 19) / 20;
  1923. //return copy of bonus with updated val
  1924. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1925. newBonus->val = newVal;
  1926. return newBonus;
  1927. }
  1928. return b;
  1929. }
  1930. std::string GrowsWithLevelUpdater::toString() const
  1931. {
  1932. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  1933. }
  1934. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  1935. {
  1936. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1937. root["type"].String() = "GROWS_WITH_LEVEL";
  1938. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  1939. if(stepSize > 1)
  1940. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  1941. return root;
  1942. }
  1943. TimesHeroLevelUpdater::TimesHeroLevelUpdater()
  1944. {
  1945. }
  1946. std::shared_ptr<Bonus> TimesHeroLevelUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1947. {
  1948. if(context.getNodeType() == CBonusSystemNode::HERO)
  1949. {
  1950. int level = static_cast<const CGHeroInstance &>(context).level;
  1951. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1952. newBonus->val *= level;
  1953. return newBonus;
  1954. }
  1955. return b;
  1956. }
  1957. std::string TimesHeroLevelUpdater::toString() const
  1958. {
  1959. return "TimesHeroLevelUpdater";
  1960. }
  1961. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  1962. {
  1963. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  1964. }
  1965. TimesStackLevelUpdater::TimesStackLevelUpdater()
  1966. {
  1967. }
  1968. std::shared_ptr<Bonus> TimesStackLevelUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1969. {
  1970. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  1971. {
  1972. int level = static_cast<const CStackInstance &>(context).getLevel();
  1973. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1974. newBonus->val *= level;
  1975. return newBonus;
  1976. }
  1977. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  1978. {
  1979. const CStack & stack = static_cast<const CStack &>(context);
  1980. //only update if stack doesn't have an instance (summons, war machines)
  1981. //otherwise we'd end up multiplying twice
  1982. if(stack.base == nullptr)
  1983. {
  1984. int level = stack.type->level;
  1985. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1986. newBonus->val *= level;
  1987. return newBonus;
  1988. }
  1989. }
  1990. return b;
  1991. }
  1992. std::string TimesStackLevelUpdater::toString() const
  1993. {
  1994. return "TimesStackLevelUpdater";
  1995. }
  1996. JsonNode TimesStackLevelUpdater::toJsonNode() const
  1997. {
  1998. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  1999. }