HeroBonus.cpp 75 KB

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