MISC: clamping numbers (#1104)

This commit is contained in:
Caldwell 2024-02-27 15:47:00 +01:00 committed by GitHub
parent 153dbfff12
commit 3d6692b292
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 27 additions and 16 deletions

@ -1,37 +1,33 @@
import { clampNumber } from "../../utils/helpers/clampNumber";
/**
* Given an experience amount and stat multiplier, calculates the
* stat level. Stat-agnostic (same formula for every stat)
*/
export function calculateSkill(exp: number, mult = 1): number {
return Math.max(Math.floor(mult * (32 * Math.log(exp + 534.6) - 200)), 1);
const value = Math.floor(mult * (32 * Math.log(exp + 534.6) - 200));
return clampNumber(value, 1);
}
export function calculateExp(skill: number, mult = 1): number {
return Math.exp((skill / mult + 200) / 32) - 534.6;
const value = Math.exp((skill / mult + 200) / 32) - 534.6;
return clampNumber(value, 0);
}
export function calculateSkillProgress(exp: number, mult = 1): ISkillProgress {
const currentSkill = calculateSkill(exp, mult);
const nextSkill = currentSkill + 1;
let baseExperience = calculateExp(currentSkill, mult);
if (baseExperience < 0) baseExperience = 0;
let nextExperience = calculateExp(nextSkill, mult);
if (nextExperience < 0) nextExperience = 0;
const baseExperience = calculateExp(currentSkill, mult);
const nextExperience = calculateExp(nextSkill, mult);
const normalize = (value: number): number => ((value - baseExperience) * 100) / (nextExperience - baseExperience);
let progress = nextExperience - baseExperience !== 0 ? normalize(exp) : 99.99;
// Clamp progress: When sleeves are working out, the player gets way too much progress
if (progress < 0) progress = 0;
if (progress > 100) progress = 100;
const rawProgress = nextExperience - baseExperience !== 0 ? normalize(exp) : 99.99;
const progress = clampNumber(rawProgress, 0, 100);
// Clamp floating point imprecisions
let currentExperience = exp - baseExperience;
let remainingExperience = nextExperience - exp;
if (currentExperience < 0) currentExperience = 0;
if (remainingExperience < 0) remainingExperience = 0;
const currentExperience = clampNumber(exp - baseExperience, 0);
const remainingExperience = clampNumber(nextExperience - exp, 0);
return {
currentSkill,

@ -0,0 +1,15 @@
import { CONSTANTS } from "../../Constants";
/**
* Clamps the value on a lower and an upper bound
* @param {number} value Value to clamp
* @param {number} min Lower bound, defaults to Number.MIN_VALUE
* @param {number} max Upper bound, defaults to Number.MAX_VALUE
* @returns {number} Clamped value
*/
export function clampNumber(value: number, min = Number.MIN_VALUE, max = Number.MAX_VALUE) {
if (isNaN(value)) {
if (CONSTANTS.isDevBranch) throw new Error("NaN passed into clampNumber()");
return min;
}
return Math.max(Math.min(value, max), min);
}