From 87a7a13211ee54068d5509609857a37e5d31cf9a Mon Sep 17 00:00:00 2001 From: lisk77 Date: Mon, 31 Mar 2025 20:58:25 +0200 Subject: [PATCH] feat: added interpolation.rs for different kinds of interpolations --- crates/comet_math/src/interpolation.rs | 33 ++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 crates/comet_math/src/interpolation.rs diff --git a/crates/comet_math/src/interpolation.rs b/crates/comet_math/src/interpolation.rs new file mode 100644 index 0000000..6a7ad99 --- /dev/null +++ b/crates/comet_math/src/interpolation.rs @@ -0,0 +1,33 @@ +use std::f32::consts::PI; + +pub fn lerp(a: f32, b: f32, t: f32) -> f32 { + a * (1.0 - t) + b * t +} + +pub fn inverse_lerp(a: f32, b: f32, x: f32) -> f32 { + (x - a) / (b - a) +} + +pub fn smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 { + let t = ((x - edge0) / (edge1 - edge0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +pub fn inverse_smoothstep(v: f32) -> f32 { + (0.5 - (0.5 - v.sqrt()).sqrt()).clamp(0.0, 1.0) +} + +pub fn smootherstep(edge0: f32, edge1: f32, x: f32) -> f32 { + let t = ((x - edge0) / (edge1 - edge0)).clamp(0.0, 1.0); + t * t * t * (t * (t * 6.0 - 15.0) + 10.0) +} + +pub fn cosine_interpolate(a: f32, b: f32, x: f32) -> f32 { + let ft = x * PI; + let f = (1.0 - ft.cos()) * 0.5; + a * (1.0 - f) + b * f +} + +pub fn inverse_cosine_interpolate(a: f32, b: f32, v: f32) -> f32 { + ((1.0 - 2.0 * (v - a) / (b - a)).acos()) / PI +} \ No newline at end of file