Skip to main content

mgui_core/
property.rs

1//! 属性轨道(独立属性动画一期)—— 呈现值轨道,**不经过 Signal / rebuild**。
2//!
3//! 与 [`crate::animation::AnimationController`] 的分工:
4//! - `AnimationController` 是标量 `0..1` 控制器,靠 `Signal::set → mark_dirty →
5//!   rebuild_signal_dirty` 驱动,会逐帧重建 Widget —— 用于"值参与 build"的场景。
6//! - 本模块的 [`PropertyTrack<T>`] 直接产出**呈现值** `T`,由 `State::tick` 推进、
7//!   `apply_to_ro` 就地写进 RO 字段,合成阶段 `layer_effect()` 每帧实时读。
8//!   全程不 mount/update、不 create_render_object → `FrameStats.rebuilt == false`。
9//!
10//! 设计约束(与 `AnimationController` 一致,避免两套时间语义):
11//! - **锚点模型**:`anchor_ms` 时刻呈现值 = `anchor_value`,之后按曲线向 `target`
12//!   推进。`retarget`/`reverse` 在任意时刻重新锚定到当前呈现值 → 中断/反向连续。
13//! - **无外部时钟**:所有方法接收 `now_ms`,由 `run_frame` 传入(Headless 下即
14//!   `ManualClock`),因此同一 `now_ms` 序列逐位可重放。
15//! - **纯逻辑、零副作用**:不订阅、不标脏、不写 RO;这些由 State 层负责。
16
17use crate::{Color, Curve, Point, Size, Transform2D};
18use std::cell::RefCell;
19use std::fmt::Debug;
20use std::rc::Rc;
21
22/// 可在两个值之间线性插值。
23///
24/// 为属性动画实现:`f32`(opacity/corner)、`Point`(offset)、`Transform2D`(scale)、
25/// `Color`(color)。采用分量线性插值;旋转用最短弧处理,避免跨 ±π 时绕远路。
26/// `Color` 连 alpha 一起插值,保证淡入淡出与颜色变化同源。
27pub trait Lerp: Copy + Debug + PartialEq {
28    fn lerp(a: Self, b: Self, t: f32) -> Self;
29}
30
31impl Lerp for f32 {
32    #[inline]
33    fn lerp(a: Self, b: Self, t: f32) -> Self {
34        a + (b - a) * t
35    }
36}
37
38impl Lerp for Point {
39    #[inline]
40    fn lerp(a: Self, b: Self, t: f32) -> Self {
41        Point::new(f32::lerp(a.x, b.x, t), f32::lerp(a.y, b.y, t))
42    }
43}
44
45impl Lerp for Size {
46    #[inline]
47    fn lerp(a: Self, b: Self, t: f32) -> Self {
48        Size::new(f32::lerp(a.width, b.width, t), f32::lerp(a.height, b.height, t))
49    }
50}
51
52impl Lerp for Color {
53    #[inline]
54    fn lerp(a: Self, b: Self, t: f32) -> Self {
55        // sRGB 编码空间的分量线性插值,alpha 同权 —— 与 PaintCommand 直接消费的
56        // Color 语义一致(paint 不做事后 gamma 转换),淡入淡出与颜色过渡同源。
57        Color::rgba(f32::lerp(a.r, b.r, t), f32::lerp(a.g, b.g, t), f32::lerp(a.b, b.b, t), f32::lerp(a.a, b.a, t))
58    }
59}
60
61impl Lerp for Transform2D {
62    fn lerp(a: Self, b: Self, t: f32) -> Self {
63        // 旋转取最短弧:把差值折叠到 (-π, π],避免 170° → -170° 走 340° 远路。
64        let mut d = b.rotation - a.rotation;
65        while d > std::f32::consts::PI {
66            d -= std::f32::consts::TAU;
67        }
68        while d <= -std::f32::consts::PI {
69            d += std::f32::consts::TAU;
70        }
71        Transform2D {
72            rotation: a.rotation + d * t,
73            scale_x: f32::lerp(a.scale_x, b.scale_x, t),
74            scale_y: f32::lerp(a.scale_y, b.scale_y, t),
75            translate: Point::lerp(a.translate, b.translate, t),
76        }
77    }
78}
79
80/// 单属性的呈现值轨道。
81///
82/// 典型用法(State 内):
83/// ```ignore
84/// struct AnimatedOpacityState {
85///     track: PropertyTrack<f32>,
86///     widget: WidgetNode,
87/// }
88/// fn tick(&mut self, now_ms: u64) {
89///     self.track.tick(now_ms); // 推进锚点,呈现值存在 track 里
90/// }
91/// fn is_animating(&self) -> bool { self.track.is_animating() }
92/// fn apply_to_ro(&mut self, ro: &mut dyn RenderObject) -> StateApply {
93///     ro.apply_state(self.as_any_mut())
94/// }
95/// ```
96#[derive(Clone, Debug)]
97pub struct PropertyTrack<T: Lerp> {
98    /// 锚点时刻(ms):此刻呈现值 = `anchor_value`
99    anchor_ms: u64,
100    /// 锚点呈现值
101    anchor_value: T,
102    /// 目标呈现值
103    target: T,
104    /// 动画时长(ms)
105    duration_ms: u64,
106    /// 缓动曲线
107    curve: Curve,
108    /// 是否正在推进
109    animating: bool,
110    /// 缓存的最新呈现值(供无时钟查询与 retarget 起点)
111    presented: T,
112    /// `live_only` 期间为 true:呈现值由 LiveSession 临时接管,逻辑 target 保持不变。
113    live: bool,
114}
115
116impl<T: Lerp> PropertyTrack<T> {
117    /// 以 `initial` 为初始呈现值创建静止轨道。
118    pub fn new(initial: T, duration_ms: u64) -> Self {
119        Self {
120            anchor_ms: 0,
121            anchor_value: initial,
122            target: initial,
123            duration_ms: duration_ms.max(1),
124            curve: Curve::default(),
125            animating: false,
126            presented: initial,
127            live: false,
128        }
129    }
130
131    pub fn with_curve(mut self, curve: Curve) -> Self {
132        self.curve = curve;
133        self
134    }
135
136    pub fn target(&self) -> T {
137        self.target
138    }
139
140    /// 当前呈现值(无副作用查询,不推进)。
141    pub fn presented(&self) -> T {
142        self.presented
143    }
144
145    /// `live_only` 专用:把**呈现值**就地钉到 `value`,逻辑 `target` 保持不变。
146    ///
147    /// `is_animating()` 在 live 期间为 true,驱动 State 就地写 RO;但 `tick` 不推进、
148    /// 不碰 Signal、不 mount/update。终态由 `LiveSession` 调 `settle_live` 统一结算。
149    pub fn set_presented(&mut self, value: T, now_ms: u64) {
150        self.anchor_ms = now_ms;
151        self.anchor_value = value;
152        self.presented = value;
153        self.animating = false;
154        self.live = true;
155    }
156
157    /// 结束 live 接管,把终值同时写回呈现位与逻辑目标。
158    pub fn settle_live(&mut self, value: T, now_ms: u64) {
159        self.live = false;
160        self.anchor_ms = now_ms;
161        self.anchor_value = value;
162        self.target = value;
163        self.presented = value;
164        self.animating = false;
165    }
166
167    pub fn is_animating(&self) -> bool {
168        self.live || self.animating
169    }
170
171    /// 是否已到达目标(呈现值与目标逐分量相等)。
172    pub fn is_settled(&self) -> bool {
173        !self.live && self.presented == self.target
174    }
175
176    /// 从当前呈现值起,在 `now_ms` 时刻开始向 `target` 推进。
177    ///
178    /// 关键:**先按 now_ms 结算当前呈现值,再以此为新锚点** —— 这就是中断/反向
179    /// 连续的来源:中途改目标不会出现跳变。
180    pub fn retarget(&mut self, target: T, now_ms: u64) {
181        self.live = false;
182        let current = self.value_at(now_ms);
183        self.anchor_value = current;
184        self.anchor_ms = now_ms;
185        self.target = target;
186        self.presented = current;
187        self.animating = current != target;
188    }
189
190    /// 推进到 `now_ms`,返回结算后的呈现值。
191    ///
192    /// 必须在 `State::tick` 里每帧调用一次;只改内部锚点与缓存,不产生副作用。
193    /// live 期间呈现值由手势持有,tick 原样返回。
194    pub fn tick(&mut self, now_ms: u64) -> T {
195        if self.live {
196            return self.presented;
197        }
198        self.presented = self.value_at(now_ms);
199        if self.presented == self.target {
200            self.animating = false;
201        }
202        self.presented
203    }
204
205    /// 无状态查询 `now_ms` 时刻的呈现值(不推进、不改状态)。
206    ///
207    /// 供 hit_test、语义快照等"立即读当前位置"的路径使用,与 paint 同源。
208    pub fn value_at(&self, now_ms: u64) -> T {
209        if self.live || !self.animating {
210            return self.presented;
211        }
212        let elapsed = now_ms.saturating_sub(self.anchor_ms) as f32;
213        let linear = (elapsed / self.duration_ms as f32).clamp(0.0, 1.0);
214        let t = self.curve.transform(linear);
215        if t >= 1.0 {
216            self.target
217        } else {
218            T::lerp(self.anchor_value, self.target, t)
219        }
220    }
221}
222
223// =====================================================================
224// Spring retarget —— 带速度的弹簧轨道(路线图 9.3 "随后再扩 spring retarget")
225// =====================================================================
226
227/// 弹簧参数:刚度与阻尼。
228///
229/// - `stiffness`(k)越大,回目标越快;
230/// - `damping`(c)越小,过冲/回弹越明显。
231///   `c²` 与 `4k`:`c² < 4k` 欠阻尼(过冲),`= 4k` 临界(最快无过冲),
232///   `> 4k` 过阻尼(缓慢无过冲)。
233#[derive(Clone, Copy, Debug, PartialEq)]
234pub struct Spring {
235    pub stiffness: f32,
236    pub damping: f32,
237}
238
239impl Spring {
240    /// 欠阻尼默认配置:刚度 180、阻尼 18 → `c²=324 < 4k=720`,可见过冲回弹。
241    pub const DEFAULT_STIFFNESS: f32 = 180.0;
242    pub const DEFAULT_DAMPING: f32 = 18.0;
243
244    pub fn new(stiffness: f32, damping: f32) -> Self {
245        Self { stiffness: stiffness.max(0.0), damping: damping.max(0.0) }
246    }
247}
248
249impl Default for Spring {
250    fn default() -> Self {
251        Self::new(Self::DEFAULT_STIFFNESS, Self::DEFAULT_DAMPING)
252    }
253}
254
255/// 弹簧属性轨道:保存当前呈现值、**速度**、目标值,用弹簧物理推进。
256///
257/// 与 [`PropertyTrack`](时长 + 曲线、到点即停)互补:弹簧在**进度空间**维护
258/// `position`(0=起点、1=目标,可越过 1 再回弹)与 `velocity`(进度速度,1/s),
259/// 呈现值 = `T::lerp(from, to, position)`。这样任意 `Lerp` 类型(含旋转走
260/// 最短弧的 `Transform2D`)都能用同一套弹簧,不必给每种类型定义向量空间。
261///
262/// **中断连续**:`retarget` 先结算当前呈现值与速度,以当前值为新 `from`、
263/// **保留速度**,再朝新目标推进 —— 中途改向不会瞬间归零或跳变。
264///
265/// **确定性**:进度用固定子步长 `SPRING_STEP_S` 半隐式欧拉积分,积分步数只由
266/// `now_ms` 决定,与帧率/调用间隔无关;同一 `now_ms` 序列逐位可重放。
267#[derive(Clone, Debug)]
268pub struct SpringTrack<T: Lerp> {
269    from: T,
270    to: T,
271    position: f32,
272    velocity: f32,
273    spring: Spring,
274    anchor_ms: u64,
275    /// 从 `anchor_ms` 起已积分的**整步数**。积分只认整步、不认残步,
276    /// 因此逐帧 tick 与跳帧 tick 推进的是同一串步长,结果与帧率严格无关。
277    integrated_steps: u64,
278    animating: bool,
279    presented: T,
280    /// `live_only` 期间为 true:`to` 仍是逻辑目标,presented 由手势临时接管。
281    live: bool,
282}
283
284/// 固定积分步长(秒)。选 1/120 让 60fps 下每帧恰好两步,低帧率也按同步长补步。
285const SPRING_STEP_S: f32 = 1.0 / 120.0;
286/// 固定步长的毫秒表示,用于把 `now_ms` 量化到整步编号(避免浮点残步)。
287const SPRING_STEP_MS: f64 = SPRING_STEP_S as f64 * 1000.0;
288/// 收敛判定:位置与速度同时进入容差才吸附到目标,避免"位置到了但还在冲"。
289const SPRING_EPS: f32 = 1e-3;
290
291impl<T: Lerp> SpringTrack<T> {
292    /// 以 `initial` 为初始呈现值创建静止轨道。
293    pub fn new(initial: T, spring: Spring) -> Self {
294        Self {
295            from: initial,
296            to: initial,
297            position: 0.0,
298            velocity: 0.0,
299            spring,
300            anchor_ms: 0,
301            integrated_steps: 0,
302            animating: false,
303            presented: initial,
304            live: false,
305        }
306    }
307
308    pub fn with_spring(mut self, spring: Spring) -> Self {
309        self.spring = spring;
310        self
311    }
312
313    pub fn presented(&self) -> T {
314        self.presented
315    }
316
317    /// `live_only` 专用:清速度/进度,把呈现值就地钉到 `value`,逻辑 `to` 不变。
318    pub fn set_presented(&mut self, value: T, now_ms: u64) {
319        self.from = value;
320        self.position = 0.0;
321        self.velocity = 0.0;
322        self.anchor_ms = now_ms;
323        self.integrated_steps = 0;
324        self.animating = false;
325        self.presented = value;
326        self.live = true;
327    }
328
329    /// 结束 live 接管,把终值同时写回呈现位与逻辑目标。
330    pub fn settle_live(&mut self, value: T, now_ms: u64) {
331        self.live = false;
332        self.from = value;
333        self.to = value;
334        self.position = 0.0;
335        self.velocity = 0.0;
336        self.anchor_ms = now_ms;
337        self.integrated_steps = 0;
338        self.animating = false;
339        self.presented = value;
340    }
341
342    pub fn target(&self) -> T {
343        self.to
344    }
345
346    pub fn is_animating(&self) -> bool {
347        self.live || self.animating
348    }
349
350    pub fn is_settled(&self) -> bool {
351        !self.live && !self.animating && self.presented == self.to
352    }
353
354    /// 当前进度速度(1/s);供观测"retarget 保留速度"。
355    pub fn velocity(&self) -> f32 {
356        self.velocity
357    }
358
359    /// 从当前呈现值起,在 `now_ms` 时刻重定向到 `target`,**保留速度**。
360    ///
361    /// 先按 now_ms 结算当前呈现值与速度,再以当前值为新 `from` —— 与
362    /// [`PropertyTrack::retarget`] 同为中断连续的来源,只是多带一份速度。
363    pub fn retarget(&mut self, target: T, now_ms: u64) {
364        self.live = false;
365        self.advance(now_ms);
366        self.from = self.presented;
367        self.to = target;
368        self.position = 0.0;
369        self.anchor_ms = now_ms;
370        self.integrated_steps = 0;
371        self.animating = self.from != self.to || self.velocity.abs() > SPRING_EPS;
372        if !self.animating {
373            self.presented = self.to;
374        }
375    }
376
377    /// 推进到 `now_ms`,返回结算后的呈现值。在 `State::tick` 里每帧调用一次。
378    pub fn tick(&mut self, now_ms: u64) -> T {
379        if self.live {
380            return self.presented;
381        }
382        self.advance(now_ms);
383        self.presented
384    }
385
386    /// 半隐式欧拉:先按当前位移/速度算加速度,再更新速度,最后用新速度更新位移。
387    ///
388    /// **绝对步编号**:目标步数 = `floor((now_ms - anchor_ms) / STEP_MS)`,只补
389    /// `target - integrated_steps` 个整步,每步严格 `SPRING_STEP_S`。
390    /// `anchor_ms` 只在 `retarget` 时重置,`advance` 永不改写 —— 于是不足一步的
391    /// 时间余数留在总 elapsed 里累积:逐帧 30×10ms 与跳帧 1×300ms 得到同一串
392    /// 整步,结果逐位相同(回放确定、与调用帧率无关)。
393    fn advance(&mut self, now_ms: u64) {
394        if self.live || !self.animating {
395            return;
396        }
397        let elapsed_ms = now_ms.saturating_sub(self.anchor_ms) as f64;
398        let target_steps = (elapsed_ms / SPRING_STEP_MS) as u64;
399        while self.integrated_steps < target_steps {
400            let accel = -self.spring.stiffness * (self.position - 1.0) - self.spring.damping * self.velocity;
401            self.velocity += accel * SPRING_STEP_S;
402            self.position += self.velocity * SPRING_STEP_S;
403            self.integrated_steps += 1;
404        }
405
406        if (self.position - 1.0).abs() < SPRING_EPS && self.velocity.abs() < SPRING_EPS {
407            self.position = 1.0;
408            self.velocity = 0.0;
409            self.animating = false;
410            self.presented = self.to;
411        } else {
412            self.presented = T::lerp(self.from, self.to, self.position);
413        }
414    }
415}
416
417// =====================================================================
418// Track —— 两种轨道的统一抽象(框架体系:同一套 widget 吃任意轨道实现)
419// =====================================================================
420
421/// 属性轨道的统一契约。
422///
423/// [`PropertyTrack`](时长 + 曲线、到点即停)与 [`SpringTrack`](带速度、可过冲)
424/// 都实现它,widget/state 只依赖句柄 [`SharedTrack<T>`],不再为每种轨道复制
425/// 一套 `AnimatedXxxWidget` —— 消灭"轨道类型 × 属性"的 N×M 样板。
426///
427/// `value_at`(无状态查询未来值)刻意不进 trait:只有曲线轨道有,弹簧按固定
428/// 步积分、无法无状态预知;需要"立即读当前值"的路径统一走 `presented`。
429pub trait Track<T: Lerp>: Debug {
430    fn presented(&self) -> T;
431    fn target(&self) -> T;
432    /// `live_only` 呈现位直写;不产生响应式副作用、不改逻辑目标。
433    fn set_presented(&mut self, value: T, now_ms: u64);
434    /// 结束 live 接管并把终值结算为新的逻辑目标。
435    fn settle_live(&mut self, value: T, now_ms: u64);
436    fn tick(&mut self, now_ms: u64) -> T;
437    fn retarget(&mut self, target: T, now_ms: u64);
438    fn is_animating(&self) -> bool;
439    fn is_settled(&self) -> bool;
440}
441
442/// 统一轨道句柄:widget/state 只持有这个类型,底层是曲线轨道还是弹簧轨道
443/// 由工厂函数决定,调用方无感。`Rc<RefCell<...>>` 与旧的共享句柄语义一致 —
444/// widget 构造时创建、外部持有 clone 以在运行时 retarget。
445pub type SharedTrack<T> = Rc<RefCell<dyn Track<T>>>;
446
447impl<T: Lerp> Track<T> for PropertyTrack<T> {
448    fn presented(&self) -> T {
449        PropertyTrack::presented(self)
450    }
451    fn target(&self) -> T {
452        PropertyTrack::target(self)
453    }
454    fn set_presented(&mut self, value: T, now_ms: u64) {
455        PropertyTrack::set_presented(self, value, now_ms)
456    }
457    fn settle_live(&mut self, value: T, now_ms: u64) {
458        PropertyTrack::settle_live(self, value, now_ms)
459    }
460    fn tick(&mut self, now_ms: u64) -> T {
461        PropertyTrack::tick(self, now_ms)
462    }
463    fn retarget(&mut self, target: T, now_ms: u64) {
464        PropertyTrack::retarget(self, target, now_ms)
465    }
466    fn is_animating(&self) -> bool {
467        PropertyTrack::is_animating(self)
468    }
469    fn is_settled(&self) -> bool {
470        PropertyTrack::is_settled(self)
471    }
472}
473
474impl<T: Lerp> Track<T> for SpringTrack<T> {
475    fn presented(&self) -> T {
476        SpringTrack::presented(self)
477    }
478    fn target(&self) -> T {
479        SpringTrack::target(self)
480    }
481    fn set_presented(&mut self, value: T, now_ms: u64) {
482        SpringTrack::set_presented(self, value, now_ms)
483    }
484    fn settle_live(&mut self, value: T, now_ms: u64) {
485        SpringTrack::settle_live(self, value, now_ms)
486    }
487    fn tick(&mut self, now_ms: u64) -> T {
488        SpringTrack::tick(self, now_ms)
489    }
490    fn retarget(&mut self, target: T, now_ms: u64) {
491        SpringTrack::retarget(self, target, now_ms)
492    }
493    fn is_animating(&self) -> bool {
494        SpringTrack::is_animating(self)
495    }
496    fn is_settled(&self) -> bool {
497        SpringTrack::is_settled(self)
498    }
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504
505    /// 采样 spring 在 now_ms 序列上的 presented 值。
506    fn sample(track: &mut SpringTrack<f32>, steps: &[u64]) -> Vec<f32> {
507        steps.iter().map(|&ms| track.tick(ms)).collect()
508    }
509
510    #[test]
511    fn spring_underdamped_overshoots_and_settles() {
512        // 欠阻尼:c²=18²=324 < 4k=4×180=720 → 应越过目标再回弹。
513        let mut track = SpringTrack::new(0.0f32, Spring::new(180.0, 18.0));
514        track.retarget(1.0, 0);
515        let values = sample(&mut track, &(0..=1500).step_by(10).collect::<Vec<_>>());
516        let peak = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
517        assert!(peak > 1.02, "欠阻尼应过冲,实际峰值 {peak}");
518        assert!((values.last().copied().unwrap() - 1.0).abs() < 1e-3, "最终收敛到目标");
519        assert!(track.is_settled() && !track.is_animating(), "收敛后必须停");
520        assert_eq!(track.velocity(), 0.0, "收敛后速度归零");
521    }
522
523    #[test]
524    fn spring_critically_damped_has_no_overshoot() {
525        // 临界阻尼:c = 2√k = 2√225 = 30 → c²=900=4k,不应过冲。
526        let mut track = SpringTrack::new(0.0f32, Spring::new(225.0, 30.0));
527        track.retarget(1.0, 0);
528        let values = sample(&mut track, &(0..=1500).step_by(10).collect::<Vec<_>>());
529        let peak = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
530        assert!(peak <= 1.0 + 1e-3, "临界阻尼不得过冲,实际峰值 {peak}");
531        assert!((values.last().copied().unwrap() - 1.0).abs() < 1e-3);
532    }
533
534    #[test]
535    fn spring_retarget_preserves_velocity_and_start_value() {
536        let mut track = SpringTrack::new(0.0f32, Spring::default());
537        track.retarget(1.0, 0);
538        sample(&mut track, &[100, 200, 300]);
539        let v_before = track.velocity();
540        let value_before = track.presented();
541        assert!(v_before.abs() > 1e-4, "中途应有非零速度");
542
543        // 在 t=300 反向:起点=当前呈现值,速度保留。
544        track.retarget(0.0, 300);
545        assert!((track.presented() - value_before).abs() < 1e-6, "retarget 起点不得跳变");
546        assert!((track.velocity() - v_before).abs() < 1e-6, "retarget 必须保留速度(带惯性的反向)");
547        assert!(track.is_animating(), "带速度反向后仍在动");
548
549        // 继续走会先凭惯性越过起点,再被弹簧拉回 0 —— 最终收敛。
550        let values = sample(&mut track, &(310..=2000).step_by(10).collect::<Vec<_>>());
551        assert!((values.last().copied().unwrap() - 0.0).abs() < 1e-3, "最终收敛到新目标 0");
552    }
553
554    #[test]
555    fn spring_replay_is_bit_identical() {
556        let script: Vec<u64> = (0..=200).map(|i| i * 8).collect();
557        let run = || {
558            let mut track = SpringTrack::new(0.0f32, Spring::new(180.0, 18.0));
559            track.retarget(1.0, 0);
560            script.iter().map(|&ms| track.tick(ms).to_bits()).collect::<Vec<_>>()
561        };
562        assert_eq!(run(), run(), "同一 now_ms 序列两次弹簧回放必须逐位相等");
563    }
564
565    #[test]
566    fn spring_frame_rate_independent_at_same_timestamps() {
567        // 细粒度逐帧 tick vs 一次性跳到终点:固定子步长从锚点重算,终点必须相同。
568        let mut fine = SpringTrack::new(0.0f32, Spring::new(180.0, 18.0));
569        fine.retarget(1.0, 0);
570        for ms in (10..=300).step_by(10) {
571            fine.tick(ms);
572        }
573        let fine_end = fine.presented();
574        let fine_vel = fine.velocity();
575
576        let mut coarse = SpringTrack::new(0.0f32, Spring::new(180.0, 18.0));
577        coarse.retarget(1.0, 0);
578        let coarse_end = coarse.tick(300);
579
580        assert!((fine_end - coarse_end).abs() < 1e-6, "逐帧 {fine_end} vs 跳帧 {coarse_end}");
581        assert!((fine_vel - coarse.velocity()).abs() < 1e-6, "速度也应与调用帧率无关");
582    }
583
584    #[test]
585    fn spring_works_for_point_and_color() {
586        // 泛型:Point 分量各自弹簧。
587        let mut pt = SpringTrack::new(Point::new(0.0, 10.0), Spring::new(180.0, 18.0));
588        pt.retarget(Point::new(100.0, -10.0), 0);
589        let values = sample_points(&mut pt, &(0..=1500).step_by(10).collect::<Vec<_>>());
590        let peak_x = values.iter().map(|p| p.x).fold(f32::NEG_INFINITY, f32::max);
591        assert!(peak_x > 102.0, "Point 也应过冲: {peak_x}");
592        assert!((values.last().unwrap().x - 100.0).abs() < 1e-3);
593        assert!((values.last().unwrap().y - (-10.0)).abs() < 1e-3);
594
595        // Color 含 alpha 一起弹簧,过冲后收敛。
596        let mut color = SpringTrack::new(Color::BLACK, Spring::new(180.0, 18.0));
597        color.retarget(Color::WHITE, 0);
598        let c = color.tick(1500);
599        assert!((c.r - 1.0).abs() < 1e-3 && (c.a - 1.0).abs() < 1e-3, "Color 弹簧应收敛到 WHITE");
600    }
601
602    fn sample_points(track: &mut SpringTrack<Point>, steps: &[u64]) -> Vec<Point> {
603        steps.iter().map(|&ms| track.tick(ms)).collect()
604    }
605
606    #[test]
607    fn f32_track_advances_and_settles() {
608        let mut track = PropertyTrack::new(0.0f32, 1000).with_curve(Curve::Linear);
609        track.retarget(1.0, 0);
610        assert!(track.is_animating());
611        assert_eq!(track.tick(0), 0.0);
612        assert!((track.tick(500) - 0.5).abs() < 1e-6);
613        assert_eq!(track.tick(1000), 1.0);
614        assert!(!track.is_animating(), "到目标后必须停,驱动 request_redraw 收敛");
615        assert!(track.is_settled());
616    }
617
618    #[test]
619    fn retarget_midflight_is_continuous() {
620        // 0 → 1,跑到 0.5 时改目标为 0.4:新段必须从 0.5 起,不能跳回 0.0。
621        let mut track = PropertyTrack::new(0.0f32, 1000).with_curve(Curve::Linear);
622        track.retarget(1.0, 0);
623        let at_500 = track.value_at(500);
624        assert!((at_500 - 0.5).abs() < 1e-6);
625        track.retarget(0.4, 500);
626        assert!((track.presented() - at_500).abs() < 1e-6, "retarget 起点必须是当前呈现值");
627        // 新段 500→1500 从 0.5 走向 0.4;1000ms 时走到一半 = 0.45
628        assert!((track.value_at(1000) - 0.45).abs() < 1e-6);
629        assert_eq!(track.value_at(1500), 0.4);
630    }
631
632    #[test]
633    fn reverse_midflight_has_no_jump() {
634        let mut track = PropertyTrack::new(0.0f32, 1000).with_curve(Curve::Linear);
635        track.retarget(1.0, 0);
636        let at_300 = track.value_at(300);
637        // 反向 = 把目标设回起点,从当前值继续
638        track.retarget(0.0, 300);
639        let immediately = track.value_at(300);
640        assert!((immediately - at_300).abs() < 1e-6, "反向瞬间不得跳变");
641        let at_600 = track.value_at(600);
642        assert!(at_600 < at_300, "反向后值必须持续下降");
643        assert_eq!(track.value_at(1300), 0.0);
644    }
645
646    #[test]
647    fn deterministic_replay_is_bit_identical() {
648        let script: Vec<u64> = (0..=40).map(|i| i * 25).collect();
649        let run = || {
650            let mut track = PropertyTrack::new(0.0f32, 1000).with_curve(Curve::EaseInOut);
651            track.retarget(1.0, 0);
652            script.iter().map(|&ms| track.tick(ms).to_bits()).collect::<Vec<_>>()
653        };
654        assert_eq!(run(), run(), "同一 now_ms 序列两次回放必须逐位相等");
655    }
656
657    #[test]
658    fn color_lerp_interpolates_all_channels_including_alpha() {
659        let mid = <Color as Lerp>::lerp(Color::rgba(0.0, 0.0, 0.0, 0.0), Color::rgba(1.0, 0.5, 0.25, 1.0), 0.5);
660        assert!((mid.r - 0.5).abs() < 1e-6);
661        assert!((mid.g - 0.25).abs() < 1e-6);
662        assert!((mid.b - 0.125).abs() < 1e-6);
663        assert!((mid.a - 0.5).abs() < 1e-6, "alpha 必须一起插值,否则淡入淡出会跳变");
664
665        let mut track = PropertyTrack::new(Color::BLACK, 1000).with_curve(Curve::Linear);
666        track.retarget(Color::WHITE, 0);
667        assert_eq!(track.tick(500), Color::rgba(0.5, 0.5, 0.5, 1.0));
668        assert_eq!(track.tick(1000), Color::WHITE);
669        assert!(!track.is_animating());
670    }
671
672    #[test]
673    fn size_lerp_interpolates_width_and_height() {
674        let mid = <Size as Lerp>::lerp(Size::new(20.0, 40.0), Size::new(60.0, 100.0), 0.5);
675        assert!((mid.width - 40.0).abs() < 1e-6);
676        assert!((mid.height - 70.0).abs() < 1e-6);
677
678        let mut track = PropertyTrack::new(Size::new(20.0, 20.0), 1000).with_curve(Curve::Linear);
679        track.retarget(Size::new(100.0, 60.0), 0);
680        assert_eq!(track.tick(500), Size::new(60.0, 40.0));
681        assert_eq!(track.tick(1000), Size::new(100.0, 60.0));
682        assert!(!track.is_animating());
683    }
684
685    #[test]
686    fn point_and_transform_lerp() {
687        let p = <Point as Lerp>::lerp(Point::new(0.0, 10.0), Point::new(100.0, 20.0), 0.25);
688        assert!((p.x - 25.0).abs() < 1e-6 && (p.y - 12.5).abs() < 1e-6);
689
690        let a = Transform2D::rotate(3.0);
691        let b = Transform2D::rotate(-3.0);
692        let mid = <Transform2D as Lerp>::lerp(a, b, 0.5);
693        // 3 → -3 最短弧是 +0.283...,中点 ≈ 3.14159(π),不是 0(绕远路)
694        assert!(mid.rotation.abs() > 3.0, "旋转插值必须走最短弧,实际 {rotation}", rotation = mid.rotation);
695    }
696
697    #[test]
698    fn point_track_retarget() {
699        let mut track = PropertyTrack::new(Point::ZERO, 1000).with_curve(Curve::Linear);
700        track.retarget(Point::new(100.0, 50.0), 0);
701        let mid = track.tick(500);
702        assert!((mid.x - 50.0).abs() < 1e-6 && (mid.y - 25.0).abs() < 1e-6);
703        track.retarget(Point::new(0.0, 50.0), 500);
704        let after = track.value_at(1000);
705        assert!((after.x - 25.0).abs() < 1e-6, "x 从 50 反向到 0,中点 25");
706        assert!(
707            (after.y - 37.5).abs() < 1e-6,
708            "y 从退靶时的 25 继续朝新目标 50 走,中点 37.5(退靶重启整段,不是保持旧值)",
709        );
710    }
711
712    #[test]
713    fn settle_before_duration_does_not_overshoot() {
714        let mut track = PropertyTrack::new(0.0f32, 100).with_curve(Curve::Linear);
715        track.retarget(1.0, 0);
716        // 远超时长:必须钳制在 target,不 overshoot
717        assert_eq!(track.tick(10_000), 1.0);
718        assert!(!track.is_animating());
719    }
720}