HeroBonus.cpp 77 KB

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