DamageCalculator.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /*
  2. * DamageCalculator.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 "DamageCalculator.h"
  12. #include "CBattleInfoCallback.h"
  13. #include "Unit.h"
  14. #include "../bonuses/Bonus.h"
  15. #include "../bonuses/BonusSubtypes.h"
  16. #include "../mapObjects/CGTownInstance.h"
  17. #include "../spells/CSpellHandler.h"
  18. #include "../GameSettings.h"
  19. VCMI_LIB_NAMESPACE_BEGIN
  20. DamageRange DamageCalculator::getBaseDamageSingle() const
  21. {
  22. int64_t minDmg = 0.0;
  23. int64_t maxDmg = 0.0;
  24. minDmg = info.attacker->getMinDamage(info.shooting);
  25. maxDmg = info.attacker->getMaxDamage(info.shooting);
  26. if(info.attacker->creatureIndex() == CreatureID::ARROW_TOWERS)
  27. {
  28. const auto * town = callback.battleGetDefendedTown();
  29. assert(town);
  30. switch(info.attacker->getPosition())
  31. {
  32. case BattleHex::CASTLE_CENTRAL_TOWER:
  33. return town->getKeepDamageRange();
  34. case BattleHex::CASTLE_BOTTOM_TOWER:
  35. case BattleHex::CASTLE_UPPER_TOWER:
  36. return town->getTowerDamageRange();
  37. default:
  38. assert(0);
  39. }
  40. }
  41. const std::string cachingStrSiedgeWeapon = "type_SIEGE_WEAPON";
  42. static const auto selectorSiedgeWeapon = Selector::type()(BonusType::SIEGE_WEAPON);
  43. if(info.attacker->hasBonus(selectorSiedgeWeapon, cachingStrSiedgeWeapon) && info.attacker->creatureIndex() != CreatureID::ARROW_TOWERS)
  44. {
  45. auto retrieveHeroPrimSkill = [&](PrimarySkill skill) -> int
  46. {
  47. std::shared_ptr<const Bonus> b = info.attacker->getBonus(Selector::sourceTypeSel(BonusSource::HERO_BASE_SKILL).And(Selector::typeSubtype(BonusType::PRIMARY_SKILL, TBonusSubtype(skill))));
  48. return b ? b->val : 0;
  49. };
  50. //minDmg and maxDmg are multiplied by hero attack + 1
  51. minDmg *= retrieveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  52. maxDmg *= retrieveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  53. }
  54. return { minDmg, maxDmg };
  55. }
  56. DamageRange DamageCalculator::getBaseDamageBlessCurse() const
  57. {
  58. const std::string cachingStrForcedMinDamage = "type_ALWAYS_MINIMUM_DAMAGE";
  59. static const auto selectorForcedMinDamage = Selector::type()(BonusType::ALWAYS_MINIMUM_DAMAGE);
  60. const std::string cachingStrForcedMaxDamage = "type_ALWAYS_MAXIMUM_DAMAGE";
  61. static const auto selectorForcedMaxDamage = Selector::type()(BonusType::ALWAYS_MAXIMUM_DAMAGE);
  62. TConstBonusListPtr curseEffects = info.attacker->getBonuses(selectorForcedMinDamage, cachingStrForcedMinDamage);
  63. TConstBonusListPtr blessEffects = info.attacker->getBonuses(selectorForcedMaxDamage, cachingStrForcedMaxDamage);
  64. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  65. DamageRange baseDamage = getBaseDamageSingle();
  66. DamageRange modifiedDamage = {
  67. std::max(static_cast<int64_t>(1), baseDamage.min + curseBlessAdditiveModifier),
  68. std::max(static_cast<int64_t>(1), baseDamage.max + curseBlessAdditiveModifier)
  69. };
  70. if(curseEffects->size() && blessEffects->size() )
  71. {
  72. logGlobal->warn("Stack has both curse and bless! Effects will negate each other!");
  73. return modifiedDamage;
  74. }
  75. if(curseEffects->size())
  76. {
  77. return {
  78. modifiedDamage.min,
  79. modifiedDamage.min
  80. };
  81. }
  82. if(blessEffects->size())
  83. {
  84. return {
  85. modifiedDamage.max,
  86. modifiedDamage.max
  87. };
  88. }
  89. return modifiedDamage;
  90. }
  91. DamageRange DamageCalculator::getBaseDamageStack() const
  92. {
  93. auto stackSize = info.attacker->getCount();
  94. auto baseDamage = getBaseDamageBlessCurse();
  95. return {
  96. baseDamage.min * stackSize,
  97. baseDamage.max * stackSize
  98. };
  99. }
  100. int DamageCalculator::getActorAttackBase() const
  101. {
  102. return info.attacker->getAttack(info.shooting);
  103. }
  104. int DamageCalculator::getActorAttackEffective() const
  105. {
  106. return getActorAttackBase() + getActorAttackSlayer();
  107. }
  108. int DamageCalculator::getActorAttackSlayer() const
  109. {
  110. const std::string cachingStrSlayer = "type_SLAYER";
  111. static const auto selectorSlayer = Selector::type()(BonusType::SLAYER);
  112. auto slayerEffects = info.attacker->getBonuses(selectorSlayer, cachingStrSlayer);
  113. auto slayerAffected = info.defender->unitType()->valOfBonuses(Selector::type()(BonusType::KING));
  114. if(std::shared_ptr<const Bonus> slayerEffect = slayerEffects->getFirst(Selector::all))
  115. {
  116. const auto spLevel = slayerEffect->val;
  117. bool isAffected = spLevel >= slayerAffected;
  118. if(isAffected)
  119. {
  120. SpellID spell(SpellID::SLAYER);
  121. int attackBonus = spell.toSpell()->getLevelPower(spLevel);
  122. if(info.attacker->hasBonusOfType(BonusType::SPECIAL_PECULIAR_ENCHANT, TBonusSubtype(spell)))
  123. {
  124. ui8 attackerTier = info.attacker->unitType()->getLevel();
  125. ui8 specialtyBonus = std::max(5 - attackerTier, 0);
  126. attackBonus += specialtyBonus;
  127. }
  128. return attackBonus;
  129. }
  130. }
  131. return 0;
  132. }
  133. int DamageCalculator::getTargetDefenseBase() const
  134. {
  135. return info.defender->getDefense(info.shooting);
  136. }
  137. int DamageCalculator::getTargetDefenseEffective() const
  138. {
  139. return getTargetDefenseBase() + getTargetDefenseIgnored();
  140. }
  141. int DamageCalculator::getTargetDefenseIgnored() const
  142. {
  143. double multDefenceReduction = battleBonusValue(info.attacker, Selector::type()(BonusType::ENEMY_DEFENCE_REDUCTION)) / 100.0;
  144. if(multDefenceReduction > 0)
  145. {
  146. int reduction = std::floor(multDefenceReduction * getTargetDefenseBase()) + 1;
  147. return -std::min(reduction,getTargetDefenseBase());
  148. }
  149. return 0;
  150. }
  151. double DamageCalculator::getAttackSkillFactor() const
  152. {
  153. int attackAdvantage = getActorAttackEffective() - getTargetDefenseEffective();
  154. if(attackAdvantage > 0)
  155. {
  156. const double attackMultiplier = VLC->settings()->getDouble(EGameSettings::COMBAT_ATTACK_POINT_DAMAGE_FACTOR);
  157. const double attackMultiplierCap = VLC->settings()->getDouble(EGameSettings::COMBAT_ATTACK_POINT_DAMAGE_FACTOR_CAP);
  158. const double attackFactor = std::min(attackMultiplier * attackAdvantage, attackMultiplierCap);
  159. return attackFactor;
  160. }
  161. return 0.f;
  162. }
  163. double DamageCalculator::getAttackBlessFactor() const
  164. {
  165. const std::string cachingStrDamage = "type_GENERAL_DAMAGE_PREMY";
  166. static const auto selectorDamage = Selector::type()(BonusType::GENERAL_DAMAGE_PREMY);
  167. return info.attacker->valOfBonuses(selectorDamage, cachingStrDamage) / 100.0;
  168. }
  169. double DamageCalculator::getAttackOffenseArcheryFactor() const
  170. {
  171. if(info.shooting)
  172. {
  173. const std::string cachingStrArchery = "type_PERCENTAGE_DAMAGE_BOOSTs_1";
  174. static const auto selectorArchery = Selector::typeSubtype(BonusType::PERCENTAGE_DAMAGE_BOOST, BonusSubtypes::damageTypeRanged);
  175. return info.attacker->valOfBonuses(selectorArchery, cachingStrArchery) / 100.0;
  176. }
  177. const std::string cachingStrOffence = "type_PERCENTAGE_DAMAGE_BOOSTs_0";
  178. static const auto selectorOffence = Selector::typeSubtype(BonusType::PERCENTAGE_DAMAGE_BOOST, BonusSubtypes::damageTypeMelee);
  179. return info.attacker->valOfBonuses(selectorOffence, cachingStrOffence) / 100.0;
  180. }
  181. double DamageCalculator::getAttackLuckFactor() const
  182. {
  183. if(info.luckyStrike)
  184. return 1.0;
  185. return 0.0;
  186. }
  187. double DamageCalculator::getAttackDeathBlowFactor() const
  188. {
  189. if(info.deathBlow)
  190. return 1.0;
  191. return 0.0;
  192. }
  193. double DamageCalculator::getAttackDoubleDamageFactor() const
  194. {
  195. if(info.doubleDamage) {
  196. const auto cachingStr = "type_BONUS_DAMAGE_PERCENTAGEs_" + std::to_string(info.attacker->creatureIndex());
  197. const auto selector = Selector::typeSubtype(BonusType::BONUS_DAMAGE_PERCENTAGE, TBonusSubtype(info.attacker->creatureId()));
  198. return info.attacker->valOfBonuses(selector, cachingStr) / 100.0;
  199. }
  200. return 0.0;
  201. }
  202. double DamageCalculator::getAttackJoustingFactor() const
  203. {
  204. const std::string cachingStrJousting = "type_JOUSTING";
  205. static const auto selectorJousting = Selector::type()(BonusType::JOUSTING);
  206. const std::string cachingStrChargeImmunity = "type_CHARGE_IMMUNITY";
  207. static const auto selectorChargeImmunity = Selector::type()(BonusType::CHARGE_IMMUNITY);
  208. //applying jousting bonus
  209. if(info.chargeDistance > 0 && info.attacker->hasBonus(selectorJousting, cachingStrJousting) && !info.defender->hasBonus(selectorChargeImmunity, cachingStrChargeImmunity))
  210. return info.chargeDistance * (info.attacker->valOfBonuses(selectorJousting))/100.0;
  211. return 0.0;
  212. }
  213. double DamageCalculator::getAttackHateFactor() const
  214. {
  215. //assume that unit have only few HATE features and cache them all
  216. const std::string cachingStrHate = "type_HATE";
  217. static const auto selectorHate = Selector::type()(BonusType::HATE);
  218. auto allHateEffects = info.attacker->getBonuses(selectorHate, cachingStrHate);
  219. return allHateEffects->valOfBonuses(Selector::subtype()(TBonusSubtype(info.defender->creatureId()))) / 100.0;
  220. }
  221. double DamageCalculator::getDefenseSkillFactor() const
  222. {
  223. int defenseAdvantage = getTargetDefenseEffective() - getActorAttackEffective();
  224. //bonus from attack/defense skills
  225. if(defenseAdvantage > 0) //decreasing dmg
  226. {
  227. const double defenseMultiplier = VLC->settings()->getDouble(EGameSettings::COMBAT_DEFENSE_POINT_DAMAGE_FACTOR);
  228. const double defenseMultiplierCap = VLC->settings()->getDouble(EGameSettings::COMBAT_DEFENSE_POINT_DAMAGE_FACTOR_CAP);
  229. const double dec = std::min(defenseMultiplier * defenseAdvantage, defenseMultiplierCap);
  230. return dec;
  231. }
  232. return 0.0;
  233. }
  234. double DamageCalculator::getDefenseArmorerFactor() const
  235. {
  236. const std::string cachingStrArmorer = "type_GENERAL_DAMAGE_REDUCTIONs_N1_NsrcSPELL_EFFECT";
  237. static const auto selectorArmorer = Selector::typeSubtype(BonusType::GENERAL_DAMAGE_REDUCTION, BonusSubtypes::damageTypeAll).And(Selector::sourceTypeSel(BonusSource::SPELL_EFFECT).Not());
  238. return info.defender->valOfBonuses(selectorArmorer, cachingStrArmorer) / 100.0;
  239. }
  240. double DamageCalculator::getDefenseMagicShieldFactor() const
  241. {
  242. const std::string cachingStrMeleeReduction = "type_GENERAL_DAMAGE_REDUCTIONs_0";
  243. static const auto selectorMeleeReduction = Selector::typeSubtype(BonusType::GENERAL_DAMAGE_REDUCTION, BonusSubtypes::damageTypeMelee);
  244. const std::string cachingStrRangedReduction = "type_GENERAL_DAMAGE_REDUCTIONs_1";
  245. static const auto selectorRangedReduction = Selector::typeSubtype(BonusType::GENERAL_DAMAGE_REDUCTION, BonusSubtypes::damageTypeRanged);
  246. //handling spell effects - shield and air shield
  247. if(info.shooting)
  248. return info.defender->valOfBonuses(selectorRangedReduction, cachingStrRangedReduction) / 100.0;
  249. else
  250. return info.defender->valOfBonuses(selectorMeleeReduction, cachingStrMeleeReduction) / 100.0;
  251. }
  252. double DamageCalculator::getDefenseRangePenaltiesFactor() const
  253. {
  254. if(info.shooting)
  255. {
  256. BattleHex attackerPos = info.attackerPos.isValid() ? info.attackerPos : info.attacker->getPosition();
  257. BattleHex defenderPos = info.defenderPos.isValid() ? info.defenderPos : info.defender->getPosition();
  258. const std::string cachingStrAdvAirShield = "isAdvancedAirShield";
  259. auto isAdvancedAirShield = [](const Bonus* bonus)
  260. {
  261. return bonus->source == BonusSource::SPELL_EFFECT
  262. && bonus->sid == SpellID::AIR_SHIELD
  263. && bonus->val >= MasteryLevel::ADVANCED;
  264. };
  265. const bool distPenalty = callback.battleHasDistancePenalty(info.attacker, attackerPos, defenderPos);
  266. if(distPenalty || info.defender->hasBonus(isAdvancedAirShield, cachingStrAdvAirShield))
  267. return 0.5;
  268. }
  269. else
  270. {
  271. const std::string cachingStrNoMeleePenalty = "type_NO_MELEE_PENALTY";
  272. static const auto selectorNoMeleePenalty = Selector::type()(BonusType::NO_MELEE_PENALTY);
  273. if(info.attacker->isShooter() && !info.attacker->hasBonus(selectorNoMeleePenalty, cachingStrNoMeleePenalty))
  274. return 0.5;
  275. }
  276. return 0.0;
  277. }
  278. double DamageCalculator::getDefenseObstacleFactor() const
  279. {
  280. if(info.shooting)
  281. {
  282. BattleHex attackerPos = info.attackerPos.isValid() ? info.attackerPos : info.attacker->getPosition();
  283. BattleHex defenderPos = info.defenderPos.isValid() ? info.defenderPos : info.defender->getPosition();
  284. const bool obstaclePenalty = callback.battleHasWallPenalty(info.attacker, attackerPos, defenderPos);
  285. if(obstaclePenalty)
  286. return 0.5;
  287. }
  288. return 0.0;
  289. }
  290. double DamageCalculator::getDefenseUnluckyFactor() const
  291. {
  292. if(info.unluckyStrike)
  293. return 0.5;
  294. return 0.0;
  295. }
  296. double DamageCalculator::getDefenseBlindParalysisFactor() const
  297. {
  298. double multAttackReduction = battleBonusValue(info.attacker, Selector::type()(BonusType::GENERAL_ATTACK_REDUCTION)) / 100.0;
  299. return multAttackReduction;
  300. }
  301. double DamageCalculator::getDefenseForgetfulnessFactor() const
  302. {
  303. if(info.shooting)
  304. {
  305. //todo: set actual percentage in spell bonus configuration instead of just level; requires non trivial backward compatibility handling
  306. //get list first, total value of 0 also counts
  307. TConstBonusListPtr forgetfulList = info.attacker->getBonuses(Selector::type()(BonusType::FORGETFULL),"type_FORGETFULL");
  308. if(!forgetfulList->empty())
  309. {
  310. int forgetful = forgetfulList->valOfBonuses(Selector::all);
  311. //none of basic level
  312. if(forgetful == 0 || forgetful == 1)
  313. return 0.5;
  314. else
  315. logGlobal->warn("Attempt to calculate shooting damage with adv+ FORGETFULL effect");
  316. }
  317. }
  318. return 0.0;
  319. }
  320. double DamageCalculator::getDefensePetrificationFactor() const
  321. {
  322. // Creatures that are petrified by a Basilisk's Petrifying attack or a Medusa's Stone gaze take 50% damage (R8 = 0.50) from ranged and melee attacks. Taking damage also deactivates the effect.
  323. const std::string cachingStrAllReduction = "type_GENERAL_DAMAGE_REDUCTIONs_N1_srcSPELL_EFFECT";
  324. static const auto selectorAllReduction = Selector::typeSubtype(BonusType::GENERAL_DAMAGE_REDUCTION, BonusSubtypes::damageTypeAll).And(Selector::sourceTypeSel(BonusSource::SPELL_EFFECT));
  325. return info.defender->valOfBonuses(selectorAllReduction, cachingStrAllReduction) / 100.0;
  326. }
  327. double DamageCalculator::getDefenseMagicFactor() const
  328. {
  329. // Magic Elementals deal half damage (R8 = 0.50) against Magic Elementals and Black Dragons. This is not affected by the Orb of Vulnerability, Anti-Magic, or Magic Resistance.
  330. if(info.attacker->creatureIndex() == CreatureID::MAGIC_ELEMENTAL)
  331. {
  332. const std::string cachingStrMagicImmunity = "type_LEVEL_SPELL_IMMUNITY";
  333. static const auto selectorMagicImmunity = Selector::type()(BonusType::LEVEL_SPELL_IMMUNITY);
  334. if(info.defender->valOfBonuses(selectorMagicImmunity, cachingStrMagicImmunity) >= 5)
  335. return 0.5;
  336. }
  337. return 0.0;
  338. }
  339. double DamageCalculator::getDefenseMindFactor() const
  340. {
  341. // Psychic Elementals deal half damage (R8 = 0.50) against creatures that are immune to Mind spells, such as Giants and Undead. This is not affected by the Orb of Vulnerability.
  342. if(info.attacker->creatureIndex() == CreatureID::PSYCHIC_ELEMENTAL)
  343. {
  344. const std::string cachingStrMindImmunity = "type_MIND_IMMUNITY";
  345. static const auto selectorMindImmunity = Selector::type()(BonusType::MIND_IMMUNITY);
  346. if(info.defender->hasBonus(selectorMindImmunity, cachingStrMindImmunity))
  347. return 0.5;
  348. }
  349. return 0.0;
  350. }
  351. std::vector<double> DamageCalculator::getAttackFactors() const
  352. {
  353. return {
  354. getAttackSkillFactor(),
  355. getAttackOffenseArcheryFactor(),
  356. getAttackBlessFactor(),
  357. getAttackLuckFactor(),
  358. getAttackJoustingFactor(),
  359. getAttackDeathBlowFactor(),
  360. getAttackDoubleDamageFactor(),
  361. getAttackHateFactor()
  362. };
  363. }
  364. std::vector<double> DamageCalculator::getDefenseFactors() const
  365. {
  366. return {
  367. getDefenseSkillFactor(),
  368. getDefenseArmorerFactor(),
  369. getDefenseMagicShieldFactor(),
  370. getDefenseRangePenaltiesFactor(),
  371. getDefenseObstacleFactor(),
  372. getDefenseBlindParalysisFactor(),
  373. getDefenseUnluckyFactor(),
  374. getDefenseForgetfulnessFactor(),
  375. getDefensePetrificationFactor(),
  376. getDefenseMagicFactor(),
  377. getDefenseMindFactor()
  378. };
  379. }
  380. DamageRange DamageCalculator::getCasualties(const DamageRange & damageDealt) const
  381. {
  382. return {
  383. getCasualties(damageDealt.min),
  384. getCasualties(damageDealt.max),
  385. };
  386. }
  387. int64_t DamageCalculator::getCasualties(int64_t damageDealt) const
  388. {
  389. if (damageDealt < info.defender->getFirstHPleft())
  390. return 0;
  391. int64_t damageLeft = damageDealt - info.defender->getFirstHPleft();
  392. int64_t killsLeft = damageLeft / info.defender->getMaxHealth();
  393. return 1 + killsLeft;
  394. }
  395. int DamageCalculator::battleBonusValue(const IBonusBearer * bearer, const CSelector & selector) const
  396. {
  397. auto noLimit = Selector::effectRange()(BonusLimitEffect::NO_LIMIT);
  398. auto limitMatches = info.shooting
  399. ? Selector::effectRange()(BonusLimitEffect::ONLY_DISTANCE_FIGHT)
  400. : Selector::effectRange()(BonusLimitEffect::ONLY_MELEE_FIGHT);
  401. //any regular bonuses or just ones for melee/ranged
  402. return bearer->getBonuses(selector, noLimit.Or(limitMatches))->totalValue();
  403. };
  404. DamageEstimation DamageCalculator::calculateDmgRange() const
  405. {
  406. DamageRange damageBase = getBaseDamageStack();
  407. auto attackFactors = getAttackFactors();
  408. auto defenseFactors = getDefenseFactors();
  409. double attackFactorTotal = 1.0;
  410. double defenseFactorTotal = 1.0;
  411. for (auto & factor : attackFactors)
  412. {
  413. assert(factor >= 0.0);
  414. attackFactorTotal += factor;
  415. }
  416. for (auto & factor : defenseFactors)
  417. {
  418. assert(factor >= 0.0);
  419. defenseFactorTotal *= ( 1 - std::min(1.0, factor));
  420. }
  421. double resultingFactor = std::min(8.0, attackFactorTotal) * std::max( 0.01, defenseFactorTotal);
  422. info.defender->getTotalHealth();
  423. DamageRange damageDealt {
  424. std::max<int64_t>( 1.0, std::floor(damageBase.min * resultingFactor)),
  425. std::max<int64_t>( 1.0, std::floor(damageBase.max * resultingFactor))
  426. };
  427. DamageRange killsDealt = getCasualties(damageDealt);
  428. return DamageEstimation{damageDealt, killsDealt};
  429. }
  430. VCMI_LIB_NAMESPACE_END