emath/
lib.rs

1//! Opinionated 2D math library for building GUIs.
2//!
3//! Includes vectors, positions, rectangles etc.
4//!
5//! Conventions (unless otherwise specified):
6//!
7//! * All angles are in radians
8//! * X+ is right and Y+ is down.
9//! * (0,0) is left top.
10//! * Dimension order is always `x y`
11//!
12//! ## Integrating with other math libraries.
13//! `emath` does not strive to become a general purpose or all-powerful math library.
14//!
15//! For that, use something else ([`glam`](https://docs.rs/glam), [`nalgebra`](https://docs.rs/nalgebra), …)
16//! and enable the `mint` feature flag in `emath` to enable implicit conversion to/from `emath`.
17//!
18//! ## Feature flags
19#![cfg_attr(feature = "document-features", doc = document_features::document_features!())]
20//!
21
22#![allow(clippy::float_cmp)]
23
24use std::ops::{Add, Div, Mul, RangeInclusive, Sub};
25
26// ----------------------------------------------------------------------------
27
28pub mod align;
29pub mod easing;
30mod gui_rounding;
31mod history;
32mod numeric;
33mod ordered_float;
34mod pos2;
35mod range;
36mod rect;
37mod rect_align;
38mod rect_transform;
39mod rot2;
40pub mod smart_aim;
41mod ts_transform;
42mod vec2;
43mod vec2b;
44
45pub use self::{
46    align::{Align, Align2},
47    gui_rounding::{GUI_ROUNDING, GuiRounding},
48    history::History,
49    numeric::*,
50    ordered_float::*,
51    pos2::*,
52    range::Rangef,
53    rect::*,
54    rect_align::RectAlign,
55    rect_transform::*,
56    rot2::*,
57    ts_transform::*,
58    vec2::*,
59    vec2b::*,
60};
61
62// ----------------------------------------------------------------------------
63
64/// Helper trait to implement [`lerp`] and [`remap`].
65pub trait One {
66    const ONE: Self;
67}
68
69impl One for f32 {
70    const ONE: Self = 1.0;
71}
72
73impl One for f64 {
74    const ONE: Self = 1.0;
75}
76
77/// Helper trait to implement [`lerp`] and [`remap`].
78pub trait Real:
79    Copy
80    + PartialEq
81    + PartialOrd
82    + One
83    + Add<Self, Output = Self>
84    + Sub<Self, Output = Self>
85    + Mul<Self, Output = Self>
86    + Div<Self, Output = Self>
87{
88}
89
90impl Real for f32 {}
91
92impl Real for f64 {}
93
94// ----------------------------------------------------------------------------
95
96/// Linear interpolation.
97///
98/// ```
99/// # use emath::lerp;
100/// assert_eq!(lerp(1.0..=5.0, 0.0), 1.0);
101/// assert_eq!(lerp(1.0..=5.0, 0.5), 3.0);
102/// assert_eq!(lerp(1.0..=5.0, 1.0), 5.0);
103/// assert_eq!(lerp(1.0..=5.0, 2.0), 9.0);
104/// ```
105#[inline(always)]
106pub fn lerp<R, T>(range: impl Into<RangeInclusive<R>>, t: T) -> R
107where
108    T: Real + Mul<R, Output = R>,
109    R: Copy + Add<R, Output = R>,
110{
111    let range = range.into();
112    (T::ONE - t) * *range.start() + t * *range.end()
113}
114
115/// Where in the range is this value? Returns 0-1 if within the range.
116///
117/// Returns <0 if before and >1 if after.
118///
119/// Returns `None` if the input range is zero-width.
120///
121/// ```
122/// # use emath::inverse_lerp;
123/// assert_eq!(inverse_lerp(1.0..=5.0, 1.0), Some(0.0));
124/// assert_eq!(inverse_lerp(1.0..=5.0, 3.0), Some(0.5));
125/// assert_eq!(inverse_lerp(1.0..=5.0, 5.0), Some(1.0));
126/// assert_eq!(inverse_lerp(1.0..=5.0, 9.0), Some(2.0));
127/// assert_eq!(inverse_lerp(1.0..=1.0, 3.0), None);
128/// ```
129#[inline]
130pub fn inverse_lerp<R>(range: RangeInclusive<R>, value: R) -> Option<R>
131where
132    R: Copy + PartialEq + Sub<R, Output = R> + Div<R, Output = R>,
133{
134    let min = *range.start();
135    let max = *range.end();
136    if min == max {
137        None
138    } else {
139        Some((value - min) / (max - min))
140    }
141}
142
143/// Linearly remap a value from one range to another,
144/// so that when `x == from.start()` returns `to.start()`
145/// and when `x == from.end()` returns `to.end()`.
146pub fn remap<T>(x: T, from: impl Into<RangeInclusive<T>>, to: impl Into<RangeInclusive<T>>) -> T
147where
148    T: Real,
149{
150    let from = from.into();
151    let to = to.into();
152    debug_assert!(
153        from.start() != from.end(),
154        "from.start() and from.end() should not be equal"
155    );
156    let t = (x - *from.start()) / (*from.end() - *from.start());
157    lerp(to, t)
158}
159
160/// Like [`remap`], but also clamps the value so that the returned value is always in the `to` range.
161pub fn remap_clamp<T>(
162    x: T,
163    from: impl Into<RangeInclusive<T>>,
164    to: impl Into<RangeInclusive<T>>,
165) -> T
166where
167    T: Real,
168{
169    let from = from.into();
170    let to = to.into();
171    if from.end() < from.start() {
172        return remap_clamp(x, *from.end()..=*from.start(), *to.end()..=*to.start());
173    }
174    if x <= *from.start() {
175        *to.start()
176    } else if *from.end() <= x {
177        *to.end()
178    } else {
179        debug_assert!(
180            from.start() != from.end(),
181            "from.start() and from.end() should not be equal"
182        );
183        let t = (x - *from.start()) / (*from.end() - *from.start());
184        // Ensure no numerical inaccuracies sneak in:
185        if T::ONE <= t { *to.end() } else { lerp(to, t) }
186    }
187}
188
189/// Round a value to the given number of decimal places.
190pub fn round_to_decimals(value: f64, decimal_places: usize) -> f64 {
191    // This is a stupid way of doing this, but stupid works.
192    format!("{value:.decimal_places$}").parse().unwrap_or(value)
193}
194
195pub fn format_with_minimum_decimals(value: f64, decimals: usize) -> String {
196    format_with_decimals_in_range(value, decimals..=6)
197}
198
199/// Use as few decimals as possible to show the value accurately, but within the given range.
200///
201/// Decimals are counted after the decimal point.
202pub fn format_with_decimals_in_range(value: f64, decimal_range: RangeInclusive<usize>) -> String {
203    let min_decimals = *decimal_range.start();
204    let max_decimals = *decimal_range.end();
205    debug_assert!(
206        min_decimals <= max_decimals,
207        "min_decimals should be <= max_decimals, but got min_decimals: {min_decimals}, max_decimals: {max_decimals}"
208    );
209    debug_assert!(
210        max_decimals < 100,
211        "max_decimals should be < 100, but got {max_decimals}"
212    );
213    let max_decimals = max_decimals.min(16);
214    let min_decimals = min_decimals.min(max_decimals);
215
216    if min_decimals < max_decimals {
217        // Ugly/slow way of doing this. TODO(emilk): clean up precision.
218        for decimals in min_decimals..max_decimals {
219            let text = format!("{value:.decimals$}");
220            let epsilon = 16.0 * f32::EPSILON; // margin large enough to handle most peoples round-tripping needs
221            if almost_equal(text.parse::<f32>().unwrap(), value as f32, epsilon) {
222                // Enough precision to show the value accurately - good!
223                return text;
224            }
225        }
226        // The value has more precision than we expected.
227        // Probably the value was set not by the slider, but from outside.
228        // In any case: show the full value
229    }
230    format!("{value:.max_decimals$}")
231}
232
233/// Return true when arguments are the same within some rounding error.
234///
235/// For instance `almost_equal(x, x.to_degrees().to_radians(), f32::EPSILON)` should hold true for all x.
236/// The `epsilon`  can be `f32::EPSILON` to handle simple transforms (like degrees -> radians)
237/// but should be higher to handle more complex transformations.
238pub fn almost_equal(a: f32, b: f32, epsilon: f32) -> bool {
239    if a == b {
240        true // handle infinites
241    } else {
242        let abs_max = a.abs().max(b.abs());
243        abs_max <= epsilon || ((a - b).abs() / abs_max) <= epsilon
244    }
245}
246
247#[expect(clippy::approx_constant)]
248#[test]
249fn test_format() {
250    assert_eq!(format_with_minimum_decimals(1_234_567.0, 0), "1234567");
251    assert_eq!(format_with_minimum_decimals(1_234_567.0, 1), "1234567.0");
252    assert_eq!(format_with_minimum_decimals(3.14, 2), "3.14");
253    assert_eq!(format_with_minimum_decimals(3.14, 3), "3.140");
254    assert_eq!(
255        format_with_minimum_decimals(std::f64::consts::PI, 2),
256        "3.14159"
257    );
258}
259
260#[test]
261fn test_almost_equal() {
262    for &x in &[
263        0.0_f32,
264        f32::MIN_POSITIVE,
265        1e-20,
266        1e-10,
267        f32::EPSILON,
268        0.1,
269        0.99,
270        1.0,
271        1.001,
272        1e10,
273        f32::MAX / 100.0,
274        // f32::MAX, // overflows in rad<->deg test
275        f32::INFINITY,
276    ] {
277        for &x in &[-x, x] {
278            for roundtrip in &[
279                |x: f32| x.to_degrees().to_radians(),
280                |x: f32| x.to_radians().to_degrees(),
281            ] {
282                let epsilon = f32::EPSILON;
283                assert!(
284                    almost_equal(x, roundtrip(x), epsilon),
285                    "{} vs {}",
286                    x,
287                    roundtrip(x)
288                );
289            }
290        }
291    }
292}
293
294#[test]
295fn test_remap() {
296    assert_eq!(remap_clamp(1.0, 0.0..=1.0, 0.0..=16.0), 16.0);
297    assert_eq!(remap_clamp(1.0, 1.0..=0.0, 16.0..=0.0), 16.0);
298    assert_eq!(remap_clamp(0.5, 1.0..=0.0, 16.0..=0.0), 8.0);
299}
300
301// ----------------------------------------------------------------------------
302
303/// Extends `f32`, [`Vec2`] etc with `at_least` and `at_most` as aliases for `max` and `min`.
304pub trait NumExt {
305    /// More readable version of `self.max(lower_limit)`
306    #[must_use]
307    fn at_least(self, lower_limit: Self) -> Self;
308
309    /// More readable version of `self.min(upper_limit)`
310    #[must_use]
311    fn at_most(self, upper_limit: Self) -> Self;
312}
313
314macro_rules! impl_num_ext {
315    ($t: ty) => {
316        impl NumExt for $t {
317            #[inline(always)]
318            fn at_least(self, lower_limit: Self) -> Self {
319                self.max(lower_limit)
320            }
321
322            #[inline(always)]
323            fn at_most(self, upper_limit: Self) -> Self {
324                self.min(upper_limit)
325            }
326        }
327    };
328}
329
330impl_num_ext!(u8);
331impl_num_ext!(u16);
332impl_num_ext!(u32);
333impl_num_ext!(u64);
334impl_num_ext!(u128);
335impl_num_ext!(usize);
336impl_num_ext!(i8);
337impl_num_ext!(i16);
338impl_num_ext!(i32);
339impl_num_ext!(i64);
340impl_num_ext!(i128);
341impl_num_ext!(isize);
342impl_num_ext!(f32);
343impl_num_ext!(f64);
344impl_num_ext!(Vec2);
345impl_num_ext!(Pos2);
346
347// ----------------------------------------------------------------------------
348
349/// Wrap angle to `[-PI, PI]` range.
350pub fn normalized_angle(mut angle: f32) -> f32 {
351    use std::f32::consts::{PI, TAU};
352    angle %= TAU;
353    if angle > PI {
354        angle -= TAU;
355    } else if angle < -PI {
356        angle += TAU;
357    }
358    angle
359}
360
361#[test]
362fn test_normalized_angle() {
363    macro_rules! almost_eq {
364        ($left: expr, $right: expr) => {
365            let left = $left;
366            let right = $right;
367            assert!((left - right).abs() < 1e-6, "{} != {}", left, right);
368        };
369    }
370
371    use std::f32::consts::TAU;
372    almost_eq!(normalized_angle(-3.0 * TAU), 0.0);
373    almost_eq!(normalized_angle(-2.3 * TAU), -0.3 * TAU);
374    almost_eq!(normalized_angle(-TAU), 0.0);
375    almost_eq!(normalized_angle(0.0), 0.0);
376    almost_eq!(normalized_angle(TAU), 0.0);
377    almost_eq!(normalized_angle(2.7 * TAU), -0.3 * TAU);
378}
379
380// ----------------------------------------------------------------------------
381
382/// Calculate a lerp-factor for exponential smoothing using a time step.
383///
384/// * `exponential_smooth_factor(0.90, 1.0, dt)`: reach 90% in 1.0 seconds
385/// * `exponential_smooth_factor(0.50, 0.2, dt)`: reach 50% in 0.2 seconds
386///
387/// Example:
388/// ```
389/// # use emath::{lerp, exponential_smooth_factor};
390/// # let (mut smoothed_value, target_value, dt) = (0.0_f32, 1.0_f32, 0.01_f32);
391/// let t = exponential_smooth_factor(0.90, 0.2, dt); // reach 90% in 0.2 seconds
392/// smoothed_value = lerp(smoothed_value..=target_value, t);
393/// ```
394pub fn exponential_smooth_factor(
395    reach_this_fraction: f32,
396    in_this_many_seconds: f32,
397    dt: f32,
398) -> f32 {
399    1.0 - (1.0 - reach_this_fraction).powf(dt / in_this_many_seconds)
400}
401
402/// If you have a value animating over time,
403/// how much towards its target do you need to move it this frame?
404///
405/// You only need to store the start time and target value in order to animate using this function.
406///
407/// ``` rs
408/// struct Animation {
409///     current_value: f32,
410///
411///     animation_time_span: (f64, f64),
412///     target_value: f32,
413/// }
414///
415/// impl Animation {
416///     fn update(&mut self, now: f64, dt: f32) {
417///         let t = interpolation_factor(self.animation_time_span, now, dt, ease_in_ease_out);
418///         self.current_value = emath::lerp(self.current_value..=self.target_value, t);
419///     }
420/// }
421/// ```
422pub fn interpolation_factor(
423    (start_time, end_time): (f64, f64),
424    current_time: f64,
425    dt: f32,
426    easing: impl Fn(f32) -> f32,
427) -> f32 {
428    let animation_duration = (end_time - start_time) as f32;
429    let prev_time = current_time - dt as f64;
430    let prev_t = easing((prev_time - start_time) as f32 / animation_duration);
431    let end_t = easing((current_time - start_time) as f32 / animation_duration);
432    if end_t < 1.0 {
433        (end_t - prev_t) / (1.0 - prev_t)
434    } else {
435        1.0
436    }
437}
438
439/// Ease in, ease out.
440///
441/// `f(0) = 0, f'(0) = 0, f(1) = 1, f'(1) = 0`.
442#[inline]
443pub fn ease_in_ease_out(t: f32) -> f32 {
444    let t = t.clamp(0.0, 1.0);
445    (3.0 * t * t - 2.0 * t * t * t).clamp(0.0, 1.0)
446}