1use crate::{Color, Curve, Point, Size, Transform2D};
18use std::cell::RefCell;
19use std::fmt::Debug;
20use std::rc::Rc;
21
22pub 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 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 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#[derive(Clone, Debug)]
97pub struct PropertyTrack<T: Lerp> {
98 anchor_ms: u64,
100 anchor_value: T,
102 target: T,
104 duration_ms: u64,
106 curve: Curve,
108 animating: bool,
110 presented: T,
112 live: bool,
114}
115
116impl<T: Lerp> PropertyTrack<T> {
117 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 pub fn presented(&self) -> T {
142 self.presented
143 }
144
145 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 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 pub fn is_settled(&self) -> bool {
173 !self.live && self.presented == self.target
174 }
175
176 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 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 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#[derive(Clone, Copy, Debug, PartialEq)]
234pub struct Spring {
235 pub stiffness: f32,
236 pub damping: f32,
237}
238
239impl Spring {
240 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#[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 integrated_steps: u64,
278 animating: bool,
279 presented: T,
280 live: bool,
282}
283
284const SPRING_STEP_S: f32 = 1.0 / 120.0;
286const SPRING_STEP_MS: f64 = SPRING_STEP_S as f64 * 1000.0;
288const SPRING_EPS: f32 = 1e-3;
290
291impl<T: Lerp> SpringTrack<T> {
292 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 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 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 pub fn velocity(&self) -> f32 {
356 self.velocity
357 }
358
359 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 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 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
417pub trait Track<T: Lerp>: Debug {
430 fn presented(&self) -> T;
431 fn target(&self) -> T;
432 fn set_presented(&mut self, value: T, now_ms: u64);
434 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
442pub 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 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 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 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 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 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 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 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 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 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 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 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 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 assert_eq!(track.tick(10_000), 1.0);
718 assert!(!track.is_animating());
719 }
720}