HeroBonus.cpp 75 KB

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