Defensive programming in DamageLibrary, ensuring the final damage is between 0 and uint32 max.
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Deukhoofd 2020-08-11 21:47:05 +02:00
parent 5e917b7047
commit ece07f5648
Signed by: Deukhoofd
GPG Key ID: F63E044490819F6F
1 changed files with 11 additions and 2 deletions

View File

@ -11,9 +11,18 @@ uint32_t PkmnLib::Battling::DamageLibrary::GetDamage(CreatureLib::Battling::Exec
auto levelMod = static_cast<float>(2 * attack->GetUser()->GetLevel()); auto levelMod = static_cast<float>(2 * attack->GetUser()->GetLevel());
auto bp = hitData.GetBasePower(); auto bp = hitData.GetBasePower();
auto statMod = GetStatModifier(attack, target, hitIndex, hitData); auto statMod = GetStatModifier(attack, target, hitIndex, hitData);
auto damageMod = GetDamageModifier(attack, target, hitIndex, hitData);
// HOOK: Modify stat modifier // HOOK: Modify stat modifier
int damage = static_cast<int>((((levelMod * static_cast<float>(bp) * statMod) / 50) + 2) *
GetDamageModifier(attack, target, hitIndex, hitData)); auto floatDamage = (((levelMod * static_cast<float>(bp) * statMod) / 50) + 2) * damageMod;
uint32_t damage;
if (floatDamage < 0) {
damage = 0;
} else if (floatDamage > (float)UINT32_MAX) {
damage = UINT32_MAX;
} else { // TODO: C++ 20 - add [[likely]] attribute when supported by both gcc and Clang
damage = static_cast<uint32_t>(floatDamage);
}
// HOOK: Override damage // HOOK: Override damage
return damage; return damage;
} }