1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/// Easing curve used to remap normalized tween progress.
///
/// Curves receive progress in `0.0..=1.0` and return a remapped progress value.
/// Some curves may overshoot above `1.0` to create a spring-like visual feel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Easing {
/// Constant speed with no acceleration.
Linear,
/// Smooth polynomial ramp with zero slope at both ends.
SmoothStep,
/// Cubic acceleration from rest.
EaseInCubic,
/// Cubic deceleration into rest.
EaseOutCubic,
/// Cubic acceleration and deceleration around the midpoint.
#[default]
EaseInOutCubic,
/// Fast exponential movement that settles near the end.
EaseOutExpo,
/// Overshoots the target, then settles back.
EaseOutBack,
}
impl Easing {
/// Samples the curve at normalized progress.
///
/// Input is clamped to `0.0..=1.0`. Output is usually in that same range,
/// except for overshooting curves such as [`Easing::EaseOutBack`].
pub fn sample(self, amount: f32) -> f32 {
let t = if amount.is_finite() {
amount.clamp(0.0, 1.0)
} else {
0.0
};
match self {
Self::Linear => t,
Self::SmoothStep => t * t * (3.0 - 2.0 * t),
Self::EaseInCubic => t * t * t,
Self::EaseOutCubic => 1.0 - (1.0 - t).powi(3),
Self::EaseInOutCubic if t < 0.5 => 4.0 * t * t * t,
Self::EaseInOutCubic => 1.0 - (-2.0 * t + 2.0).powi(3) * 0.5,
Self::EaseOutExpo if t >= 1.0 => 1.0,
Self::EaseOutExpo => 1.0 - 2.0_f32.powf(-10.0 * t),
Self::EaseOutBack => {
let c1 = 1.70158;
let c3 = c1 + 1.0;
1.0 + c3 * (t - 1.0).powi(3) + c1 * (t - 1.0).powi(2)
}
}
}
}
#[cfg(test)]
mod tests {
use super::Easing;
#[test]
fn easing_clamps_input() {
assert_eq!(Easing::Linear.sample(-1.0), 0.0);
assert_eq!(Easing::Linear.sample(2.0), 1.0);
assert_eq!(Easing::Linear.sample(f32::NAN), 0.0);
}
#[test]
fn every_curve_has_exact_finite_endpoints() {
let curves = [
Easing::Linear,
Easing::SmoothStep,
Easing::EaseInCubic,
Easing::EaseOutCubic,
Easing::EaseInOutCubic,
Easing::EaseOutExpo,
Easing::EaseOutBack,
];
for curve in curves {
assert_eq!(curve.sample(0.0), 0.0, "{curve:?} start");
assert_eq!(curve.sample(1.0), 1.0, "{curve:?} end");
assert!(curve.sample(0.5).is_finite(), "{curve:?} midpoint");
assert!(
curve.sample(f32::INFINITY).is_finite(),
"{curve:?} infinity"
);
}
}
}