lc_render/math/
linear.rs

1const DEFAULT_NORMALIZE: f32 = 0.5_f32;
2
3/// Normalize a value x in [a; b] and return the corresponding value from the [0; 1] range.
4pub fn normalize(start: f32, end: f32, x: f32) -> f32 {
5    if (end - start).abs() < f32::EPSILON {
6        return DEFAULT_NORMALIZE;
7    }
8
9    (x - start) / range(start, end)
10}
11
12/// Interpolate a value x in [0; 1] and return the corresponding value from the [start; end] range.
13pub fn interpolate(start: f32, end: f32, x: f32) -> f32 {
14    range(start, end) * x + start
15}
16
17/// Calculate a range from the provided start and end values.
18pub fn range(start: f32, end: f32) -> f32 {
19    end - start
20}
21
22#[cfg(test)]
23mod tests {
24    use super::*;
25
26    #[test]
27    fn normalize_basic() {
28        let result = normalize(0_f32, 100_f32, 2_f32);
29        assert!((result - 0.02_f32).abs() < f32::EPSILON);
30    }
31
32    #[test]
33    fn interpolate_basic() {
34        let result = interpolate(100_f32, 400_f32, 2_f32);
35        assert!((result - 700_f32).abs() < f32::EPSILON);
36    }
37
38    #[test]
39    fn range_basic() {
40        let result = range(11_f32, 54_f32);
41        assert!((result - 43_f32).abs() < f32::EPSILON);
42    }
43}