Skip to main content

aureole_animation/
curve.rs

1use std::f32::consts::TAU;
2use std::time::Duration;
3
4/// 弹簧,用"响应时间 + 阻尼比"描述,比刚度和阻尼系数直观。
5///
6/// 弹簧没有固定时长:目标变了就从当前位置和速度出发奔向新目标,
7/// 所以被打断时运动是连续的,这是"手感"的关键。
8#[derive(Clone, Copy, Debug, PartialEq)]
9pub struct Spring {
10    /// 无阻尼时振动一个周期的时间;越小越快
11    pub response: Duration,
12    /// 阻尼比:1 为临界阻尼(不回弹),越小回弹越多
13    pub damping_ratio: f32,
14}
15
16impl Spring {
17    /// 指定响应时间和阻尼比
18    pub const fn new(response: Duration, damping_ratio: f32) -> Self {
19        Self { response, damping_ratio }
20    }
21
22    /// 平滑,不回弹
23    pub const fn smooth() -> Self {
24        Self::new(Duration::from_millis(450), 1.0)
25    }
26
27    /// 快、跟手,几乎不回弹,适合悬停和按压
28    pub const fn snappy() -> Self {
29        Self::new(Duration::from_millis(300), 0.86)
30    }
31
32    /// 明显回弹
33    pub const fn bouncy() -> Self {
34        Self::new(Duration::from_millis(500), 0.6)
35    }
36
37    /// 无阻尼角频率
38    pub(crate) fn omega(&self) -> f32 {
39        TAU / seconds(self.response).max(1e-4)
40    }
41}
42
43impl Default for Spring {
44    fn default() -> Self {
45        Self::new(Duration::from_millis(500), 0.85)
46    }
47}
48
49/// 缓动函数:三次贝塞尔曲线,起点 (0, 0)、终点 (1, 1),两个控制点决定快慢
50#[derive(Clone, Copy, Debug, PartialEq)]
51#[non_exhaustive]
52pub enum Easing {
53    /// 匀速
54    Linear,
55    /// 两个控制点 `(x1, y1, x2, y2)`;x 应在 0..=1 内,y 可以超出范围形成过冲
56    CubicBezier(f32, f32, f32, f32),
57}
58
59impl Easing {
60    /// 起步稍快、收尾放慢,最常用的默认值
61    pub const EASE: Self = Self::CubicBezier(0.25, 0.1, 0.25, 1.0);
62    /// 慢起步,越来越快
63    pub const EASE_IN: Self = Self::CubicBezier(0.42, 0.0, 1.0, 1.0);
64    /// 快起步,逐渐放慢
65    pub const EASE_OUT: Self = Self::CubicBezier(0.0, 0.0, 0.58, 1.0);
66    /// 两端慢、中间快
67    pub const EASE_IN_OUT: Self = Self::CubicBezier(0.42, 0.0, 0.58, 1.0);
68
69    /// 进度 `x`(0..=1)映射到缓动后的进度
70    pub fn apply(&self, x: f32) -> f32 {
71        match *self {
72            Self::Linear => x.clamp(0.0, 1.0),
73            Self::CubicBezier(x1, y1, x2, y2) => cubic_bezier(x1, y1, x2, y2, x),
74        }
75    }
76
77    /// 进度 `x` 处的斜率:缓动后的进度对进度的导数(补间的速度 = 两端之差 × 斜率 ÷ 时长)。
78    /// `x` 超出 0..=1 时按端点算
79    pub fn slope(&self, x: f32) -> f32 {
80        match *self {
81            Self::Linear => 1.0,
82            Self::CubicBezier(x1, y1, x2, y2) => cubic_bezier_slope(x1, y1, x2, y2, x.clamp(0.0, 1.0)),
83        }
84    }
85}
86
87/// 补间结束后怎么办
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub enum Repeat {
90    /// 停在目标值
91    Once,
92    /// 回到起点重新开始,一直循环(转圈:0 → 2π)
93    Forever,
94    /// 来回往返,一直循环(呼吸、脉冲)
95    Alternate,
96}
97
98/// 补间:固定时长,从当前值按缓动曲线走到目标
99#[derive(Clone, Copy, Debug, PartialEq)]
100pub struct Tween {
101    /// 时长
102    pub duration: Duration,
103    /// 缓动曲线
104    pub easing: Easing,
105    /// 结束后是否循环
106    pub repeat: Repeat,
107}
108
109impl Tween {
110    /// 指定时长,默认缓动为 `ease`(起步稍快、收尾放慢)
111    pub const fn new(duration: Duration) -> Self {
112        Self { duration, easing: Easing::EASE, repeat: Repeat::Once }
113    }
114
115    /// 一直循环:到达目标后回到起点重新开始,永不停止;和 [`Tween::alternate`] 连用时是来回往返
116    pub const fn forever(mut self) -> Self {
117        if matches!(self.repeat, Repeat::Once) {
118            self.repeat = Repeat::Forever;
119        }
120        self
121    }
122
123    /// 往返:在起点和目标之间来回,永不停止(和 [`Tween::forever`] 连用,先后不论);`false` 回到不往返
124    pub const fn alternate(mut self, alternate: bool) -> Self {
125        self.repeat = match (alternate, self.repeat) {
126            (true, _) => Repeat::Alternate,
127            (false, Repeat::Alternate) => Repeat::Forever,
128            (false, repeat) => repeat,
129        };
130        self
131    }
132
133    /// 换缓动曲线
134    pub const fn easing(mut self, easing: Easing) -> Self {
135        self.easing = easing;
136        self
137    }
138
139    /// 匀速
140    pub const fn linear(self) -> Self {
141        self.easing(Easing::Linear)
142    }
143
144    /// 使用 [`Easing::EASE_IN`]
145    pub const fn ease_in(self) -> Self {
146        self.easing(Easing::EASE_IN)
147    }
148
149    /// 使用 [`Easing::EASE_OUT`]
150    pub const fn ease_out(self) -> Self {
151        self.easing(Easing::EASE_OUT)
152    }
153
154    /// 使用 [`Easing::EASE_IN_OUT`]
155    pub const fn ease_in_out(self) -> Self {
156        self.easing(Easing::EASE_IN_OUT)
157    }
158}
159
160/// 时长换成动画每帧求值用的秒(`f32`):按毫秒写的时长和直接写的秒一模一样
161pub(crate) fn seconds(duration: Duration) -> f32 {
162    duration.as_secs_f64() as f32
163}
164
165/// 动画曲线:补间或弹簧,两者都可以 `into()` 成它
166#[derive(Clone, Copy, Debug, PartialEq)]
167#[non_exhaustive]
168pub enum Curve {
169    /// 固定时长的补间
170    Tween(Tween),
171    /// 物理弹簧,没有固定时长
172    Spring(Spring),
173}
174
175impl From<Tween> for Curve {
176    fn from(tween: Tween) -> Self {
177        Self::Tween(tween)
178    }
179}
180
181impl From<Spring> for Curve {
182    fn from(spring: Spring) -> Self {
183        Self::Spring(spring)
184    }
185}
186
187/// 三次贝塞尔一个坐标的多项式系数:B(t) = ((a t + b) t + c) t,端点为 0 和 1
188fn coefficients(p1: f32, p2: f32) -> (f32, f32, f32) {
189    let c = 3.0 * p1;
190    let b = 3.0 * (p2 - p1) - c;
191    (1.0 - c - b, b, c)
192}
193
194/// 求 x(t) = x 的 t(`x` 在 0..1 之间)。牛顿迭代,不收敛时退回二分
195fn solve(x1: f32, x2: f32, x: f32) -> f32 {
196    let (ax, bx, cx) = coefficients(x1, x2);
197    let sample_x = |t: f32| ((ax * t + bx) * t + cx) * t;
198    let slope_x = |t: f32| (3.0 * ax * t + 2.0 * bx) * t + cx;
199
200    let mut t = x;
201    for _ in 0..8 {
202        let error = sample_x(t) - x;
203        if error.abs() < 1e-6 {
204            return t;
205        }
206        let slope = slope_x(t);
207        if slope.abs() < 1e-6 {
208            break;
209        }
210        t -= error / slope;
211    }
212
213    let (mut lo, mut hi) = (0.0, 1.0);
214    t = x;
215    for _ in 0..32 {
216        let value = sample_x(t);
217        if (value - x).abs() < 1e-6 {
218            break;
219        }
220        if value < x {
221            lo = t;
222        } else {
223            hi = t;
224        }
225        t = (lo + hi) * 0.5;
226    }
227    t
228}
229
230/// 求 x(t) = x 的 t,再返回 y(t)
231fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, x: f32) -> f32 {
232    if x <= 0.0 {
233        return 0.0;
234    }
235    if x >= 1.0 {
236        return 1.0;
237    }
238    let t = solve(x1, x2, x);
239    let (ay, by, cy) = coefficients(y1, y2);
240    ((ay * t + by) * t + cy) * t
241}
242
243/// dy/dx 在 x 处的值:y'(t) / x'(t)。x'(t) 接近 0(端点处控制点的 x 是 0 或 1)时用很小的一段差分
244fn cubic_bezier_slope(x1: f32, y1: f32, x2: f32, y2: f32, x: f32) -> f32 {
245    let t = if x <= 0.0 {
246        0.0
247    } else if x >= 1.0 {
248        1.0
249    } else {
250        solve(x1, x2, x)
251    };
252    let (ax, bx, cx) = coefficients(x1, x2);
253    let (ay, by, cy) = coefficients(y1, y2);
254    let dx = (3.0 * ax * t + 2.0 * bx) * t + cx;
255    let dy = (3.0 * ay * t + 2.0 * by) * t + cy;
256    if dx.abs() > 1e-4 {
257        return dy / dx;
258    }
259    const H: f32 = 1e-3;
260    let (a, b) = ((x - H).max(0.0), (x + H).min(1.0));
261    (cubic_bezier(x1, y1, x2, y2, b) - cubic_bezier(x1, y1, x2, y2, a)) / (b - a)
262}