HeroBonus.cpp 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887
  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. CSelector BonusParams::toSelector()
  1745. {
  1746. assert(isConverted);
  1747. if(subtypeRelevant && !subtypeStr.empty())
  1748. JsonUtils::resolveIdentifier(subtype, toJson(), "subtype");
  1749. auto ret = Selector::type()(type);
  1750. if(subtypeRelevant)
  1751. ret = ret.And(Selector::subtype()(subtype));
  1752. if(valueTypeRelevant)
  1753. ret = ret.And(Selector::valueType(valueType));
  1754. if(targetTypeRelevant)
  1755. ret = ret.And(Selector::targetSourceType()(targetType));
  1756. return ret;
  1757. }
  1758. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype)
  1759. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  1760. {
  1761. turnsRemain = 0;
  1762. valType = ADDITIVE_VALUE;
  1763. effectRange = NO_LIMIT;
  1764. boost::algorithm::trim(description);
  1765. targetSourceType = OTHER;
  1766. }
  1767. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType)
  1768. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  1769. {
  1770. turnsRemain = 0;
  1771. effectRange = NO_LIMIT;
  1772. targetSourceType = OTHER;
  1773. }
  1774. Bonus::Bonus()
  1775. {
  1776. duration = PERMANENT;
  1777. turnsRemain = 0;
  1778. type = NONE;
  1779. subtype = -1;
  1780. valType = ADDITIVE_VALUE;
  1781. effectRange = NO_LIMIT;
  1782. val = 0;
  1783. source = OTHER;
  1784. sid = 0;
  1785. targetSourceType = OTHER;
  1786. }
  1787. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  1788. {
  1789. propagator = Propagator;
  1790. return this->shared_from_this();
  1791. }
  1792. namespace Selector
  1793. {
  1794. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type()
  1795. {
  1796. static CSelectFieldEqual<Bonus::BonusType> stype(&Bonus::type);
  1797. return stype;
  1798. }
  1799. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype()
  1800. {
  1801. static CSelectFieldEqual<TBonusSubtype> ssubtype(&Bonus::subtype);
  1802. return ssubtype;
  1803. }
  1804. DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info()
  1805. {
  1806. static CSelectFieldEqual<CAddInfo> sinfo(&Bonus::additionalInfo);
  1807. return sinfo;
  1808. }
  1809. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType()
  1810. {
  1811. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::source);
  1812. return ssourceType;
  1813. }
  1814. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & targetSourceType()
  1815. {
  1816. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::targetSourceType);
  1817. return ssourceType;
  1818. }
  1819. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange()
  1820. {
  1821. static CSelectFieldEqual<Bonus::LimitEffect> seffectRange(&Bonus::effectRange);
  1822. return seffectRange;
  1823. }
  1824. DLL_LINKAGE CWillLastTurns turns;
  1825. DLL_LINKAGE CWillLastDays days;
  1826. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1827. {
  1828. return type()(Type).And(subtype()(Subtype));
  1829. }
  1830. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, CAddInfo info)
  1831. {
  1832. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1833. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1834. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1835. }
  1836. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1837. {
  1838. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1839. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1840. }
  1841. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1842. {
  1843. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1844. }
  1845. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1846. {
  1847. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1848. }
  1849. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1850. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1851. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1852. {
  1853. Bonus dummy;
  1854. dummy.type = type;
  1855. return sel(&dummy);
  1856. }
  1857. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1858. {
  1859. Bonus dummy;
  1860. dummy.type = type;
  1861. dummy.subtype = subtype;
  1862. return sel(&dummy);
  1863. }
  1864. }
  1865. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1866. {
  1867. switch(node->getNodeType())
  1868. {
  1869. case CBonusSystemNode::CREATURE:
  1870. return (static_cast<const CCreature *>(node));
  1871. case CBonusSystemNode::STACK_BATTLE:
  1872. return (static_cast<const CStack*>(node))->type;
  1873. default:
  1874. const CStackInstance * csi = retrieveStackInstance(node);
  1875. if(csi)
  1876. return csi->type;
  1877. return nullptr;
  1878. }
  1879. }
  1880. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1881. {
  1882. for (ui32 i = 0; i < bonusList.size(); i++)
  1883. {
  1884. auto b = bonusList[i];
  1885. out << "Bonus " << i << "\n" << *b << std::endl;
  1886. }
  1887. return out;
  1888. }
  1889. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1890. {
  1891. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1892. if(i->second == bonus.type)
  1893. out << "\tType: " << i->first << " \t";
  1894. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1895. printField(val);
  1896. printField(subtype);
  1897. printField(duration);
  1898. printField(source);
  1899. printField(sid);
  1900. if(bonus.additionalInfo != CAddInfo::NONE)
  1901. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1902. printField(turnsRemain);
  1903. printField(valType);
  1904. if(!bonus.stacking.empty())
  1905. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1906. printField(effectRange);
  1907. #undef printField
  1908. if(bonus.limiter)
  1909. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1910. if(bonus.updater)
  1911. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1912. return out;
  1913. }
  1914. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1915. {
  1916. if (limiter)
  1917. {
  1918. //If we already have limiter list, retrieve it
  1919. auto limiterList = std::dynamic_pointer_cast<AllOfLimiter>(limiter);
  1920. if(!limiterList)
  1921. {
  1922. //Create a new limiter list with old limiter and the new one will be pushed later
  1923. limiterList = std::make_shared<AllOfLimiter>();
  1924. limiterList->add(limiter);
  1925. limiter = limiterList;
  1926. }
  1927. limiterList->add(Limiter);
  1928. }
  1929. else
  1930. {
  1931. limiter = Limiter;
  1932. }
  1933. return this->shared_from_this();
  1934. }
  1935. ILimiter::~ILimiter()
  1936. {
  1937. }
  1938. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1939. {
  1940. return false;
  1941. }
  1942. std::string ILimiter::toString() const
  1943. {
  1944. return typeid(*this).name();
  1945. }
  1946. JsonNode ILimiter::toJsonNode() const
  1947. {
  1948. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1949. root["type"].String() = toString();
  1950. return root;
  1951. }
  1952. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1953. {
  1954. const CCreature *c = retrieveCreature(&context.node);
  1955. if(!c)
  1956. return true;
  1957. return c->getId() != creature->getId() && (!includeUpgrades || !creature->isMyUpgrade(c));
  1958. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1959. }
  1960. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature & creature_, bool IncludeUpgrades)
  1961. : creature(&creature_), includeUpgrades(IncludeUpgrades)
  1962. {
  1963. }
  1964. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1965. {
  1966. creature = nullptr;
  1967. includeUpgrades = false;
  1968. }
  1969. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1970. {
  1971. creature = VLC->creh->objects[id];
  1972. }
  1973. std::string CCreatureTypeLimiter::toString() const
  1974. {
  1975. boost::format fmt("CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)");
  1976. fmt % creature->getJsonKey() % (includeUpgrades ? "true" : "false");
  1977. return fmt.str();
  1978. }
  1979. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1980. {
  1981. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1982. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1983. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->getJsonKey()));
  1984. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1985. return root;
  1986. }
  1987. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1988. : type(bonus), subtype(0), isSubtypeRelevant(false), isSourceRelevant(false), isSourceIDRelevant(false)
  1989. {
  1990. }
  1991. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1992. : type(bonus), subtype(_subtype), isSubtypeRelevant(true), isSourceRelevant(false), isSourceIDRelevant(false)
  1993. {
  1994. }
  1995. HasAnotherBonusLimiter::HasAnotherBonusLimiter(Bonus::BonusType bonus, Bonus::BonusSource src)
  1996. : type(bonus), source(src), isSubtypeRelevant(false), isSourceRelevant(true), isSourceIDRelevant(false)
  1997. {
  1998. }
  1999. HasAnotherBonusLimiter::HasAnotherBonusLimiter(Bonus::BonusType bonus, TBonusSubtype _subtype, Bonus::BonusSource src)
  2000. : type(bonus), subtype(_subtype), isSubtypeRelevant(true), source(src), isSourceRelevant(true), isSourceIDRelevant(false)
  2001. {
  2002. }
  2003. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  2004. {
  2005. //TODO: proper selector config with parsing of JSON
  2006. auto mySelector = Selector::type()(type);
  2007. if(isSubtypeRelevant)
  2008. mySelector = mySelector.And(Selector::subtype()(subtype));
  2009. if(isSourceRelevant && isSourceIDRelevant)
  2010. mySelector = mySelector.And(Selector::source(source, sid));
  2011. else if (isSourceRelevant)
  2012. mySelector = mySelector.And(Selector::sourceTypeSel(source));
  2013. //if we have a bonus of required type accepted, limiter should accept also this bonus
  2014. if(context.alreadyAccepted.getFirst(mySelector))
  2015. return ACCEPT;
  2016. //if there are no matching bonuses pending, we can (and must) reject right away
  2017. if(!context.stillUndecided.getFirst(mySelector))
  2018. return DISCARD;
  2019. //do not accept for now but it may change if more bonuses gets included
  2020. return NOT_SURE;
  2021. }
  2022. std::string HasAnotherBonusLimiter::toString() const
  2023. {
  2024. std::string typeName = vstd::findKey(bonusNameMap, type);
  2025. if(isSubtypeRelevant)
  2026. {
  2027. boost::format fmt("HasAnotherBonusLimiter(type=%s, subtype=%d)");
  2028. fmt % typeName % subtype;
  2029. return fmt.str();
  2030. }
  2031. else
  2032. {
  2033. boost::format fmt("HasAnotherBonusLimiter(type=%s)");
  2034. fmt % typeName;
  2035. return fmt.str();
  2036. }
  2037. }
  2038. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  2039. {
  2040. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2041. std::string typeName = vstd::findKey(bonusNameMap, type);
  2042. auto sourceTypeName = vstd::findKey(bonusSourceMap, source);
  2043. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  2044. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  2045. if(isSubtypeRelevant)
  2046. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  2047. if(isSourceRelevant)
  2048. root["parameters"].Vector().push_back(JsonUtils::stringNode(sourceTypeName));
  2049. return root;
  2050. }
  2051. IPropagator::~IPropagator()
  2052. {
  2053. }
  2054. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  2055. {
  2056. return false;
  2057. }
  2058. CBonusSystemNode::ENodeTypes IPropagator::getPropagatorType() const
  2059. {
  2060. return CBonusSystemNode::ENodeTypes::NONE;
  2061. }
  2062. CPropagatorNodeType::CPropagatorNodeType()
  2063. :nodeType(CBonusSystemNode::ENodeTypes::UNKNOWN)
  2064. {
  2065. }
  2066. CPropagatorNodeType::CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType)
  2067. : nodeType(NodeType)
  2068. {
  2069. }
  2070. CBonusSystemNode::ENodeTypes CPropagatorNodeType::getPropagatorType() const
  2071. {
  2072. return nodeType;
  2073. }
  2074. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  2075. {
  2076. return nodeType == dest->getNodeType();
  2077. }
  2078. CreatureTerrainLimiter::CreatureTerrainLimiter()
  2079. : terrainType(ETerrainId::NATIVE_TERRAIN)
  2080. {
  2081. }
  2082. CreatureTerrainLimiter::CreatureTerrainLimiter(TerrainId terrain):
  2083. terrainType(terrain)
  2084. {
  2085. }
  2086. int CreatureTerrainLimiter::limit(const BonusLimitationContext &context) const
  2087. {
  2088. const CStack *stack = retrieveStackBattle(&context.node);
  2089. if(stack)
  2090. {
  2091. if (terrainType == ETerrainId::NATIVE_TERRAIN)//terrainType not specified = native
  2092. {
  2093. return !stack->isOnNativeTerrain();
  2094. }
  2095. else
  2096. {
  2097. return !stack->isOnTerrain(terrainType);
  2098. }
  2099. }
  2100. return true;
  2101. //TODO neutral creatues
  2102. }
  2103. std::string CreatureTerrainLimiter::toString() const
  2104. {
  2105. boost::format fmt("CreatureTerrainLimiter(terrainType=%s)");
  2106. auto terrainName = VLC->terrainTypeHandler->getById(terrainType)->getJsonKey();
  2107. fmt % (terrainType == ETerrainId::NATIVE_TERRAIN ? "native" : terrainName);
  2108. return fmt.str();
  2109. }
  2110. JsonNode CreatureTerrainLimiter::toJsonNode() const
  2111. {
  2112. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2113. root["type"].String() = "CREATURE_TERRAIN_LIMITER";
  2114. auto terrainName = VLC->terrainTypeHandler->getById(terrainType)->getJsonKey();
  2115. root["parameters"].Vector().push_back(JsonUtils::stringNode(terrainName));
  2116. return root;
  2117. }
  2118. CreatureFactionLimiter::CreatureFactionLimiter(TFaction creatureFaction)
  2119. : faction(creatureFaction)
  2120. {
  2121. }
  2122. CreatureFactionLimiter::CreatureFactionLimiter()
  2123. : faction((TFaction)-1)
  2124. {
  2125. }
  2126. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  2127. {
  2128. const CCreature *c = retrieveCreature(&context.node);
  2129. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  2130. }
  2131. std::string CreatureFactionLimiter::toString() const
  2132. {
  2133. boost::format fmt("CreatureFactionLimiter(faction=%s)");
  2134. fmt % VLC->factions()->getByIndex(faction)->getJsonKey();
  2135. return fmt.str();
  2136. }
  2137. JsonNode CreatureFactionLimiter::toJsonNode() const
  2138. {
  2139. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2140. root["type"].String() = "CREATURE_FACTION_LIMITER";
  2141. root["parameters"].Vector().push_back(JsonUtils::stringNode(VLC->factions()->getByIndex(faction)->getJsonKey()));
  2142. return root;
  2143. }
  2144. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  2145. : alignment(-1)
  2146. {
  2147. }
  2148. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  2149. : alignment(Alignment)
  2150. {
  2151. }
  2152. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  2153. {
  2154. const CCreature *c = retrieveCreature(&context.node);
  2155. if(!c)
  2156. return true;
  2157. switch(alignment)
  2158. {
  2159. case EAlignment::GOOD:
  2160. return !c->isGood(); //if not good -> return true (drop bonus)
  2161. case EAlignment::NEUTRAL:
  2162. return c->isEvil() || c->isGood();
  2163. case EAlignment::EVIL:
  2164. return !c->isEvil();
  2165. default:
  2166. logBonus->warn("Warning: illegal alignment in limiter!");
  2167. return true;
  2168. }
  2169. }
  2170. std::string CreatureAlignmentLimiter::toString() const
  2171. {
  2172. boost::format fmt("CreatureAlignmentLimiter(alignment=%s)");
  2173. fmt % EAlignment::names[alignment];
  2174. return fmt.str();
  2175. }
  2176. JsonNode CreatureAlignmentLimiter::toJsonNode() const
  2177. {
  2178. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2179. root["type"].String() = "CREATURE_ALIGNMENT_LIMITER";
  2180. root["parameters"].Vector().push_back(JsonUtils::stringNode(EAlignment::names[alignment]));
  2181. return root;
  2182. }
  2183. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  2184. :minRank(Min), maxRank(Max)
  2185. {
  2186. }
  2187. RankRangeLimiter::RankRangeLimiter()
  2188. {
  2189. minRank = maxRank = -1;
  2190. }
  2191. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  2192. {
  2193. const CStackInstance * csi = retrieveStackInstance(&context.node);
  2194. if(csi)
  2195. {
  2196. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  2197. return true;
  2198. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  2199. }
  2200. return true;
  2201. }
  2202. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  2203. {
  2204. const CStack * s = retrieveStackBattle(&context.node);
  2205. if(s)
  2206. return s->owner != owner;
  2207. const CStackInstance * csi = retrieveStackInstance(&context.node);
  2208. if(csi && csi->armyObj)
  2209. return csi->armyObj->tempOwner != owner;
  2210. return true;
  2211. }
  2212. StackOwnerLimiter::StackOwnerLimiter()
  2213. : owner(-1)
  2214. {
  2215. }
  2216. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  2217. : owner(Owner)
  2218. {
  2219. }
  2220. OppositeSideLimiter::OppositeSideLimiter()
  2221. : owner(PlayerColor::CANNOT_DETERMINE)
  2222. {
  2223. }
  2224. OppositeSideLimiter::OppositeSideLimiter(PlayerColor Owner)
  2225. : owner(Owner)
  2226. {
  2227. }
  2228. int OppositeSideLimiter::limit(const BonusLimitationContext & context) const
  2229. {
  2230. auto contextOwner = CBonusSystemNode::retrieveNodeOwner(& context.node);
  2231. auto decision = (owner == contextOwner || owner == PlayerColor::CANNOT_DETERMINE) ? ILimiter::DISCARD : ILimiter::ACCEPT;
  2232. return decision;
  2233. }
  2234. // Aggregate/Boolean Limiters
  2235. void AggregateLimiter::add(TLimiterPtr limiter)
  2236. {
  2237. if(limiter)
  2238. limiters.push_back(limiter);
  2239. }
  2240. JsonNode AggregateLimiter::toJsonNode() const
  2241. {
  2242. JsonNode result(JsonNode::JsonType::DATA_VECTOR);
  2243. result.Vector().push_back(JsonUtils::stringNode(getAggregator()));
  2244. for(auto l : limiters)
  2245. result.Vector().push_back(l->toJsonNode());
  2246. return result;
  2247. }
  2248. const std::string AllOfLimiter::aggregator = "allOf";
  2249. const std::string & AllOfLimiter::getAggregator() const
  2250. {
  2251. return aggregator;
  2252. }
  2253. int AllOfLimiter::limit(const BonusLimitationContext & context) const
  2254. {
  2255. bool wasntSure = false;
  2256. for(auto limiter : limiters)
  2257. {
  2258. auto result = limiter->limit(context);
  2259. if(result == ILimiter::DISCARD)
  2260. return result;
  2261. if(result == ILimiter::NOT_SURE)
  2262. wasntSure = true;
  2263. }
  2264. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  2265. }
  2266. const std::string AnyOfLimiter::aggregator = "anyOf";
  2267. const std::string & AnyOfLimiter::getAggregator() const
  2268. {
  2269. return aggregator;
  2270. }
  2271. int AnyOfLimiter::limit(const BonusLimitationContext & context) const
  2272. {
  2273. bool wasntSure = false;
  2274. for(auto limiter : limiters)
  2275. {
  2276. auto result = limiter->limit(context);
  2277. if(result == ILimiter::ACCEPT)
  2278. return result;
  2279. if(result == ILimiter::NOT_SURE)
  2280. wasntSure = true;
  2281. }
  2282. return wasntSure ? ILimiter::NOT_SURE : ILimiter::DISCARD;
  2283. }
  2284. const std::string NoneOfLimiter::aggregator = "noneOf";
  2285. const std::string & NoneOfLimiter::getAggregator() const
  2286. {
  2287. return aggregator;
  2288. }
  2289. int NoneOfLimiter::limit(const BonusLimitationContext & context) const
  2290. {
  2291. bool wasntSure = false;
  2292. for(auto limiter : limiters)
  2293. {
  2294. auto result = limiter->limit(context);
  2295. if(result == ILimiter::ACCEPT)
  2296. return ILimiter::DISCARD;
  2297. if(result == ILimiter::NOT_SURE)
  2298. wasntSure = true;
  2299. }
  2300. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  2301. }
  2302. // Updaters
  2303. std::shared_ptr<Bonus> Bonus::addUpdater(TUpdaterPtr Updater)
  2304. {
  2305. updater = Updater;
  2306. return this->shared_from_this();
  2307. }
  2308. // Update ONLY_ENEMY_ARMY bonuses from old saves to make them workable.
  2309. // Also, we should foreseen possible errors in bonus configuration and fix them.
  2310. void Bonus::updateOppositeBonuses()
  2311. {
  2312. if(effectRange != Bonus::ONLY_ENEMY_ARMY)
  2313. return;
  2314. if(propagator)
  2315. {
  2316. if(propagator->getPropagatorType() != CBonusSystemNode::BATTLE)
  2317. {
  2318. logMod->error("Wrong Propagator will be ignored: The 'ONLY_ENEMY_ARMY' effectRange is only compatible with the 'BATTLE_WIDE' propagator.");
  2319. propagator.reset(new CPropagatorNodeType(CBonusSystemNode::BATTLE));
  2320. }
  2321. }
  2322. else
  2323. {
  2324. propagator = std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE);
  2325. }
  2326. if(limiter)
  2327. {
  2328. if(!dynamic_cast<OppositeSideLimiter*>(limiter.get()))
  2329. {
  2330. logMod->error("Wrong Limiter will be ignored: The 'ONLY_ENEMY_ARMY' effectRange is only compatible with the 'OPPOSITE_SIDE' limiter.");
  2331. limiter.reset(new OppositeSideLimiter());
  2332. }
  2333. }
  2334. else
  2335. {
  2336. limiter = std::make_shared<OppositeSideLimiter>();
  2337. }
  2338. propagationUpdater = std::make_shared<OwnerUpdater>();
  2339. }
  2340. IUpdater::~IUpdater()
  2341. {
  2342. }
  2343. std::shared_ptr<Bonus> IUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2344. {
  2345. return b;
  2346. }
  2347. std::string IUpdater::toString() const
  2348. {
  2349. return typeid(*this).name();
  2350. }
  2351. JsonNode IUpdater::toJsonNode() const
  2352. {
  2353. return JsonNode(JsonNode::JsonType::DATA_NULL);
  2354. }
  2355. GrowsWithLevelUpdater::GrowsWithLevelUpdater() : valPer20(0), stepSize(1)
  2356. {
  2357. }
  2358. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  2359. {
  2360. }
  2361. std::shared_ptr<Bonus> GrowsWithLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2362. {
  2363. if(context.getNodeType() == CBonusSystemNode::HERO)
  2364. {
  2365. int level = static_cast<const CGHeroInstance &>(context).level;
  2366. int steps = stepSize ? level / stepSize : level;
  2367. //rounding follows format for HMM3 creature specialty bonus
  2368. int newVal = (valPer20 * steps + 19) / 20;
  2369. //return copy of bonus with updated val
  2370. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2371. newBonus->val = newVal;
  2372. return newBonus;
  2373. }
  2374. return b;
  2375. }
  2376. std::string GrowsWithLevelUpdater::toString() const
  2377. {
  2378. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  2379. }
  2380. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  2381. {
  2382. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2383. root["type"].String() = "GROWS_WITH_LEVEL";
  2384. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  2385. if(stepSize > 1)
  2386. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  2387. return root;
  2388. }
  2389. TimesHeroLevelUpdater::TimesHeroLevelUpdater()
  2390. {
  2391. }
  2392. std::shared_ptr<Bonus> TimesHeroLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2393. {
  2394. if(context.getNodeType() == CBonusSystemNode::HERO)
  2395. {
  2396. int level = static_cast<const CGHeroInstance &>(context).level;
  2397. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2398. newBonus->val *= level;
  2399. return newBonus;
  2400. }
  2401. return b;
  2402. }
  2403. std::string TimesHeroLevelUpdater::toString() const
  2404. {
  2405. return "TimesHeroLevelUpdater";
  2406. }
  2407. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  2408. {
  2409. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  2410. }
  2411. std::shared_ptr<Bonus> ArmyMovementUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2412. {
  2413. if(b->type == Bonus::MOVEMENT && context.getNodeType() == CBonusSystemNode::HERO)
  2414. {
  2415. auto newBonus = std::make_shared<Bonus>(*b);
  2416. newBonus->source = Bonus::ARMY;
  2417. newBonus->val = static_cast<const CGHeroInstance &>(context).getArmyMovementBonus();
  2418. return newBonus;
  2419. }
  2420. if(b->type != Bonus::MOVEMENT)
  2421. logGlobal->error("ArmyMovementUpdater should only be used for MOVEMENT bonus!");
  2422. return b;
  2423. }
  2424. std::string ArmyMovementUpdater::toString() const
  2425. {
  2426. return "ArmyMovementUpdater";
  2427. }
  2428. JsonNode ArmyMovementUpdater::toJsonNode() const
  2429. {
  2430. return JsonUtils::stringNode("ARMY_MOVEMENT");
  2431. }
  2432. TimesStackLevelUpdater::TimesStackLevelUpdater()
  2433. {
  2434. }
  2435. std::shared_ptr<Bonus> TimesStackLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2436. {
  2437. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  2438. {
  2439. int level = static_cast<const CStackInstance &>(context).getLevel();
  2440. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2441. newBonus->val *= level;
  2442. return newBonus;
  2443. }
  2444. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  2445. {
  2446. const CStack & stack = static_cast<const CStack &>(context);
  2447. //only update if stack doesn't have an instance (summons, war machines)
  2448. //otherwise we'd end up multiplying twice
  2449. if(stack.base == nullptr)
  2450. {
  2451. int level = stack.type->level;
  2452. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2453. newBonus->val *= level;
  2454. return newBonus;
  2455. }
  2456. }
  2457. return b;
  2458. }
  2459. std::string TimesStackLevelUpdater::toString() const
  2460. {
  2461. return "TimesStackLevelUpdater";
  2462. }
  2463. JsonNode TimesStackLevelUpdater::toJsonNode() const
  2464. {
  2465. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  2466. }
  2467. OwnerUpdater::OwnerUpdater()
  2468. {
  2469. }
  2470. std::string OwnerUpdater::toString() const
  2471. {
  2472. return "OwnerUpdater";
  2473. }
  2474. JsonNode OwnerUpdater::toJsonNode() const
  2475. {
  2476. return JsonUtils::stringNode("BONUS_OWNER_UPDATER");
  2477. }
  2478. std::shared_ptr<Bonus> OwnerUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2479. {
  2480. auto owner = CBonusSystemNode::retrieveNodeOwner(&context);
  2481. if(owner == PlayerColor::UNFLAGGABLE)
  2482. owner = PlayerColor::NEUTRAL;
  2483. std::shared_ptr<Bonus> updated = std::make_shared<Bonus>(
  2484. (Bonus::BonusDuration)b->duration, b->type, b->source, b->val, b->sid, b->subtype, b->valType);
  2485. updated->limiter = std::make_shared<OppositeSideLimiter>(owner);
  2486. return updated;
  2487. }
  2488. VCMI_LIB_NAMESPACE_END