HeroBonus.cpp 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871
  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 "TerrainHandler.h"
  24. #include "StringConstants.h"
  25. #include "battle/BattleInfo.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  28. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  29. #define BONUS_NAME(x) { #x, Bonus::x },
  30. const std::map<std::string, Bonus::BonusType> bonusNameMap = {
  31. BONUS_LIST
  32. };
  33. #undef BONUS_NAME
  34. #define BONUS_VALUE(x) { #x, Bonus::x },
  35. const std::map<std::string, Bonus::ValueType> bonusValueMap = { BONUS_VALUE_LIST };
  36. #undef BONUS_VALUE
  37. #define BONUS_SOURCE(x) { #x, Bonus::x },
  38. const std::map<std::string, Bonus::BonusSource> bonusSourceMap = { BONUS_SOURCE_LIST };
  39. #undef BONUS_SOURCE
  40. #define BONUS_ITEM(x) { #x, Bonus::x },
  41. const std::map<std::string, ui16> bonusDurationMap =
  42. {
  43. BONUS_ITEM(PERMANENT)
  44. BONUS_ITEM(ONE_BATTLE)
  45. BONUS_ITEM(ONE_DAY)
  46. BONUS_ITEM(ONE_WEEK)
  47. BONUS_ITEM(N_TURNS)
  48. BONUS_ITEM(N_DAYS)
  49. BONUS_ITEM(UNTIL_BEING_ATTACKED)
  50. BONUS_ITEM(UNTIL_ATTACK)
  51. BONUS_ITEM(STACK_GETS_TURN)
  52. BONUS_ITEM(COMMANDER_KILLED)
  53. { "UNITL_BEING_ATTACKED", Bonus::UNTIL_BEING_ATTACKED }//typo, but used in some mods
  54. };
  55. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  56. {
  57. BONUS_ITEM(NO_LIMIT)
  58. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  59. BONUS_ITEM(ONLY_MELEE_FIGHT)
  60. BONUS_ITEM(ONLY_ENEMY_ARMY)
  61. };
  62. const std::map<std::string, TLimiterPtr> bonusLimiterMap =
  63. {
  64. {"SHOOTER_ONLY", std::make_shared<HasAnotherBonusLimiter>(Bonus::SHOOTER)},
  65. {"DRAGON_NATURE", std::make_shared<HasAnotherBonusLimiter>(Bonus::DRAGON_NATURE)},
  66. {"IS_UNDEAD", std::make_shared<HasAnotherBonusLimiter>(Bonus::UNDEAD)},
  67. {"CREATURE_NATIVE_TERRAIN", std::make_shared<CreatureTerrainLimiter>()},
  68. {"CREATURE_FACTION", std::make_shared<CreatureFactionLimiter>()},
  69. {"OPPOSITE_SIDE", std::make_shared<OppositeSideLimiter>()}
  70. };
  71. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  72. {
  73. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  74. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  75. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  76. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  77. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  78. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)},
  79. {"ALL_CREATURES", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::ALL_CREATURES)}
  80. }; //untested
  81. const std::map<std::string, TUpdaterPtr> bonusUpdaterMap =
  82. {
  83. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>()},
  84. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>()},
  85. {"ARMY_MOVEMENT", std::make_shared<ArmyMovementUpdater>()}
  86. };
  87. const std::set<std::string> deprecatedBonusSet = {
  88. "SECONDARY_SKILL_PREMY",
  89. "SECONDARY_SKILL_VAL2",
  90. "MAXED_SPELL",
  91. "LAND_MOVEMENT",
  92. "SEA_MOVEMENT",
  93. "SIGHT_RADIOUS",
  94. "NO_TYPE",
  95. "SPECIAL_SECONDARY_SKILL",
  96. "FULL_HP_REGENERATION",
  97. "KING1",
  98. "KING2",
  99. "KING3",
  100. };
  101. ///CBonusProxy
  102. CBonusProxy::CBonusProxy(const IBonusBearer * Target, CSelector Selector)
  103. : bonusListCachedLast(0),
  104. target(Target),
  105. selector(Selector),
  106. bonusList(),
  107. currentBonusListIndex(0),
  108. swapGuard()
  109. {
  110. }
  111. CBonusProxy::CBonusProxy(const CBonusProxy & other)
  112. : bonusListCachedLast(other.bonusListCachedLast),
  113. target(other.target),
  114. selector(other.selector),
  115. currentBonusListIndex(other.currentBonusListIndex),
  116. swapGuard()
  117. {
  118. bonusList[currentBonusListIndex] = other.bonusList[currentBonusListIndex];
  119. }
  120. CBonusProxy::CBonusProxy(CBonusProxy && other)
  121. : bonusListCachedLast(0),
  122. target(other.target),
  123. selector(),
  124. bonusList(),
  125. currentBonusListIndex(0),
  126. swapGuard()
  127. {
  128. std::swap(bonusListCachedLast, other.bonusListCachedLast);
  129. std::swap(selector, other.selector);
  130. std::swap(bonusList, other.bonusList);
  131. std::swap(currentBonusListIndex, other.currentBonusListIndex);
  132. }
  133. CBonusProxy & CBonusProxy::operator=(const CBonusProxy & other)
  134. {
  135. boost::lock_guard<boost::mutex> lock(swapGuard);
  136. selector = other.selector;
  137. swapBonusList(other.bonusList[other.currentBonusListIndex]);
  138. bonusListCachedLast = other.bonusListCachedLast;
  139. return *this;
  140. }
  141. CBonusProxy & CBonusProxy::operator=(CBonusProxy && other)
  142. {
  143. std::swap(bonusListCachedLast, other.bonusListCachedLast);
  144. std::swap(selector, other.selector);
  145. std::swap(bonusList, other.bonusList);
  146. std::swap(currentBonusListIndex, other.currentBonusListIndex);
  147. return *this;
  148. }
  149. void CBonusProxy::swapBonusList(TConstBonusListPtr other) const
  150. {
  151. // The idea here is to avoid changing active bonusList while it can be read by a different thread.
  152. // Because such use of shared ptr is not thread safe
  153. // So to avoid this we change the second offline instance and swap active index
  154. auto newCurrent = 1 - currentBonusListIndex;
  155. bonusList[newCurrent] = other;
  156. currentBonusListIndex = newCurrent;
  157. }
  158. TConstBonusListPtr CBonusProxy::getBonusList() const
  159. {
  160. auto needUpdateBonusList = [&]() -> bool
  161. {
  162. return target->getTreeVersion() != bonusListCachedLast || !bonusList[currentBonusListIndex];
  163. };
  164. // avoid locking if everything is up-to-date
  165. if(needUpdateBonusList())
  166. {
  167. boost::lock_guard<boost::mutex>lock(swapGuard);
  168. if(needUpdateBonusList())
  169. {
  170. //TODO: support limiters
  171. swapBonusList(target->getAllBonuses(selector, Selector::all));
  172. bonusListCachedLast = target->getTreeVersion();
  173. }
  174. }
  175. return bonusList[currentBonusListIndex];
  176. }
  177. const BonusList * CBonusProxy::operator->() const
  178. {
  179. return getBonusList().get();
  180. }
  181. CTotalsProxy::CTotalsProxy(const IBonusBearer * Target, CSelector Selector, int InitialValue)
  182. : CBonusProxy(Target, Selector),
  183. initialValue(InitialValue),
  184. meleeCachedLast(0),
  185. meleeValue(0),
  186. rangedCachedLast(0),
  187. rangedValue(0),
  188. value(0),
  189. valueCachedLast(0)
  190. {
  191. }
  192. CTotalsProxy::CTotalsProxy(const CTotalsProxy & other)
  193. : CBonusProxy(other),
  194. initialValue(other.initialValue),
  195. meleeCachedLast(other.meleeCachedLast),
  196. meleeValue(other.meleeValue),
  197. rangedCachedLast(other.rangedCachedLast),
  198. rangedValue(other.rangedValue)
  199. {
  200. }
  201. CTotalsProxy & CTotalsProxy::operator=(const CTotalsProxy & other)
  202. {
  203. CBonusProxy::operator=(other);
  204. initialValue = other.initialValue;
  205. meleeCachedLast = other.meleeCachedLast;
  206. meleeValue = other.meleeValue;
  207. rangedCachedLast = other.rangedCachedLast;
  208. rangedValue = other.rangedValue;
  209. value = other.value;
  210. valueCachedLast = other.valueCachedLast;
  211. return *this;
  212. }
  213. int CTotalsProxy::getValue() const
  214. {
  215. const auto treeVersion = target->getTreeVersion();
  216. if(treeVersion != valueCachedLast)
  217. {
  218. auto bonuses = getBonusList();
  219. value = initialValue + bonuses->totalValue();
  220. valueCachedLast = treeVersion;
  221. }
  222. return value;
  223. }
  224. int CTotalsProxy::getValueAndList(TConstBonusListPtr & outBonusList) const
  225. {
  226. const auto treeVersion = target->getTreeVersion();
  227. outBonusList = getBonusList();
  228. if(treeVersion != valueCachedLast)
  229. {
  230. value = initialValue + outBonusList->totalValue();
  231. valueCachedLast = treeVersion;
  232. }
  233. return value;
  234. }
  235. int CTotalsProxy::getMeleeValue() const
  236. {
  237. static const auto limit = Selector::effectRange()(Bonus::NO_LIMIT).Or(Selector::effectRange()(Bonus::ONLY_MELEE_FIGHT));
  238. const auto treeVersion = target->getTreeVersion();
  239. if(treeVersion != meleeCachedLast)
  240. {
  241. auto bonuses = target->getBonuses(selector, limit);
  242. meleeValue = initialValue + bonuses->totalValue();
  243. meleeCachedLast = treeVersion;
  244. }
  245. return meleeValue;
  246. }
  247. int CTotalsProxy::getRangedValue() const
  248. {
  249. static const auto limit = Selector::effectRange()(Bonus::NO_LIMIT).Or(Selector::effectRange()(Bonus::ONLY_DISTANCE_FIGHT));
  250. const auto treeVersion = target->getTreeVersion();
  251. if(treeVersion != rangedCachedLast)
  252. {
  253. auto bonuses = target->getBonuses(selector, limit);
  254. rangedValue = initialValue + bonuses->totalValue();
  255. rangedCachedLast = treeVersion;
  256. }
  257. return rangedValue;
  258. }
  259. ///CCheckProxy
  260. CCheckProxy::CCheckProxy(const IBonusBearer * Target, CSelector Selector)
  261. : target(Target),
  262. selector(Selector),
  263. cachedLast(0),
  264. hasBonus(false)
  265. {
  266. }
  267. CCheckProxy::CCheckProxy(const CCheckProxy & other)
  268. : target(other.target),
  269. selector(other.selector),
  270. cachedLast(other.cachedLast),
  271. hasBonus(other.hasBonus)
  272. {
  273. }
  274. bool CCheckProxy::getHasBonus() const
  275. {
  276. const auto treeVersion = target->getTreeVersion();
  277. if(treeVersion != cachedLast)
  278. {
  279. hasBonus = target->hasBonus(selector);
  280. cachedLast = treeVersion;
  281. }
  282. return hasBonus;
  283. }
  284. CAddInfo::CAddInfo()
  285. {
  286. }
  287. CAddInfo::CAddInfo(si32 value)
  288. {
  289. if(value != CAddInfo::NONE)
  290. push_back(value);
  291. }
  292. bool CAddInfo::operator==(si32 value) const
  293. {
  294. switch(size())
  295. {
  296. case 0:
  297. return value == CAddInfo::NONE;
  298. case 1:
  299. return operator[](0) == value;
  300. default:
  301. return false;
  302. }
  303. }
  304. bool CAddInfo::operator!=(si32 value) const
  305. {
  306. return !operator==(value);
  307. }
  308. si32 & CAddInfo::operator[](size_type pos)
  309. {
  310. if(pos >= size())
  311. resize(pos + 1, CAddInfo::NONE);
  312. return vector::operator[](pos);
  313. }
  314. si32 CAddInfo::operator[](size_type pos) const
  315. {
  316. return pos < size() ? vector::operator[](pos) : CAddInfo::NONE;
  317. }
  318. std::string CAddInfo::toString() const
  319. {
  320. return toJsonNode().toJson(true);
  321. }
  322. JsonNode CAddInfo::toJsonNode() const
  323. {
  324. if(size() < 2)
  325. {
  326. return JsonUtils::intNode(operator[](0));
  327. }
  328. else
  329. {
  330. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  331. for(si32 value : *this)
  332. node.Vector().push_back(JsonUtils::intNode(value));
  333. return node;
  334. }
  335. }
  336. std::atomic<int32_t> CBonusSystemNode::treeChanged(1);
  337. const bool CBonusSystemNode::cachingEnabled = true;
  338. BonusList::BonusList(bool BelongsToTree) : belongsToTree(BelongsToTree)
  339. {
  340. }
  341. BonusList::BonusList(const BonusList &bonusList)
  342. {
  343. bonuses.resize(bonusList.size());
  344. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  345. belongsToTree = false;
  346. }
  347. BonusList::BonusList(BonusList&& other):
  348. belongsToTree(false)
  349. {
  350. std::swap(belongsToTree, other.belongsToTree);
  351. std::swap(bonuses, other.bonuses);
  352. }
  353. BonusList& BonusList::operator=(const BonusList &bonusList)
  354. {
  355. bonuses.resize(bonusList.size());
  356. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  357. belongsToTree = false;
  358. return *this;
  359. }
  360. void BonusList::changed()
  361. {
  362. if(belongsToTree)
  363. CBonusSystemNode::treeHasChanged();
  364. }
  365. void BonusList::stackBonuses()
  366. {
  367. boost::sort(bonuses, [](std::shared_ptr<Bonus> b1, std::shared_ptr<Bonus> b2) -> bool
  368. {
  369. if(b1 == b2)
  370. return false;
  371. #define COMPARE_ATT(ATT) if(b1->ATT != b2->ATT) return b1->ATT < b2->ATT
  372. COMPARE_ATT(stacking);
  373. COMPARE_ATT(type);
  374. COMPARE_ATT(subtype);
  375. COMPARE_ATT(valType);
  376. #undef COMPARE_ATT
  377. return b1->val > b2->val;
  378. });
  379. // remove non-stacking
  380. size_t next = 1;
  381. while(next < bonuses.size())
  382. {
  383. bool remove;
  384. std::shared_ptr<Bonus> last = bonuses[next-1];
  385. std::shared_ptr<Bonus> current = bonuses[next];
  386. if(current->stacking.empty())
  387. remove = current == last;
  388. else if(current->stacking == "ALWAYS")
  389. remove = false;
  390. else
  391. remove = current->stacking == last->stacking
  392. && current->type == last->type
  393. && current->subtype == last->subtype
  394. && current->valType == last->valType;
  395. if(remove)
  396. bonuses.erase(bonuses.begin() + next);
  397. else
  398. next++;
  399. }
  400. }
  401. int BonusList::totalValue() const
  402. {
  403. struct BonusCollection
  404. {
  405. int base = 0;
  406. int percentToBase = 0;
  407. int percentToAll = 0;
  408. int additive = 0;
  409. int percentToSource;
  410. int indepMin = std::numeric_limits<int>::max();
  411. int indepMax = std::numeric_limits<int>::min();
  412. };
  413. auto percent = [](int base, int percent) -> int {return (base * (100 + percent)) / 100; };
  414. std::array <BonusCollection, Bonus::BonusSource::NUM_BONUS_SOURCE> sources = {};
  415. BonusCollection any;
  416. bool hasIndepMax = false;
  417. bool hasIndepMin = false;
  418. for(std::shared_ptr<Bonus> b : bonuses)
  419. {
  420. switch(b->valType)
  421. {
  422. case Bonus::BASE_NUMBER:
  423. sources[b->source].base += b->val;
  424. break;
  425. case Bonus::PERCENT_TO_ALL:
  426. sources[b->source].percentToAll += b->val;
  427. break;
  428. case Bonus::PERCENT_TO_BASE:
  429. sources[b->source].percentToBase += b->val;
  430. break;
  431. case Bonus::PERCENT_TO_SOURCE:
  432. sources[b->source].percentToSource += b->val;
  433. break;
  434. case Bonus::PERCENT_TO_TARGET_TYPE:
  435. sources[b->targetSourceType].percentToSource += b->val;
  436. break;
  437. case Bonus::ADDITIVE_VALUE:
  438. sources[b->source].additive += b->val;
  439. break;
  440. case Bonus::INDEPENDENT_MAX:
  441. hasIndepMax = true;
  442. vstd::amax(sources[b->source].indepMax, b->val);
  443. break;
  444. case Bonus::INDEPENDENT_MIN:
  445. hasIndepMin = true;
  446. vstd::amin(sources[b->source].indepMin, b->val);
  447. break;
  448. }
  449. }
  450. for(auto src : sources)
  451. {
  452. any.base += percent(src.base ,src.percentToSource);
  453. any.percentToBase += percent(src.percentToBase, src.percentToSource);
  454. any.percentToAll += percent(src.percentToAll, src.percentToSource);
  455. any.additive += percent(src.additive, src.percentToSource);
  456. if(hasIndepMin)
  457. vstd::amin(any.indepMin, percent(src.indepMin, src.percentToSource));
  458. if(hasIndepMax)
  459. vstd::amax(any.indepMax, percent(src.indepMin, src.percentToSource));
  460. }
  461. any.base = percent(any.base, any.percentToBase);
  462. any.base += any.additive;
  463. auto valFirst = percent(any.base ,any.percentToAll);
  464. if(hasIndepMin && hasIndepMax)
  465. assert(any.indepMin < any.indepMax);
  466. const int notIndepBonuses = (int)std::count_if(bonuses.cbegin(), bonuses.cend(), [](const std::shared_ptr<Bonus>& b)
  467. {
  468. return b->valType != Bonus::INDEPENDENT_MAX && b->valType != Bonus::INDEPENDENT_MIN;
  469. });
  470. if (hasIndepMax)
  471. {
  472. if(notIndepBonuses)
  473. vstd::amax(valFirst, any.indepMax);
  474. else
  475. valFirst = any.indepMax;
  476. }
  477. if (hasIndepMin)
  478. {
  479. if(notIndepBonuses)
  480. vstd::amin(valFirst, any.indepMin);
  481. else
  482. valFirst = any.indepMin;
  483. }
  484. return valFirst;
  485. }
  486. std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &select)
  487. {
  488. for (auto & b : bonuses)
  489. {
  490. if(select(b.get()))
  491. return b;
  492. }
  493. return nullptr;
  494. }
  495. std::shared_ptr<const Bonus> BonusList::getFirst(const CSelector &selector) const
  496. {
  497. for (auto & b : bonuses)
  498. {
  499. if(selector(b.get()))
  500. return b;
  501. }
  502. return nullptr;
  503. }
  504. void BonusList::getBonuses(BonusList & out, const CSelector &selector, const CSelector &limit) const
  505. {
  506. out.reserve(bonuses.size());
  507. for (auto & b : bonuses)
  508. {
  509. //add matching bonuses that matches limit predicate or have NO_LIMIT if no given predicate
  510. auto noFightLimit = b->effectRange == Bonus::NO_LIMIT || b->effectRange == Bonus::ONLY_ENEMY_ARMY;
  511. if(selector(b.get()) && ((!limit && noFightLimit) || ((bool)limit && limit(b.get()))))
  512. out.push_back(b);
  513. }
  514. }
  515. void BonusList::getAllBonuses(BonusList &out) const
  516. {
  517. for(auto & b : bonuses)
  518. out.push_back(b);
  519. }
  520. int BonusList::valOfBonuses(const CSelector &select) const
  521. {
  522. BonusList ret;
  523. CSelector limit = nullptr;
  524. getBonuses(ret, select, limit);
  525. return ret.totalValue();
  526. }
  527. JsonNode BonusList::toJsonNode() const
  528. {
  529. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  530. for(std::shared_ptr<Bonus> b : bonuses)
  531. node.Vector().push_back(b->toJsonNode());
  532. return node;
  533. }
  534. void BonusList::push_back(std::shared_ptr<Bonus> x)
  535. {
  536. bonuses.push_back(x);
  537. changed();
  538. }
  539. BonusList::TInternalContainer::iterator BonusList::erase(const int position)
  540. {
  541. changed();
  542. return bonuses.erase(bonuses.begin() + position);
  543. }
  544. void BonusList::clear()
  545. {
  546. bonuses.clear();
  547. changed();
  548. }
  549. std::vector<BonusList*>::size_type BonusList::operator-=(std::shared_ptr<Bonus> const &i)
  550. {
  551. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  552. if(itr == bonuses.end())
  553. return false;
  554. bonuses.erase(itr);
  555. changed();
  556. return true;
  557. }
  558. void BonusList::resize(BonusList::TInternalContainer::size_type sz, std::shared_ptr<Bonus> c )
  559. {
  560. bonuses.resize(sz, c);
  561. changed();
  562. }
  563. void BonusList::reserve(TInternalContainer::size_type sz)
  564. {
  565. bonuses.reserve(sz);
  566. }
  567. void BonusList::insert(BonusList::TInternalContainer::iterator position, BonusList::TInternalContainer::size_type n, std::shared_ptr<Bonus> const &x)
  568. {
  569. bonuses.insert(position, n, x);
  570. changed();
  571. }
  572. CSelector IBonusBearer::anaffectedByMoraleSelector =
  573. Selector::type()(Bonus::NON_LIVING)
  574. .Or(Selector::type()(Bonus::UNDEAD))
  575. .Or(Selector::type()(Bonus::SIEGE_WEAPON))
  576. .Or(Selector::type()(Bonus::NO_MORALE))
  577. .Or(Selector::type()(Bonus::BLOCK_MORALE));
  578. CSelector IBonusBearer::moraleSelector = Selector::type()(Bonus::MORALE);
  579. CSelector IBonusBearer::luckSelector = Selector::type()(Bonus::LUCK);
  580. CSelector IBonusBearer::selfMoraleSelector = Selector::type()(Bonus::SELF_MORALE);
  581. CSelector IBonusBearer::selfLuckSelector = Selector::type()(Bonus::SELF_LUCK);
  582. IBonusBearer::IBonusBearer()
  583. :anaffectedByMorale(this, anaffectedByMoraleSelector),
  584. moraleValue(this, moraleSelector, 0),
  585. luckValue(this, luckSelector, 0),
  586. selfMorale(this, selfMoraleSelector),
  587. selfLuck(this, selfLuckSelector)
  588. {
  589. }
  590. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  591. {
  592. return valOfBonuses(Selector::type()(type).And(selector));
  593. }
  594. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype) const
  595. {
  596. //This part is performance-critical
  597. std::string cachingStr = "type_" + std::to_string(int(type)) + "_" + std::to_string(subtype);
  598. CSelector s = Selector::type()(type);
  599. if(subtype != -1)
  600. s = s.And(Selector::subtype()(subtype));
  601. return valOfBonuses(s, cachingStr);
  602. }
  603. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  604. {
  605. CSelector limit = nullptr;
  606. TConstBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  607. return hlp->totalValue();
  608. }
  609. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  610. {
  611. //TODO: We don't need to count all bonuses and could break on first matching
  612. return getBonuses(selector, cachingStr)->size() > 0;
  613. }
  614. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  615. {
  616. return getBonuses(selector, limit, cachingStr)->size() > 0;
  617. }
  618. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  619. {
  620. //This part is performance-ciritcal
  621. std::string cachingStr = "type_" + std::to_string(int(type)) + "_" + std::to_string(subtype);
  622. CSelector s = Selector::type()(type);
  623. if(subtype != -1)
  624. s = s.And(Selector::subtype()(subtype));
  625. return hasBonus(s, cachingStr);
  626. }
  627. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  628. {
  629. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  630. }
  631. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  632. {
  633. return getAllBonuses(selector, limit, nullptr, cachingStr);
  634. }
  635. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  636. {
  637. boost::format fmt("source_%did_%d");
  638. fmt % (int)source % sourceID;
  639. return hasBonus(Selector::source(source,sourceID), fmt.str());
  640. }
  641. int IBonusBearer::MoraleVal() const
  642. {
  643. if(anaffectedByMorale.getHasBonus())
  644. return 0;
  645. int ret = moraleValue.getValue();
  646. if(selfMorale.getHasBonus()) //eg. minotaur
  647. vstd::amax(ret, +1);
  648. return vstd::abetween(ret, -3, +3);
  649. }
  650. int IBonusBearer::LuckVal() const
  651. {
  652. if(hasBonusOfType(Bonus::NO_LUCK))
  653. return 0;
  654. int ret = luckValue.getValue();
  655. if(selfLuck.getHasBonus()) //eg. halfling
  656. vstd::amax(ret, +1);
  657. return vstd::abetween(ret, -3, +3);
  658. }
  659. int IBonusBearer::MoraleValAndBonusList(TConstBonusListPtr & bonusList) const
  660. {
  661. if(anaffectedByMorale.getHasBonus())
  662. {
  663. if(!bonusList->empty())
  664. bonusList = std::make_shared<const BonusList>();
  665. return 0;
  666. }
  667. int ret = moraleValue.getValueAndList(bonusList);
  668. if(selfMorale.getHasBonus()) //eg. minotaur
  669. vstd::amax(ret, +1);
  670. return vstd::abetween(ret, -3, +3);
  671. }
  672. int IBonusBearer::LuckValAndBonusList(TConstBonusListPtr & bonusList) const
  673. {
  674. if(hasBonusOfType(Bonus::NO_LUCK))
  675. {
  676. if(!bonusList->empty())
  677. bonusList = std::make_shared<const BonusList>();
  678. return 0;
  679. }
  680. int ret = luckValue.getValueAndList(bonusList);
  681. if(selfLuck.getHasBonus()) //eg. halfling
  682. vstd::amax(ret, +1);
  683. return vstd::abetween(ret, -3, +3);
  684. }
  685. ui32 IBonusBearer::MaxHealth() const
  686. {
  687. const std::string cachingStr = "type_STACK_HEALTH";
  688. static const auto selector = Selector::type()(Bonus::STACK_HEALTH);
  689. auto value = valOfBonuses(selector, cachingStr);
  690. return std::max(1, value); //never 0
  691. }
  692. int IBonusBearer::getAttack(bool ranged) const
  693. {
  694. const std::string cachingStr = "type_PRIMARY_SKILLs_ATTACK";
  695. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  696. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  697. }
  698. int IBonusBearer::getDefense(bool ranged) const
  699. {
  700. const std::string cachingStr = "type_PRIMARY_SKILLs_DEFENSE";
  701. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  702. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  703. }
  704. int IBonusBearer::getMinDamage(bool ranged) const
  705. {
  706. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_1";
  707. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1));
  708. return valOfBonuses(selector, cachingStr);
  709. }
  710. int IBonusBearer::getMaxDamage(bool ranged) const
  711. {
  712. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_2";
  713. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2));
  714. return valOfBonuses(selector, cachingStr);
  715. }
  716. si32 IBonusBearer::manaLimit() const
  717. {
  718. return 0;
  719. }
  720. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  721. {
  722. static const CSelector selectorAllSkills = Selector::type()(Bonus::PRIMARY_SKILL);
  723. static const std::string keyAllSkills = "type_PRIMARY_SKILL";
  724. auto allSkills = getBonuses(selectorAllSkills, keyAllSkills);
  725. auto ret = allSkills->valOfBonuses(Selector::subtype()(id));
  726. auto minSkillValue = (id == PrimarySkill::SPELL_POWER || id == PrimarySkill::KNOWLEDGE) ? 1 : 0;
  727. vstd::amax(ret, minSkillValue); //otherwise, some artifacts may cause negative skill value effect
  728. return ret; //sp=0 works in old saves
  729. }
  730. si32 IBonusBearer::magicResistance() const
  731. {
  732. return valOfBonuses(Bonus::MAGIC_RESISTANCE);
  733. }
  734. ui32 IBonusBearer::Speed(int turn, bool useBind) const
  735. {
  736. //war machines cannot move
  737. if(hasBonus(Selector::type()(Bonus::SIEGE_WEAPON).And(Selector::turns(turn))))
  738. {
  739. return 0;
  740. }
  741. //bind effect check - doesn't influence stack initiative
  742. if(useBind && hasBonus(Selector::type()(Bonus::BIND_EFFECT).And(Selector::turns(turn))))
  743. {
  744. return 0;
  745. }
  746. return valOfBonuses(Selector::type()(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  747. }
  748. bool IBonusBearer::isLiving() const //TODO: theoreticaly there exists "LIVING" bonus in stack experience documentation
  749. {
  750. static const std::string cachingStr = "IBonusBearer::isLiving";
  751. static const CSelector selector = Selector::type()(Bonus::UNDEAD)
  752. .Or(Selector::type()(Bonus::NON_LIVING))
  753. .Or(Selector::type()(Bonus::GARGOYLE))
  754. .Or(Selector::type()(Bonus::SIEGE_WEAPON));
  755. return !hasBonus(selector, cachingStr);
  756. }
  757. std::shared_ptr<const Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  758. {
  759. auto bonuses = getAllBonuses(selector, Selector::all);
  760. return bonuses->getFirst(Selector::all);
  761. }
  762. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  763. {
  764. switch(node->getNodeType())
  765. {
  766. case CBonusSystemNode::STACK_BATTLE:
  767. return static_cast<const CStack*>(node);
  768. default:
  769. return nullptr;
  770. }
  771. }
  772. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  773. {
  774. switch(node->getNodeType())
  775. {
  776. case CBonusSystemNode::STACK_INSTANCE:
  777. return (static_cast<const CStackInstance *>(node));
  778. case CBonusSystemNode::STACK_BATTLE:
  779. return (static_cast<const CStack*>(node))->base;
  780. default:
  781. return nullptr;
  782. }
  783. }
  784. PlayerColor CBonusSystemNode::retrieveNodeOwner(const CBonusSystemNode * node)
  785. {
  786. return node ? node->getOwner() : PlayerColor::CANNOT_DETERMINE;
  787. }
  788. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector)
  789. {
  790. auto ret = bonuses.getFirst(selector);
  791. if(ret)
  792. return ret;
  793. FOREACH_PARENT(pname)
  794. {
  795. ret = pname->getBonusLocalFirst(selector);
  796. if (ret)
  797. return ret;
  798. }
  799. return nullptr;
  800. }
  801. std::shared_ptr<const Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector) const
  802. {
  803. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  804. }
  805. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  806. {
  807. for (auto & elem : parents)
  808. {
  809. const CBonusSystemNode *parent = elem;
  810. out.insert(parent);
  811. }
  812. }
  813. void CBonusSystemNode::getParents(TNodes &out)
  814. {
  815. for (auto & elem : parents)
  816. {
  817. const CBonusSystemNode *parent = elem;
  818. out.insert(const_cast<CBonusSystemNode*>(parent));
  819. }
  820. }
  821. void CBonusSystemNode::getAllParents(TCNodes & out) const //retrieves list of parent nodes (nodes to inherit bonuses from)
  822. {
  823. for(auto parent : parents)
  824. {
  825. out.insert(parent);
  826. parent->getAllParents(out);
  827. }
  828. }
  829. void CBonusSystemNode::getAllBonusesRec(BonusList &out) const
  830. {
  831. //out has been reserved sufficient capacity at getAllBonuses() call
  832. BonusList beforeUpdate;
  833. TCNodes lparents;
  834. getAllParents(lparents);
  835. if (lparents.size())
  836. {
  837. //estimate on how many bonuses are missing yet - must be positive
  838. beforeUpdate.reserve(std::max(out.capacity() - out.size(), bonuses.size()));
  839. }
  840. else
  841. {
  842. beforeUpdate.reserve(bonuses.size()); //at most all local bonuses
  843. }
  844. for (auto parent : lparents)
  845. {
  846. parent->getAllBonusesRec(beforeUpdate);
  847. }
  848. bonuses.getAllBonuses(beforeUpdate);
  849. for(const auto & b : beforeUpdate)
  850. {
  851. auto updated = b->updater
  852. ? getUpdatedBonus(b, b->updater)
  853. : b;
  854. //do not add bonus with updater
  855. bool bonusExists = false;
  856. for (auto const & bonus : out )
  857. {
  858. if (bonus == updated)
  859. bonusExists = true;
  860. if (bonus->updater && bonus->updater == updated->updater)
  861. bonusExists = true;
  862. }
  863. if (!bonusExists)
  864. out.push_back(updated);
  865. }
  866. }
  867. TConstBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  868. {
  869. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  870. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  871. {
  872. // Exclusive access for one thread
  873. boost::lock_guard<boost::mutex> lock(sync);
  874. // If the bonus system tree changes(state of a single node or the relations to each other) then
  875. // cache all bonus objects. Selector objects doesn't matter.
  876. if (cachedLast != treeChanged)
  877. {
  878. BonusList allBonuses;
  879. allBonuses.reserve(cachedBonuses.capacity()); //we assume we'll get about the same number of bonuses
  880. cachedBonuses.clear();
  881. cachedRequests.clear();
  882. getAllBonusesRec(allBonuses);
  883. limitBonuses(allBonuses, cachedBonuses);
  884. cachedBonuses.stackBonuses();
  885. cachedLast = treeChanged;
  886. }
  887. // If a bonus system request comes with a caching string then look up in the map if there are any
  888. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  889. if(!cachingStr.empty())
  890. {
  891. auto it = cachedRequests.find(cachingStr);
  892. if(it != cachedRequests.end())
  893. {
  894. //Cached list contains bonuses for our query with applied limiters
  895. return it->second;
  896. }
  897. }
  898. //We still don't have the bonuses (didn't returned them from cache)
  899. //Perform bonus selection
  900. auto ret = std::make_shared<BonusList>();
  901. cachedBonuses.getBonuses(*ret, selector, limit);
  902. // Save the results in the cache
  903. if(!cachingStr.empty())
  904. cachedRequests[cachingStr] = ret;
  905. return ret;
  906. }
  907. else
  908. {
  909. return getAllBonusesWithoutCaching(selector, limit, root);
  910. }
  911. }
  912. TConstBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  913. {
  914. auto ret = std::make_shared<BonusList>();
  915. // Get bonus results without caching enabled.
  916. BonusList beforeLimiting, afterLimiting;
  917. getAllBonusesRec(beforeLimiting);
  918. if(!root || root == this)
  919. {
  920. limitBonuses(beforeLimiting, afterLimiting);
  921. }
  922. else if(root)
  923. {
  924. //We want to limit our query against an external node. We get all its bonuses,
  925. // add the ones we're considering and see if they're cut out by limiters
  926. BonusList rootBonuses, limitedRootBonuses;
  927. getAllBonusesRec(rootBonuses);
  928. for(auto b : beforeLimiting)
  929. rootBonuses.push_back(b);
  930. root->limitBonuses(rootBonuses, limitedRootBonuses);
  931. for(auto b : beforeLimiting)
  932. if(vstd::contains(limitedRootBonuses, b))
  933. afterLimiting.push_back(b);
  934. }
  935. afterLimiting.getBonuses(*ret, selector, limit);
  936. ret->stackBonuses();
  937. return ret;
  938. }
  939. std::shared_ptr<Bonus> CBonusSystemNode::getUpdatedBonus(const std::shared_ptr<Bonus> & b, const TUpdaterPtr updater) const
  940. {
  941. assert(updater);
  942. return updater->createUpdatedBonus(b, * this);
  943. }
  944. TConstBonusListPtr CBonusSystemNode::getUpdatedBonusList(const BonusList & out, const CSelector & sel) const
  945. {
  946. auto ret = std::make_shared<BonusList>();
  947. for(const auto & b : out)
  948. {
  949. if(sel(b.get()) && b->updater)
  950. ret->push_back(getUpdatedBonus(b, b->updater));
  951. else
  952. ret->push_back(b);
  953. }
  954. return ret;
  955. }
  956. CBonusSystemNode::CBonusSystemNode()
  957. :CBonusSystemNode(false)
  958. {
  959. }
  960. CBonusSystemNode::CBonusSystemNode(bool isHypotetic)
  961. : bonuses(true),
  962. exportedBonuses(true),
  963. nodeType(UNKNOWN),
  964. cachedLast(0),
  965. sync(),
  966. isHypotheticNode(isHypotetic)
  967. {
  968. }
  969. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType)
  970. : bonuses(true),
  971. exportedBonuses(true),
  972. nodeType(NodeType),
  973. cachedLast(0),
  974. sync(),
  975. isHypotheticNode(false)
  976. {
  977. }
  978. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other):
  979. bonuses(std::move(other.bonuses)),
  980. exportedBonuses(std::move(other.exportedBonuses)),
  981. nodeType(other.nodeType),
  982. description(other.description),
  983. cachedLast(0),
  984. sync(),
  985. isHypotheticNode(other.isHypotheticNode)
  986. {
  987. std::swap(parents, other.parents);
  988. std::swap(children, other.children);
  989. //fixing bonus tree without recalculation
  990. if(!isHypothetic())
  991. {
  992. for(CBonusSystemNode * n : parents)
  993. {
  994. n->children -= &other;
  995. n->children.push_back(this);
  996. }
  997. }
  998. for(CBonusSystemNode * n : children)
  999. {
  1000. n->parents -= &other;
  1001. n->parents.push_back(this);
  1002. }
  1003. //cache ignored
  1004. //cachedBonuses
  1005. //cachedRequests
  1006. }
  1007. CBonusSystemNode::~CBonusSystemNode()
  1008. {
  1009. detachFromAll();
  1010. if(children.size())
  1011. {
  1012. while(children.size())
  1013. children.front()->detachFrom(*this);
  1014. }
  1015. }
  1016. void CBonusSystemNode::attachTo(CBonusSystemNode & parent)
  1017. {
  1018. assert(!vstd::contains(parents, &parent));
  1019. parents.push_back(&parent);
  1020. if(!isHypothetic())
  1021. {
  1022. if(parent.actsAsBonusSourceOnly())
  1023. parent.newRedDescendant(*this);
  1024. else
  1025. newRedDescendant(parent);
  1026. parent.newChildAttached(*this);
  1027. }
  1028. CBonusSystemNode::treeHasChanged();
  1029. }
  1030. void CBonusSystemNode::detachFrom(CBonusSystemNode & parent)
  1031. {
  1032. assert(vstd::contains(parents, &parent));
  1033. if(!isHypothetic())
  1034. {
  1035. if(parent.actsAsBonusSourceOnly())
  1036. parent.removedRedDescendant(*this);
  1037. else
  1038. removedRedDescendant(parent);
  1039. }
  1040. if (vstd::contains(parents, &parent))
  1041. {
  1042. parents -= &parent;
  1043. }
  1044. else
  1045. {
  1046. logBonus->error("Error on Detach. Node %s (nodeType=%d) has not parent %s (nodeType=%d)"
  1047. , nodeShortInfo(), nodeType, parent.nodeShortInfo(), parent.nodeType);
  1048. }
  1049. if(!isHypothetic())
  1050. {
  1051. parent.childDetached(*this);
  1052. }
  1053. CBonusSystemNode::treeHasChanged();
  1054. }
  1055. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  1056. {
  1057. removeBonuses(s);
  1058. for(CBonusSystemNode * child : children)
  1059. child->removeBonusesRecursive(s);
  1060. }
  1061. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  1062. {
  1063. BonusList bl;
  1064. exportedBonuses.getBonuses(bl, s, Selector::all);
  1065. for(auto b : bl)
  1066. {
  1067. b->turnsRemain--;
  1068. if(b->turnsRemain <= 0)
  1069. removeBonus(b);
  1070. }
  1071. for(CBonusSystemNode *child : children)
  1072. child->reduceBonusDurations(s);
  1073. }
  1074. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  1075. {
  1076. //turnsRemain shouldn't be zero for following durations
  1077. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  1078. {
  1079. assert(b->turnsRemain);
  1080. }
  1081. assert(!vstd::contains(exportedBonuses, b));
  1082. exportedBonuses.push_back(b);
  1083. exportBonus(b);
  1084. CBonusSystemNode::treeHasChanged();
  1085. }
  1086. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  1087. {
  1088. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  1089. if(bonus)
  1090. bonus->val += b->val;
  1091. else
  1092. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  1093. }
  1094. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  1095. {
  1096. exportedBonuses -= b;
  1097. if(b->propagator)
  1098. unpropagateBonus(b);
  1099. else
  1100. bonuses -= b;
  1101. CBonusSystemNode::treeHasChanged();
  1102. }
  1103. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  1104. {
  1105. BonusList toRemove;
  1106. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  1107. for(auto bonus : toRemove)
  1108. removeBonus(bonus);
  1109. }
  1110. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  1111. {
  1112. switch(nodeType)
  1113. {
  1114. case CREATURE:
  1115. case ARTIFACT:
  1116. case ARTIFACT_INSTANCE:
  1117. return true;
  1118. default:
  1119. return false;
  1120. }
  1121. }
  1122. void CBonusSystemNode::propagateBonus(std::shared_ptr<Bonus> b, const CBonusSystemNode & source)
  1123. {
  1124. if(b->propagator->shouldBeAttached(this))
  1125. {
  1126. auto propagated = b->propagationUpdater
  1127. ? source.getUpdatedBonus(b, b->propagationUpdater)
  1128. : b;
  1129. bonuses.push_back(propagated);
  1130. logBonus->trace("#$# %s #propagated to# %s", propagated->Description(), nodeName());
  1131. }
  1132. FOREACH_RED_CHILD(child)
  1133. child->propagateBonus(b, source);
  1134. }
  1135. void CBonusSystemNode::unpropagateBonus(std::shared_ptr<Bonus> b)
  1136. {
  1137. if(b->propagator->shouldBeAttached(this))
  1138. {
  1139. bonuses -= b;
  1140. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  1141. }
  1142. FOREACH_RED_CHILD(child)
  1143. child->unpropagateBonus(b);
  1144. }
  1145. void CBonusSystemNode::newChildAttached(CBonusSystemNode & child)
  1146. {
  1147. assert(!vstd::contains(children, &child));
  1148. children.push_back(&child);
  1149. }
  1150. void CBonusSystemNode::childDetached(CBonusSystemNode & child)
  1151. {
  1152. if(vstd::contains(children, &child))
  1153. children -= &child;
  1154. else
  1155. {
  1156. logBonus->error("Error on Detach. Node %s (nodeType=%d) is not a child of %s (nodeType=%d)"
  1157. , child.nodeShortInfo(), child.nodeType, nodeShortInfo(), nodeType);
  1158. }
  1159. }
  1160. void CBonusSystemNode::detachFromAll()
  1161. {
  1162. while(parents.size())
  1163. detachFrom(*parents.front());
  1164. }
  1165. bool CBonusSystemNode::isIndependentNode() const
  1166. {
  1167. return parents.empty() && children.empty();
  1168. }
  1169. std::string CBonusSystemNode::nodeName() const
  1170. {
  1171. return description.size()
  1172. ? description
  1173. : std::string("Bonus system node of type ") + typeid(*this).name();
  1174. }
  1175. std::string CBonusSystemNode::nodeShortInfo() const
  1176. {
  1177. std::ostringstream str;
  1178. str << "'" << typeid(* this).name() << "'";
  1179. description.length() > 0
  1180. ? str << " (" << description << ")"
  1181. : str << " (no description)";
  1182. return str.str();
  1183. }
  1184. void CBonusSystemNode::deserializationFix()
  1185. {
  1186. exportBonuses();
  1187. }
  1188. void CBonusSystemNode::getRedParents(TNodes & out)
  1189. {
  1190. FOREACH_PARENT(pname)
  1191. {
  1192. if(pname->actsAsBonusSourceOnly())
  1193. {
  1194. out.insert(pname);
  1195. }
  1196. }
  1197. if(!actsAsBonusSourceOnly())
  1198. {
  1199. for(CBonusSystemNode *child : children)
  1200. {
  1201. out.insert(child);
  1202. }
  1203. }
  1204. }
  1205. void CBonusSystemNode::getRedChildren(TNodes &out)
  1206. {
  1207. FOREACH_PARENT(pname)
  1208. {
  1209. if(!pname->actsAsBonusSourceOnly())
  1210. {
  1211. out.insert(pname);
  1212. }
  1213. }
  1214. if(actsAsBonusSourceOnly())
  1215. {
  1216. for(CBonusSystemNode *child : children)
  1217. {
  1218. out.insert(child);
  1219. }
  1220. }
  1221. }
  1222. void CBonusSystemNode::newRedDescendant(CBonusSystemNode & descendant)
  1223. {
  1224. for(auto b : exportedBonuses)
  1225. {
  1226. if(b->propagator)
  1227. descendant.propagateBonus(b, *this);
  1228. }
  1229. TNodes redParents;
  1230. getRedAncestors(redParents); //get all red parents recursively
  1231. for(auto parent : redParents)
  1232. {
  1233. for(auto b : parent->exportedBonuses)
  1234. {
  1235. if(b->propagator)
  1236. descendant.propagateBonus(b, *this);
  1237. }
  1238. }
  1239. }
  1240. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode & descendant)
  1241. {
  1242. for(auto b : exportedBonuses)
  1243. if(b->propagator)
  1244. descendant.unpropagateBonus(b);
  1245. TNodes redParents;
  1246. getRedAncestors(redParents); //get all red parents recursively
  1247. for(auto parent : redParents)
  1248. {
  1249. for(auto b : parent->exportedBonuses)
  1250. if(b->propagator)
  1251. descendant.unpropagateBonus(b);
  1252. }
  1253. }
  1254. void CBonusSystemNode::getRedAncestors(TNodes &out)
  1255. {
  1256. getRedParents(out);
  1257. TNodes redParents;
  1258. getRedParents(redParents);
  1259. for(CBonusSystemNode * parent : redParents)
  1260. parent->getRedAncestors(out);
  1261. }
  1262. void CBonusSystemNode::getRedDescendants(TNodes &out)
  1263. {
  1264. getRedChildren(out);
  1265. FOREACH_RED_CHILD(c)
  1266. c->getRedChildren(out);
  1267. }
  1268. void CBonusSystemNode::exportBonus(std::shared_ptr<Bonus> b)
  1269. {
  1270. if(b->propagator)
  1271. propagateBonus(b, *this);
  1272. else
  1273. bonuses.push_back(b);
  1274. CBonusSystemNode::treeHasChanged();
  1275. }
  1276. void CBonusSystemNode::exportBonuses()
  1277. {
  1278. for(auto b : exportedBonuses)
  1279. exportBonus(b);
  1280. }
  1281. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  1282. {
  1283. return nodeType;
  1284. }
  1285. const BonusList& CBonusSystemNode::getBonusList() const
  1286. {
  1287. return bonuses;
  1288. }
  1289. const TNodesVector& CBonusSystemNode::getParentNodes() const
  1290. {
  1291. return parents;
  1292. }
  1293. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  1294. {
  1295. return children;
  1296. }
  1297. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  1298. {
  1299. nodeType = type;
  1300. }
  1301. BonusList & CBonusSystemNode::getExportedBonusList()
  1302. {
  1303. return exportedBonuses;
  1304. }
  1305. const BonusList & CBonusSystemNode::getExportedBonusList() const
  1306. {
  1307. return exportedBonuses;
  1308. }
  1309. const std::string& CBonusSystemNode::getDescription() const
  1310. {
  1311. return description;
  1312. }
  1313. void CBonusSystemNode::setDescription(const std::string &description)
  1314. {
  1315. this->description = description;
  1316. }
  1317. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  1318. {
  1319. assert(&allBonuses != &out); //todo should it work in-place?
  1320. BonusList undecided = allBonuses,
  1321. &accepted = out;
  1322. while(true)
  1323. {
  1324. int undecidedCount = static_cast<int>(undecided.size());
  1325. for(int i = 0; i < undecided.size(); i++)
  1326. {
  1327. auto b = undecided[i];
  1328. BonusLimitationContext context = {b, *this, out, undecided};
  1329. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  1330. if(decision == ILimiter::DISCARD)
  1331. {
  1332. undecided.erase(i);
  1333. i--; continue;
  1334. }
  1335. else if(decision == ILimiter::ACCEPT)
  1336. {
  1337. accepted.push_back(b);
  1338. undecided.erase(i);
  1339. i--; continue;
  1340. }
  1341. else
  1342. assert(decision == ILimiter::NOT_SURE);
  1343. }
  1344. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  1345. return;
  1346. }
  1347. }
  1348. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  1349. {
  1350. auto ret = std::make_shared<BonusList>();
  1351. limitBonuses(allBonuses, *ret);
  1352. return ret;
  1353. }
  1354. void CBonusSystemNode::treeHasChanged()
  1355. {
  1356. treeChanged++;
  1357. }
  1358. int64_t CBonusSystemNode::getTreeVersion() const
  1359. {
  1360. int64_t ret = treeChanged;
  1361. return ret << 32;
  1362. }
  1363. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1364. {
  1365. if(obj)
  1366. return obj->valOfBonuses(type, subtype);
  1367. return 0;
  1368. }
  1369. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1370. {
  1371. if(obj)
  1372. return obj->hasBonusOfType(type, subtype);
  1373. return false;
  1374. }
  1375. std::string Bonus::Description(boost::optional<si32> customValue) const
  1376. {
  1377. std::ostringstream str;
  1378. if(description.empty())
  1379. {
  1380. if(stacking.empty() || stacking == "ALWAYS")
  1381. {
  1382. switch(source)
  1383. {
  1384. case ARTIFACT:
  1385. str << ArtifactID(sid).toArtifact(VLC->artifacts())->getNameTranslated();
  1386. break;
  1387. case SPELL_EFFECT:
  1388. str << SpellID(sid).toSpell(VLC->spells())->getNameTranslated();
  1389. break;
  1390. case CREATURE_ABILITY:
  1391. str << VLC->creh->objects[sid]->getNamePluralTranslated();
  1392. break;
  1393. case SECONDARY_SKILL:
  1394. str << VLC->skillh->getByIndex(sid)->getNameTranslated();
  1395. break;
  1396. case HERO_SPECIAL:
  1397. str << VLC->heroh->objects[sid]->getNameTranslated();
  1398. break;
  1399. default:
  1400. //todo: handle all possible sources
  1401. str << "Unknown";
  1402. break;
  1403. }
  1404. }
  1405. else
  1406. str << stacking;
  1407. }
  1408. else
  1409. {
  1410. str << description;
  1411. }
  1412. if(auto value = customValue.value_or(val))
  1413. str << " " << std::showpos << value;
  1414. return str.str();
  1415. }
  1416. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  1417. {
  1418. switch(type)
  1419. {
  1420. case Bonus::PRIMARY_SKILL:
  1421. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  1422. case Bonus::SPECIAL_SPELL_LEV:
  1423. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1424. case Bonus::SPELL:
  1425. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1426. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1427. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1428. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "spell", SpellID::encode(subtype)));
  1429. case Bonus::IMPROVED_NECROMANCY:
  1430. case Bonus::SPECIAL_UPGRADE:
  1431. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(subtype)));
  1432. case Bonus::GENERATE_RESOURCE:
  1433. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1434. default:
  1435. return JsonUtils::intNode(subtype);
  1436. }
  1437. }
  1438. JsonNode additionalInfoToJson(Bonus::BonusType type, CAddInfo addInfo)
  1439. {
  1440. switch(type)
  1441. {
  1442. case Bonus::SPECIAL_UPGRADE:
  1443. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(addInfo[0])));
  1444. default:
  1445. return addInfo.toJsonNode();
  1446. }
  1447. }
  1448. JsonNode durationToJson(ui16 duration)
  1449. {
  1450. std::vector<std::string> durationNames;
  1451. for(ui16 durBit = 1; durBit; durBit = durBit << 1)
  1452. {
  1453. if(duration & durBit)
  1454. durationNames.push_back(vstd::findKey(bonusDurationMap, durBit));
  1455. }
  1456. if(durationNames.size() == 1)
  1457. {
  1458. return JsonUtils::stringNode(durationNames[0]);
  1459. }
  1460. else
  1461. {
  1462. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  1463. for(std::string dur : durationNames)
  1464. node.Vector().push_back(JsonUtils::stringNode(dur));
  1465. return node;
  1466. }
  1467. }
  1468. JsonNode Bonus::toJsonNode() const
  1469. {
  1470. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1471. // only add values that might reasonably be found in config files
  1472. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1473. if(subtype != -1)
  1474. root["subtype"] = subtypeToJson(type, subtype);
  1475. if(additionalInfo != CAddInfo::NONE)
  1476. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1477. if(duration != 0)
  1478. {
  1479. JsonNode durationVec(JsonNode::JsonType::DATA_VECTOR);
  1480. for(auto & kv : bonusDurationMap)
  1481. {
  1482. if(duration & kv.second)
  1483. durationVec.Vector().push_back(JsonUtils::stringNode(kv.first));
  1484. }
  1485. root["duration"] = durationVec;
  1486. }
  1487. if(turnsRemain != 0)
  1488. root["turns"].Integer() = turnsRemain;
  1489. if(source != OTHER)
  1490. root["sourceType"].String() = vstd::findKey(bonusSourceMap, source);
  1491. if(targetSourceType != OTHER)
  1492. root["targetSourceType"].String() = vstd::findKey(bonusSourceMap, targetSourceType);
  1493. if(sid != 0)
  1494. root["sourceID"].Integer() = sid;
  1495. if(val != 0)
  1496. root["val"].Integer() = val;
  1497. if(valType != ADDITIVE_VALUE)
  1498. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1499. if(!stacking.empty())
  1500. root["stacking"].String() = stacking;
  1501. if(!description.empty())
  1502. root["description"].String() = description;
  1503. if(effectRange != NO_LIMIT)
  1504. root["effectRange"].String() = vstd::findKey(bonusLimitEffect, effectRange);
  1505. if(duration != PERMANENT)
  1506. root["duration"] = durationToJson(duration);
  1507. if(turnsRemain)
  1508. root["turns"].Integer() = turnsRemain;
  1509. if(limiter)
  1510. root["limiters"] = limiter->toJsonNode();
  1511. if(updater)
  1512. root["updater"] = updater->toJsonNode();
  1513. if(propagator)
  1514. root["propagator"].String() = vstd::findKey(bonusPropagatorMap, propagator);
  1515. return root;
  1516. }
  1517. std::string Bonus::nameForBonus() const
  1518. {
  1519. switch(type)
  1520. {
  1521. case Bonus::PRIMARY_SKILL:
  1522. return PrimarySkill::names[subtype];
  1523. case Bonus::SPECIAL_SPELL_LEV:
  1524. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1525. case Bonus::SPELL:
  1526. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1527. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1528. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1529. return (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier;
  1530. case Bonus::SPECIAL_UPGRADE:
  1531. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo[0]);
  1532. case Bonus::GENERATE_RESOURCE:
  1533. return GameConstants::RESOURCE_NAMES[subtype];
  1534. case Bonus::STACKS_SPEED:
  1535. return "speed";
  1536. default:
  1537. return vstd::findKey(bonusNameMap, type);
  1538. }
  1539. }
  1540. BonusParams::BonusParams(std::string deprecatedTypeStr, std::string deprecatedSubtypeStr, int deprecatedSubtype):
  1541. isConverted(true)
  1542. {
  1543. if(deprecatedTypeStr == "SECONDARY_SKILL_PREMY" || deprecatedTypeStr == "SPECIAL_SECONDARY_SKILL")
  1544. {
  1545. if(deprecatedSubtype == SecondarySkill::PATHFINDING || deprecatedSubtypeStr == "skill.pathfinding")
  1546. type = Bonus::ROUGH_TERRAIN_DISCOUNT;
  1547. else if(deprecatedSubtype == SecondarySkill::DIPLOMACY || deprecatedSubtypeStr == "skill.diplomacy")
  1548. type = Bonus::WANDERING_CREATURES_JOIN_BONUS;
  1549. else if(deprecatedSubtype == SecondarySkill::WISDOM || deprecatedSubtypeStr == "skill.wisdom")
  1550. type = Bonus::MAX_LEARNABLE_SPELL_LEVEL;
  1551. else if(deprecatedSubtype == SecondarySkill::MYSTICISM || deprecatedSubtypeStr == "skill.mysticism")
  1552. type = Bonus::MANA_REGENERATION;
  1553. else if(deprecatedSubtype == SecondarySkill::NECROMANCY || deprecatedSubtypeStr == "skill.necromancy")
  1554. type = Bonus::UNDEAD_RAISE_PERCENTAGE;
  1555. else if(deprecatedSubtype == SecondarySkill::LEARNING || deprecatedSubtypeStr == "skill.learning")
  1556. type = Bonus::HERO_EXPERIENCE_GAIN_PERCENT;
  1557. else if(deprecatedSubtype == SecondarySkill::RESISTANCE || deprecatedSubtypeStr == "skill.resistance")
  1558. type = Bonus::MAGIC_RESISTANCE;
  1559. else if(deprecatedSubtype == SecondarySkill::EAGLE_EYE || deprecatedSubtypeStr == "skill.eagleEye")
  1560. type = Bonus::LEARN_BATTLE_SPELL_CHANCE;
  1561. else if(deprecatedSubtype == SecondarySkill::INTELLIGENCE || deprecatedSubtypeStr == "skill.intelligence")
  1562. {
  1563. type = Bonus::MANA_PER_KNOWLEDGE;
  1564. valueType = Bonus::PERCENT_TO_BASE;
  1565. valueTypeRelevant = true;
  1566. }
  1567. else if(deprecatedSubtype == SecondarySkill::SORCERY || deprecatedSubtypeStr == "skill.sorcery")
  1568. type = Bonus::SPELL_DAMAGE;
  1569. else if(deprecatedSubtype == SecondarySkill::SCHOLAR || deprecatedSubtypeStr == "skill.scholar")
  1570. type = Bonus::LEARN_MEETING_SPELL_LIMIT;
  1571. else if(deprecatedSubtype == SecondarySkill::ARCHERY|| deprecatedSubtypeStr == "skill.archery")
  1572. {
  1573. subtype = 1;
  1574. subtypeRelevant = true;
  1575. type = Bonus::PERCENTAGE_DAMAGE_BOOST;
  1576. }
  1577. else if(deprecatedSubtype == SecondarySkill::OFFENCE || deprecatedSubtypeStr == "skill.offence")
  1578. {
  1579. subtype = 0;
  1580. subtypeRelevant = true;
  1581. type = Bonus::PERCENTAGE_DAMAGE_BOOST;
  1582. }
  1583. else if(deprecatedSubtype == SecondarySkill::ARMORER || deprecatedSubtypeStr == "skill.armorer")
  1584. {
  1585. subtype = -1;
  1586. subtypeRelevant = true;
  1587. type = Bonus::GENERAL_DAMAGE_REDUCTION;
  1588. }
  1589. else if(deprecatedSubtype == SecondarySkill::NAVIGATION || deprecatedSubtypeStr == "skill.navigation")
  1590. {
  1591. subtype = 0;
  1592. subtypeRelevant = true;
  1593. valueType = Bonus::PERCENT_TO_BASE;
  1594. valueTypeRelevant = true;
  1595. type = Bonus::MOVEMENT;
  1596. }
  1597. else if(deprecatedSubtype == SecondarySkill::LOGISTICS || deprecatedSubtypeStr == "skill.logistics")
  1598. {
  1599. subtype = 0;
  1600. subtypeRelevant = true;
  1601. valueType = Bonus::PERCENT_TO_BASE;
  1602. valueTypeRelevant = true;
  1603. type = Bonus::MOVEMENT;
  1604. }
  1605. else if(deprecatedSubtype == SecondarySkill::ESTATES || deprecatedSubtypeStr == "skill.estates")
  1606. {
  1607. type = Bonus::GENERATE_RESOURCE;
  1608. subtype = Res::GOLD;
  1609. subtypeRelevant = true;
  1610. }
  1611. else if(deprecatedSubtype == SecondarySkill::AIR_MAGIC || deprecatedSubtypeStr == "skill.airMagic")
  1612. {
  1613. type = Bonus::MAGIC_SCHOOL_SKILL;
  1614. subtypeRelevant = true;
  1615. subtype = 4;
  1616. }
  1617. else if(deprecatedSubtype == SecondarySkill::WATER_MAGIC || deprecatedSubtypeStr == "skill.waterMagic")
  1618. {
  1619. type = Bonus::MAGIC_SCHOOL_SKILL;
  1620. subtypeRelevant = true;
  1621. subtype = 1;
  1622. }
  1623. else if(deprecatedSubtype == SecondarySkill::FIRE_MAGIC || deprecatedSubtypeStr == "skill.fireMagic")
  1624. {
  1625. type = Bonus::MAGIC_SCHOOL_SKILL;
  1626. subtypeRelevant = true;
  1627. subtype = 2;
  1628. }
  1629. else if(deprecatedSubtype == SecondarySkill::EARTH_MAGIC || deprecatedSubtypeStr == "skill.earthMagic")
  1630. {
  1631. type = Bonus::MAGIC_SCHOOL_SKILL;
  1632. subtypeRelevant = true;
  1633. subtype = 8;
  1634. }
  1635. else if (deprecatedSubtype == SecondarySkill::ARTILLERY || deprecatedSubtypeStr == "skill.artillery")
  1636. {
  1637. type = Bonus::BONUS_DAMAGE_CHANCE;
  1638. subtypeRelevant = true;
  1639. subtypeStr = "core:creature.ballista";
  1640. }
  1641. else if (deprecatedSubtype == SecondarySkill::FIRST_AID || deprecatedSubtypeStr == "skill.firstAid")
  1642. {
  1643. type = Bonus::SPECIFIC_SPELL_POWER;
  1644. subtypeRelevant = true;
  1645. subtypeStr = "core:spell.firstAid";
  1646. }
  1647. else if (deprecatedSubtype == SecondarySkill::BALLISTICS || deprecatedSubtypeStr == "skill.ballistics")
  1648. {
  1649. type = Bonus::CATAPULT_EXTRA_SHOTS;
  1650. subtypeRelevant = true;
  1651. subtypeStr = "core:spell.catapultShot";
  1652. }
  1653. else
  1654. isConverted = false;
  1655. }
  1656. else if (deprecatedTypeStr == "SECONDARY_SKILL_VAL2")
  1657. {
  1658. if(deprecatedSubtype == SecondarySkill::EAGLE_EYE || deprecatedSubtypeStr == "skill.eagleEye")
  1659. type = Bonus::LEARN_BATTLE_SPELL_LEVEL_LIMIT;
  1660. else if (deprecatedSubtype == SecondarySkill::ARTILLERY || deprecatedSubtypeStr == "skill.artillery")
  1661. {
  1662. type = Bonus::HERO_GRANTS_ATTACKS;
  1663. subtypeRelevant = true;
  1664. subtypeStr = "core:creature.ballista";
  1665. }
  1666. else
  1667. isConverted = false;
  1668. }
  1669. else if (deprecatedTypeStr == "SEA_MOVEMENT")
  1670. {
  1671. subtype = 0;
  1672. subtypeRelevant = true;
  1673. valueType = Bonus::ADDITIVE_VALUE;
  1674. valueTypeRelevant = true;
  1675. type = Bonus::MOVEMENT;
  1676. }
  1677. else if (deprecatedTypeStr == "LAND_MOVEMENT")
  1678. {
  1679. subtype = 1;
  1680. subtypeRelevant = true;
  1681. valueType = Bonus::ADDITIVE_VALUE;
  1682. valueTypeRelevant = true;
  1683. type = Bonus::MOVEMENT;
  1684. }
  1685. else if (deprecatedTypeStr == "MAXED_SPELL")
  1686. {
  1687. type = Bonus::SPELL;
  1688. subtypeStr = deprecatedSubtypeStr;
  1689. subtypeRelevant = true;
  1690. valueType = Bonus::INDEPENDENT_MAX;
  1691. valueTypeRelevant = true;
  1692. val = 3;
  1693. valRelevant = true;
  1694. }
  1695. else if (deprecatedTypeStr == "FULL_HP_REGENERATION")
  1696. {
  1697. type = Bonus::HP_REGENERATION;
  1698. val = 100000; //very high value to always chose stack health
  1699. valRelevant = true;
  1700. }
  1701. else if (deprecatedTypeStr == "KING1")
  1702. {
  1703. type = Bonus::KING;
  1704. val = 0;
  1705. valRelevant = true;
  1706. }
  1707. else if (deprecatedTypeStr == "KING2")
  1708. {
  1709. type = Bonus::KING;
  1710. val = 2;
  1711. valRelevant = true;
  1712. }
  1713. else if (deprecatedTypeStr == "KING3")
  1714. {
  1715. type = Bonus::KING;
  1716. val = 3;
  1717. valRelevant = true;
  1718. }
  1719. else if (deprecatedTypeStr == "SIGHT_RADIOUS")
  1720. type = Bonus::SIGHT_RADIUS;
  1721. else
  1722. isConverted = false;
  1723. }
  1724. const JsonNode & BonusParams::toJson()
  1725. {
  1726. assert(isConverted);
  1727. if(ret.isNull())
  1728. {
  1729. ret["type"].String() = vstd::findKey(bonusNameMap, type);
  1730. if(subtypeRelevant && !subtypeStr.empty())
  1731. ret["subtype"].String() = subtypeStr;
  1732. else if(subtypeRelevant)
  1733. ret["subtype"].Integer() = subtype;
  1734. if(valueTypeRelevant)
  1735. ret["valueType"].String() = vstd::findKey(bonusValueMap, valueType);
  1736. if(valRelevant)
  1737. ret["val"].Float() = val;
  1738. if(targetTypeRelevant)
  1739. ret["targetSourceType"].String() = vstd::findKey(bonusSourceMap, targetType);
  1740. jsonCreated = true;
  1741. }
  1742. return ret;
  1743. };
  1744. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype)
  1745. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  1746. {
  1747. turnsRemain = 0;
  1748. valType = ADDITIVE_VALUE;
  1749. effectRange = NO_LIMIT;
  1750. boost::algorithm::trim(description);
  1751. targetSourceType = OTHER;
  1752. }
  1753. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType)
  1754. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  1755. {
  1756. turnsRemain = 0;
  1757. effectRange = NO_LIMIT;
  1758. targetSourceType = OTHER;
  1759. }
  1760. Bonus::Bonus()
  1761. {
  1762. duration = PERMANENT;
  1763. turnsRemain = 0;
  1764. type = NONE;
  1765. subtype = -1;
  1766. valType = ADDITIVE_VALUE;
  1767. effectRange = NO_LIMIT;
  1768. val = 0;
  1769. source = OTHER;
  1770. sid = 0;
  1771. targetSourceType = OTHER;
  1772. }
  1773. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  1774. {
  1775. propagator = Propagator;
  1776. return this->shared_from_this();
  1777. }
  1778. namespace Selector
  1779. {
  1780. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type()
  1781. {
  1782. static CSelectFieldEqual<Bonus::BonusType> stype(&Bonus::type);
  1783. return stype;
  1784. }
  1785. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype()
  1786. {
  1787. static CSelectFieldEqual<TBonusSubtype> ssubtype(&Bonus::subtype);
  1788. return ssubtype;
  1789. }
  1790. DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info()
  1791. {
  1792. static CSelectFieldEqual<CAddInfo> sinfo(&Bonus::additionalInfo);
  1793. return sinfo;
  1794. }
  1795. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType()
  1796. {
  1797. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::source);
  1798. return ssourceType;
  1799. }
  1800. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & targetSourceType()
  1801. {
  1802. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::targetSourceType);
  1803. return ssourceType;
  1804. }
  1805. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange()
  1806. {
  1807. static CSelectFieldEqual<Bonus::LimitEffect> seffectRange(&Bonus::effectRange);
  1808. return seffectRange;
  1809. }
  1810. DLL_LINKAGE CWillLastTurns turns;
  1811. DLL_LINKAGE CWillLastDays days;
  1812. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1813. {
  1814. return type()(Type).And(subtype()(Subtype));
  1815. }
  1816. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, CAddInfo info)
  1817. {
  1818. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1819. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1820. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1821. }
  1822. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1823. {
  1824. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1825. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1826. }
  1827. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1828. {
  1829. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1830. }
  1831. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1832. {
  1833. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1834. }
  1835. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1836. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1837. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1838. {
  1839. Bonus dummy;
  1840. dummy.type = type;
  1841. return sel(&dummy);
  1842. }
  1843. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1844. {
  1845. Bonus dummy;
  1846. dummy.type = type;
  1847. dummy.subtype = subtype;
  1848. return sel(&dummy);
  1849. }
  1850. }
  1851. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1852. {
  1853. switch(node->getNodeType())
  1854. {
  1855. case CBonusSystemNode::CREATURE:
  1856. return (static_cast<const CCreature *>(node));
  1857. case CBonusSystemNode::STACK_BATTLE:
  1858. return (static_cast<const CStack*>(node))->type;
  1859. default:
  1860. const CStackInstance * csi = retrieveStackInstance(node);
  1861. if(csi)
  1862. return csi->type;
  1863. return nullptr;
  1864. }
  1865. }
  1866. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1867. {
  1868. for (ui32 i = 0; i < bonusList.size(); i++)
  1869. {
  1870. auto b = bonusList[i];
  1871. out << "Bonus " << i << "\n" << *b << std::endl;
  1872. }
  1873. return out;
  1874. }
  1875. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1876. {
  1877. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1878. if(i->second == bonus.type)
  1879. out << "\tType: " << i->first << " \t";
  1880. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1881. printField(val);
  1882. printField(subtype);
  1883. printField(duration);
  1884. printField(source);
  1885. printField(sid);
  1886. if(bonus.additionalInfo != CAddInfo::NONE)
  1887. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1888. printField(turnsRemain);
  1889. printField(valType);
  1890. if(!bonus.stacking.empty())
  1891. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1892. printField(effectRange);
  1893. #undef printField
  1894. if(bonus.limiter)
  1895. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1896. if(bonus.updater)
  1897. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1898. return out;
  1899. }
  1900. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1901. {
  1902. if (limiter)
  1903. {
  1904. //If we already have limiter list, retrieve it
  1905. auto limiterList = std::dynamic_pointer_cast<AllOfLimiter>(limiter);
  1906. if(!limiterList)
  1907. {
  1908. //Create a new limiter list with old limiter and the new one will be pushed later
  1909. limiterList = std::make_shared<AllOfLimiter>();
  1910. limiterList->add(limiter);
  1911. limiter = limiterList;
  1912. }
  1913. limiterList->add(Limiter);
  1914. }
  1915. else
  1916. {
  1917. limiter = Limiter;
  1918. }
  1919. return this->shared_from_this();
  1920. }
  1921. ILimiter::~ILimiter()
  1922. {
  1923. }
  1924. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1925. {
  1926. return false;
  1927. }
  1928. std::string ILimiter::toString() const
  1929. {
  1930. return typeid(*this).name();
  1931. }
  1932. JsonNode ILimiter::toJsonNode() const
  1933. {
  1934. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1935. root["type"].String() = toString();
  1936. return root;
  1937. }
  1938. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1939. {
  1940. const CCreature *c = retrieveCreature(&context.node);
  1941. if(!c)
  1942. return true;
  1943. return c->getId() != creature->getId() && (!includeUpgrades || !creature->isMyUpgrade(c));
  1944. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1945. }
  1946. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature & creature_, bool IncludeUpgrades)
  1947. : creature(&creature_), includeUpgrades(IncludeUpgrades)
  1948. {
  1949. }
  1950. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1951. {
  1952. creature = nullptr;
  1953. includeUpgrades = false;
  1954. }
  1955. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1956. {
  1957. creature = VLC->creh->objects[id];
  1958. }
  1959. std::string CCreatureTypeLimiter::toString() const
  1960. {
  1961. boost::format fmt("CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)");
  1962. fmt % creature->getJsonKey() % (includeUpgrades ? "true" : "false");
  1963. return fmt.str();
  1964. }
  1965. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1966. {
  1967. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1968. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1969. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->getJsonKey()));
  1970. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1971. return root;
  1972. }
  1973. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1974. : type(bonus), subtype(0), isSubtypeRelevant(false), isSourceRelevant(false), isSourceIDRelevant(false)
  1975. {
  1976. }
  1977. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1978. : type(bonus), subtype(_subtype), isSubtypeRelevant(true), isSourceRelevant(false), isSourceIDRelevant(false)
  1979. {
  1980. }
  1981. HasAnotherBonusLimiter::HasAnotherBonusLimiter(Bonus::BonusType bonus, Bonus::BonusSource src)
  1982. : type(bonus), source(src), isSubtypeRelevant(false), isSourceRelevant(true), isSourceIDRelevant(false)
  1983. {
  1984. }
  1985. HasAnotherBonusLimiter::HasAnotherBonusLimiter(Bonus::BonusType bonus, TBonusSubtype _subtype, Bonus::BonusSource src)
  1986. : type(bonus), subtype(_subtype), isSubtypeRelevant(true), source(src), isSourceRelevant(true), isSourceIDRelevant(false)
  1987. {
  1988. }
  1989. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1990. {
  1991. //TODO: proper selector config with parsing of JSON
  1992. auto mySelector = Selector::type()(type);
  1993. if(isSubtypeRelevant)
  1994. mySelector = mySelector.And(Selector::subtype()(subtype));
  1995. if(isSourceRelevant && isSourceIDRelevant)
  1996. mySelector = mySelector.And(Selector::source(source, sid));
  1997. else if (isSourceRelevant)
  1998. mySelector = mySelector.And(Selector::sourceTypeSel(source));
  1999. //if we have a bonus of required type accepted, limiter should accept also this bonus
  2000. if(context.alreadyAccepted.getFirst(mySelector))
  2001. return ACCEPT;
  2002. //if there are no matching bonuses pending, we can (and must) reject right away
  2003. if(!context.stillUndecided.getFirst(mySelector))
  2004. return DISCARD;
  2005. //do not accept for now but it may change if more bonuses gets included
  2006. return NOT_SURE;
  2007. }
  2008. std::string HasAnotherBonusLimiter::toString() const
  2009. {
  2010. std::string typeName = vstd::findKey(bonusNameMap, type);
  2011. if(isSubtypeRelevant)
  2012. {
  2013. boost::format fmt("HasAnotherBonusLimiter(type=%s, subtype=%d)");
  2014. fmt % typeName % subtype;
  2015. return fmt.str();
  2016. }
  2017. else
  2018. {
  2019. boost::format fmt("HasAnotherBonusLimiter(type=%s)");
  2020. fmt % typeName;
  2021. return fmt.str();
  2022. }
  2023. }
  2024. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  2025. {
  2026. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2027. std::string typeName = vstd::findKey(bonusNameMap, type);
  2028. auto sourceTypeName = vstd::findKey(bonusSourceMap, source);
  2029. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  2030. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  2031. if(isSubtypeRelevant)
  2032. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  2033. if(isSourceRelevant)
  2034. root["parameters"].Vector().push_back(JsonUtils::stringNode(sourceTypeName));
  2035. return root;
  2036. }
  2037. IPropagator::~IPropagator()
  2038. {
  2039. }
  2040. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  2041. {
  2042. return false;
  2043. }
  2044. CBonusSystemNode::ENodeTypes IPropagator::getPropagatorType() const
  2045. {
  2046. return CBonusSystemNode::ENodeTypes::NONE;
  2047. }
  2048. CPropagatorNodeType::CPropagatorNodeType()
  2049. :nodeType(CBonusSystemNode::ENodeTypes::UNKNOWN)
  2050. {
  2051. }
  2052. CPropagatorNodeType::CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType)
  2053. : nodeType(NodeType)
  2054. {
  2055. }
  2056. CBonusSystemNode::ENodeTypes CPropagatorNodeType::getPropagatorType() const
  2057. {
  2058. return nodeType;
  2059. }
  2060. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  2061. {
  2062. return nodeType == dest->getNodeType();
  2063. }
  2064. CreatureTerrainLimiter::CreatureTerrainLimiter()
  2065. : terrainType(ETerrainId::NATIVE_TERRAIN)
  2066. {
  2067. }
  2068. CreatureTerrainLimiter::CreatureTerrainLimiter(TerrainId terrain):
  2069. terrainType(terrain)
  2070. {
  2071. }
  2072. int CreatureTerrainLimiter::limit(const BonusLimitationContext &context) const
  2073. {
  2074. const CStack *stack = retrieveStackBattle(&context.node);
  2075. if(stack)
  2076. {
  2077. if (terrainType == ETerrainId::NATIVE_TERRAIN)//terrainType not specified = native
  2078. {
  2079. return !stack->isOnNativeTerrain();
  2080. }
  2081. else
  2082. {
  2083. return !stack->isOnTerrain(terrainType);
  2084. }
  2085. }
  2086. return true;
  2087. //TODO neutral creatues
  2088. }
  2089. std::string CreatureTerrainLimiter::toString() const
  2090. {
  2091. boost::format fmt("CreatureTerrainLimiter(terrainType=%s)");
  2092. auto terrainName = VLC->terrainTypeHandler->getById(terrainType)->getJsonKey();
  2093. fmt % (terrainType == ETerrainId::NATIVE_TERRAIN ? "native" : terrainName);
  2094. return fmt.str();
  2095. }
  2096. JsonNode CreatureTerrainLimiter::toJsonNode() const
  2097. {
  2098. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2099. root["type"].String() = "CREATURE_TERRAIN_LIMITER";
  2100. auto terrainName = VLC->terrainTypeHandler->getById(terrainType)->getJsonKey();
  2101. root["parameters"].Vector().push_back(JsonUtils::stringNode(terrainName));
  2102. return root;
  2103. }
  2104. CreatureFactionLimiter::CreatureFactionLimiter(TFaction creatureFaction)
  2105. : faction(creatureFaction)
  2106. {
  2107. }
  2108. CreatureFactionLimiter::CreatureFactionLimiter()
  2109. : faction((TFaction)-1)
  2110. {
  2111. }
  2112. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  2113. {
  2114. const CCreature *c = retrieveCreature(&context.node);
  2115. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  2116. }
  2117. std::string CreatureFactionLimiter::toString() const
  2118. {
  2119. boost::format fmt("CreatureFactionLimiter(faction=%s)");
  2120. fmt % VLC->factions()->getByIndex(faction)->getJsonKey();
  2121. return fmt.str();
  2122. }
  2123. JsonNode CreatureFactionLimiter::toJsonNode() const
  2124. {
  2125. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2126. root["type"].String() = "CREATURE_FACTION_LIMITER";
  2127. root["parameters"].Vector().push_back(JsonUtils::stringNode(VLC->factions()->getByIndex(faction)->getJsonKey()));
  2128. return root;
  2129. }
  2130. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  2131. : alignment(-1)
  2132. {
  2133. }
  2134. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  2135. : alignment(Alignment)
  2136. {
  2137. }
  2138. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  2139. {
  2140. const CCreature *c = retrieveCreature(&context.node);
  2141. if(!c)
  2142. return true;
  2143. switch(alignment)
  2144. {
  2145. case EAlignment::GOOD:
  2146. return !c->isGood(); //if not good -> return true (drop bonus)
  2147. case EAlignment::NEUTRAL:
  2148. return c->isEvil() || c->isGood();
  2149. case EAlignment::EVIL:
  2150. return !c->isEvil();
  2151. default:
  2152. logBonus->warn("Warning: illegal alignment in limiter!");
  2153. return true;
  2154. }
  2155. }
  2156. std::string CreatureAlignmentLimiter::toString() const
  2157. {
  2158. boost::format fmt("CreatureAlignmentLimiter(alignment=%s)");
  2159. fmt % EAlignment::names[alignment];
  2160. return fmt.str();
  2161. }
  2162. JsonNode CreatureAlignmentLimiter::toJsonNode() const
  2163. {
  2164. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2165. root["type"].String() = "CREATURE_ALIGNMENT_LIMITER";
  2166. root["parameters"].Vector().push_back(JsonUtils::stringNode(EAlignment::names[alignment]));
  2167. return root;
  2168. }
  2169. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  2170. :minRank(Min), maxRank(Max)
  2171. {
  2172. }
  2173. RankRangeLimiter::RankRangeLimiter()
  2174. {
  2175. minRank = maxRank = -1;
  2176. }
  2177. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  2178. {
  2179. const CStackInstance * csi = retrieveStackInstance(&context.node);
  2180. if(csi)
  2181. {
  2182. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  2183. return true;
  2184. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  2185. }
  2186. return true;
  2187. }
  2188. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  2189. {
  2190. const CStack * s = retrieveStackBattle(&context.node);
  2191. if(s)
  2192. return s->owner != owner;
  2193. const CStackInstance * csi = retrieveStackInstance(&context.node);
  2194. if(csi && csi->armyObj)
  2195. return csi->armyObj->tempOwner != owner;
  2196. return true;
  2197. }
  2198. StackOwnerLimiter::StackOwnerLimiter()
  2199. : owner(-1)
  2200. {
  2201. }
  2202. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  2203. : owner(Owner)
  2204. {
  2205. }
  2206. OppositeSideLimiter::OppositeSideLimiter()
  2207. : owner(PlayerColor::CANNOT_DETERMINE)
  2208. {
  2209. }
  2210. OppositeSideLimiter::OppositeSideLimiter(PlayerColor Owner)
  2211. : owner(Owner)
  2212. {
  2213. }
  2214. int OppositeSideLimiter::limit(const BonusLimitationContext & context) const
  2215. {
  2216. auto contextOwner = CBonusSystemNode::retrieveNodeOwner(& context.node);
  2217. auto decision = (owner == contextOwner || owner == PlayerColor::CANNOT_DETERMINE) ? ILimiter::DISCARD : ILimiter::ACCEPT;
  2218. return decision;
  2219. }
  2220. // Aggregate/Boolean Limiters
  2221. void AggregateLimiter::add(TLimiterPtr limiter)
  2222. {
  2223. if(limiter)
  2224. limiters.push_back(limiter);
  2225. }
  2226. JsonNode AggregateLimiter::toJsonNode() const
  2227. {
  2228. JsonNode result(JsonNode::JsonType::DATA_VECTOR);
  2229. result.Vector().push_back(JsonUtils::stringNode(getAggregator()));
  2230. for(auto l : limiters)
  2231. result.Vector().push_back(l->toJsonNode());
  2232. return result;
  2233. }
  2234. const std::string AllOfLimiter::aggregator = "allOf";
  2235. const std::string & AllOfLimiter::getAggregator() const
  2236. {
  2237. return aggregator;
  2238. }
  2239. int AllOfLimiter::limit(const BonusLimitationContext & context) const
  2240. {
  2241. bool wasntSure = false;
  2242. for(auto limiter : limiters)
  2243. {
  2244. auto result = limiter->limit(context);
  2245. if(result == ILimiter::DISCARD)
  2246. return result;
  2247. if(result == ILimiter::NOT_SURE)
  2248. wasntSure = true;
  2249. }
  2250. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  2251. }
  2252. const std::string AnyOfLimiter::aggregator = "anyOf";
  2253. const std::string & AnyOfLimiter::getAggregator() const
  2254. {
  2255. return aggregator;
  2256. }
  2257. int AnyOfLimiter::limit(const BonusLimitationContext & context) const
  2258. {
  2259. bool wasntSure = false;
  2260. for(auto limiter : limiters)
  2261. {
  2262. auto result = limiter->limit(context);
  2263. if(result == ILimiter::ACCEPT)
  2264. return result;
  2265. if(result == ILimiter::NOT_SURE)
  2266. wasntSure = true;
  2267. }
  2268. return wasntSure ? ILimiter::NOT_SURE : ILimiter::DISCARD;
  2269. }
  2270. const std::string NoneOfLimiter::aggregator = "noneOf";
  2271. const std::string & NoneOfLimiter::getAggregator() const
  2272. {
  2273. return aggregator;
  2274. }
  2275. int NoneOfLimiter::limit(const BonusLimitationContext & context) const
  2276. {
  2277. bool wasntSure = false;
  2278. for(auto limiter : limiters)
  2279. {
  2280. auto result = limiter->limit(context);
  2281. if(result == ILimiter::ACCEPT)
  2282. return ILimiter::DISCARD;
  2283. if(result == ILimiter::NOT_SURE)
  2284. wasntSure = true;
  2285. }
  2286. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  2287. }
  2288. // Updaters
  2289. std::shared_ptr<Bonus> Bonus::addUpdater(TUpdaterPtr Updater)
  2290. {
  2291. updater = Updater;
  2292. return this->shared_from_this();
  2293. }
  2294. // Update ONLY_ENEMY_ARMY bonuses from old saves to make them workable.
  2295. // Also, we should foreseen possible errors in bonus configuration and fix them.
  2296. void Bonus::updateOppositeBonuses()
  2297. {
  2298. if(effectRange != Bonus::ONLY_ENEMY_ARMY)
  2299. return;
  2300. if(propagator)
  2301. {
  2302. if(propagator->getPropagatorType() != CBonusSystemNode::BATTLE)
  2303. {
  2304. logMod->error("Wrong Propagator will be ignored: The 'ONLY_ENEMY_ARMY' effectRange is only compatible with the 'BATTLE_WIDE' propagator.");
  2305. propagator.reset(new CPropagatorNodeType(CBonusSystemNode::BATTLE));
  2306. }
  2307. }
  2308. else
  2309. {
  2310. propagator = std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE);
  2311. }
  2312. if(limiter)
  2313. {
  2314. if(!dynamic_cast<OppositeSideLimiter*>(limiter.get()))
  2315. {
  2316. logMod->error("Wrong Limiter will be ignored: The 'ONLY_ENEMY_ARMY' effectRange is only compatible with the 'OPPOSITE_SIDE' limiter.");
  2317. limiter.reset(new OppositeSideLimiter());
  2318. }
  2319. }
  2320. else
  2321. {
  2322. limiter = std::make_shared<OppositeSideLimiter>();
  2323. }
  2324. propagationUpdater = std::make_shared<OwnerUpdater>();
  2325. }
  2326. IUpdater::~IUpdater()
  2327. {
  2328. }
  2329. std::shared_ptr<Bonus> IUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2330. {
  2331. return b;
  2332. }
  2333. std::string IUpdater::toString() const
  2334. {
  2335. return typeid(*this).name();
  2336. }
  2337. JsonNode IUpdater::toJsonNode() const
  2338. {
  2339. return JsonNode(JsonNode::JsonType::DATA_NULL);
  2340. }
  2341. GrowsWithLevelUpdater::GrowsWithLevelUpdater() : valPer20(0), stepSize(1)
  2342. {
  2343. }
  2344. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  2345. {
  2346. }
  2347. std::shared_ptr<Bonus> GrowsWithLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2348. {
  2349. if(context.getNodeType() == CBonusSystemNode::HERO)
  2350. {
  2351. int level = static_cast<const CGHeroInstance &>(context).level;
  2352. int steps = stepSize ? level / stepSize : level;
  2353. //rounding follows format for HMM3 creature specialty bonus
  2354. int newVal = (valPer20 * steps + 19) / 20;
  2355. //return copy of bonus with updated val
  2356. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2357. newBonus->val = newVal;
  2358. return newBonus;
  2359. }
  2360. return b;
  2361. }
  2362. std::string GrowsWithLevelUpdater::toString() const
  2363. {
  2364. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  2365. }
  2366. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  2367. {
  2368. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2369. root["type"].String() = "GROWS_WITH_LEVEL";
  2370. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  2371. if(stepSize > 1)
  2372. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  2373. return root;
  2374. }
  2375. TimesHeroLevelUpdater::TimesHeroLevelUpdater()
  2376. {
  2377. }
  2378. std::shared_ptr<Bonus> TimesHeroLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2379. {
  2380. if(context.getNodeType() == CBonusSystemNode::HERO)
  2381. {
  2382. int level = static_cast<const CGHeroInstance &>(context).level;
  2383. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2384. newBonus->val *= level;
  2385. return newBonus;
  2386. }
  2387. return b;
  2388. }
  2389. std::string TimesHeroLevelUpdater::toString() const
  2390. {
  2391. return "TimesHeroLevelUpdater";
  2392. }
  2393. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  2394. {
  2395. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  2396. }
  2397. std::shared_ptr<Bonus> ArmyMovementUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2398. {
  2399. if(b->type == Bonus::MOVEMENT && context.getNodeType() == CBonusSystemNode::HERO)
  2400. {
  2401. auto newBonus = std::make_shared<Bonus>(*b);
  2402. newBonus->source = Bonus::ARMY;
  2403. newBonus->val = static_cast<const CGHeroInstance &>(context).getArmyMovementBonus();
  2404. return newBonus;
  2405. }
  2406. if(b->type != Bonus::MOVEMENT)
  2407. logGlobal->error("ArmyMovementUpdater should only be used for MOVEMENT bonus!");
  2408. return b;
  2409. }
  2410. std::string ArmyMovementUpdater::toString() const
  2411. {
  2412. return "ArmyMovementUpdater";
  2413. }
  2414. JsonNode ArmyMovementUpdater::toJsonNode() const
  2415. {
  2416. return JsonUtils::stringNode("ARMY_MOVEMENT");
  2417. }
  2418. TimesStackLevelUpdater::TimesStackLevelUpdater()
  2419. {
  2420. }
  2421. std::shared_ptr<Bonus> TimesStackLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2422. {
  2423. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  2424. {
  2425. int level = static_cast<const CStackInstance &>(context).getLevel();
  2426. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2427. newBonus->val *= level;
  2428. return newBonus;
  2429. }
  2430. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  2431. {
  2432. const CStack & stack = static_cast<const CStack &>(context);
  2433. //only update if stack doesn't have an instance (summons, war machines)
  2434. //otherwise we'd end up multiplying twice
  2435. if(stack.base == nullptr)
  2436. {
  2437. int level = stack.type->level;
  2438. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2439. newBonus->val *= level;
  2440. return newBonus;
  2441. }
  2442. }
  2443. return b;
  2444. }
  2445. std::string TimesStackLevelUpdater::toString() const
  2446. {
  2447. return "TimesStackLevelUpdater";
  2448. }
  2449. JsonNode TimesStackLevelUpdater::toJsonNode() const
  2450. {
  2451. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  2452. }
  2453. OwnerUpdater::OwnerUpdater()
  2454. {
  2455. }
  2456. std::string OwnerUpdater::toString() const
  2457. {
  2458. return "OwnerUpdater";
  2459. }
  2460. JsonNode OwnerUpdater::toJsonNode() const
  2461. {
  2462. return JsonUtils::stringNode("BONUS_OWNER_UPDATER");
  2463. }
  2464. std::shared_ptr<Bonus> OwnerUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2465. {
  2466. auto owner = CBonusSystemNode::retrieveNodeOwner(&context);
  2467. if(owner == PlayerColor::UNFLAGGABLE)
  2468. owner = PlayerColor::NEUTRAL;
  2469. std::shared_ptr<Bonus> updated = std::make_shared<Bonus>(
  2470. (Bonus::BonusDuration)b->duration, b->type, b->source, b->val, b->sid, b->subtype, b->valType);
  2471. updated->limiter = std::make_shared<OppositeSideLimiter>(owner);
  2472. return updated;
  2473. }
  2474. VCMI_LIB_NAMESPACE_END