1use std::any::Any;
29use std::cell::{Cell, RefCell};
30use std::future::Future;
31use std::ops::ControlFlow;
32use std::pin::Pin;
33use std::rc::Rc;
34use std::task::{Context, Poll, Waker};
35
36use day_reactive::Signal;
37use day_spec::{AnimSample, AnimSpec, Curve};
38
39use crate::frame::{FrameClock, FrameHandle};
40use crate::tween::Lerp;
41
42use std::f64::consts::PI;
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum Ease {
47 In,
49 Out,
51 InOut,
53}
54
55#[derive(Clone, Copy, Debug, PartialEq)]
58pub enum Easing {
59 Linear,
61 Bezier(f64, f64, f64, f64),
63 Power(Ease, f64),
65 Sine(Ease),
67 Circle(Ease),
69 Exponential(Ease),
71 Back(Ease, f64),
74 ElasticOut(f64),
76 BounceOut,
78}
79
80impl Easing {
81 pub const EASE: Easing = Easing::Bezier(0.25, 0.1, 0.25, 1.0);
83 pub const EASE_IN_OUT: Easing = Easing::Bezier(0.42, 0.0, 0.58, 1.0);
85
86 #[must_use]
88 pub fn value(self, t: f64) -> f64 {
89 let t = t.clamp(0.0, 1.0);
90 match self {
91 Easing::Linear => t,
92 Easing::Bezier(x1, y1, x2, y2) => bezier(t, x1, y1, x2, y2),
93 Easing::Power(ease, power) => shaped(ease, t, |t| t.powf(power)),
94 Easing::Sine(ease) => shaped(ease, t, |t| 1.0 - (t * PI / 2.0).cos()),
95 Easing::Circle(ease) => shaped(ease, t, |t| 1.0 - (1.0 - t * t).max(0.0).sqrt()),
96 Easing::Exponential(ease) => shaped(ease, t, |t| {
97 if t <= 0.0 {
98 0.0
99 } else {
100 2f64.powf(10.0 * (t - 1.0))
101 }
102 }),
103 Easing::Back(ease, overshoot) => {
104 shaped(ease, t, |t| t * t * ((overshoot + 1.0) * t - overshoot))
105 }
106 Easing::ElasticOut(bounciness) => {
107 if t <= 0.0 || t >= 1.0 {
108 t
109 } else {
110 let p = bounciness.max(0.01) * PI;
111 1.0 - (t * PI / 2.0).cos().powi(3) * (t * p).cos()
112 }
113 }
114 Easing::BounceOut => bounce(t),
115 }
116 }
117
118 #[must_use]
120 pub fn samples(self, count: usize) -> Vec<f64> {
121 let last = count.saturating_sub(1).max(1) as f64;
122 (0..count).map(|i| self.value(i as f64 / last)).collect()
123 }
124}
125
126fn shaped(ease: Ease, t: f64, ease_in: impl Fn(f64) -> f64) -> f64 {
128 match ease {
129 Ease::In => ease_in(t),
130 Ease::Out => 1.0 - ease_in(1.0 - t),
131 Ease::InOut => {
132 if t < 0.5 {
133 ease_in(t * 2.0) / 2.0
134 } else {
135 1.0 - ease_in((1.0 - t) * 2.0) / 2.0
136 }
137 }
138 }
139}
140
141fn bounce(t: f64) -> f64 {
142 const N: f64 = 7.5625;
143 const D: f64 = 2.75;
144 if t < 1.0 / D {
145 N * t * t
146 } else if t < 2.0 / D {
147 let t = t - 1.5 / D;
148 N * t * t + 0.75
149 } else if t < 2.5 / D {
150 let t = t - 2.25 / D;
151 N * t * t + 0.9375
152 } else {
153 let t = t - 2.625 / D;
154 N * t * t + 0.984_375
155 }
156}
157
158fn bezier(x: f64, x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
161 let axis = |t: f64, a: f64, b: f64| {
162 let u = 1.0 - t;
163 3.0 * u * u * t * a + 3.0 * u * t * t * b + t * t * t
164 };
165 let slope = |t: f64, a: f64, b: f64| {
166 let u = 1.0 - t;
167 3.0 * u * u * a + 6.0 * u * t * (b - a) + 3.0 * t * t * (1.0 - b)
168 };
169 let mut t = x;
170 for _ in 0..8 {
171 let error = axis(t, x1, x2) - x;
172 if error.abs() < 1e-6 {
173 return axis(t, y1, y2);
174 }
175 let d = slope(t, x1, x2);
176 if d.abs() < 1e-6 {
177 break;
178 }
179 t = (t - error / d).clamp(0.0, 1.0);
180 }
181 let (mut lo, mut hi) = (0.0, 1.0);
182 t = x;
183 for _ in 0..24 {
184 let at = axis(t, x1, x2);
185 if (at - x).abs() < 1e-6 {
186 break;
187 }
188 if at < x {
189 lo = t;
190 } else {
191 hi = t;
192 }
193 t = f64::midpoint(lo, hi);
194 }
195 axis(t, y1, y2)
196}
197
198#[derive(Clone, Copy, Debug, PartialEq)]
200pub struct Spring {
201 pub stiffness: f64,
203 pub damping: f64,
205 pub mass: f64,
207}
208
209impl Default for Spring {
210 fn default() -> Self {
212 Spring::new(170.0, 26.0)
213 }
214}
215
216impl Spring {
217 #[must_use]
219 pub const fn new(stiffness: f64, damping: f64) -> Self {
220 Spring {
221 stiffness,
222 damping,
223 mass: 1.0,
224 }
225 }
226
227 #[must_use]
229 pub const fn mass(mut self, mass: f64) -> Self {
230 self.mass = mass;
231 self
232 }
233
234 #[must_use]
238 pub fn from_response(response: f64, ratio: f64) -> Self {
239 let (stiffness, damping) = Curve::Spring {
240 response,
241 damping: ratio,
242 }
243 .spring_constants()
244 .unwrap_or((170.0, 26.0));
245 Spring::new(stiffness, damping)
246 }
247
248 #[must_use]
252 pub fn curve(self) -> Curve {
253 let mass = self.mass.max(1e-6);
254 let omega0 = (self.stiffness.max(0.0) / mass).sqrt().max(1e-6);
255 Curve::Spring {
256 response: std::f64::consts::TAU / omega0,
257 damping: self.damping / (2.0 * mass * omega0),
258 }
259 }
260
261 pub fn step(self, state: &mut SpringState, target: f64, dt: f64) {
264 let mut left = dt.clamp(0.0, 0.25);
265 let mass = self.mass.max(1e-6);
266 while left > 0.0 {
267 let h = left.min(0.001);
268 let force = -self.stiffness * (state.value - target) - self.damping * state.velocity;
269 state.velocity += force / mass * h;
270 state.value += state.velocity * h;
271 left -= h;
272 }
273 }
274
275 #[must_use]
278 pub fn settled(self, state: SpringState, target: f64) -> bool {
279 (state.value - target).abs() < 0.01 && state.velocity.abs() < 0.01
280 }
281
282 #[must_use]
285 pub fn response(self, seconds: f64, count: usize) -> Vec<f64> {
286 let mut state = SpringState::default();
287 let dt = seconds / count.saturating_sub(1).max(1) as f64;
288 (0..count)
289 .map(|i| {
290 if i > 0 {
291 self.step(&mut state, 1.0, dt);
292 }
293 state.value
294 })
295 .collect()
296 }
297}
298
299#[derive(Clone, Copy, Debug, Default, PartialEq)]
301pub struct SpringState {
302 pub value: f64,
304 pub velocity: f64,
306}
307
308impl SpringState {
309 #[must_use]
311 pub const fn at(value: f64) -> Self {
312 SpringState {
313 value,
314 velocity: 0.0,
315 }
316 }
317}
318
319#[derive(Clone, Copy, Debug, PartialEq)]
322pub struct Decay {
323 pub rate: f64,
325}
326
327impl Decay {
328 pub fn step(self, state: &mut SpringState, dt: f64) {
331 let ms = (dt * 1000.0).clamp(0.0, 250.0);
332 let rate = self.rate.clamp(0.0, 0.999_999);
333 let k = rate.ln();
334 let factor = rate.powf(ms);
335 state.value += state.velocity * (factor - 1.0) / k / 1000.0;
337 state.velocity *= factor;
338 }
339
340 #[must_use]
342 pub fn stopped(self, state: SpringState) -> bool {
343 state.velocity.abs() < 1.0
344 }
345
346 #[must_use]
349 pub fn rest(self, state: SpringState) -> f64 {
350 let k = self.rate.clamp(0.0, 0.999_999).ln();
351 state.value - state.velocity / k / 1000.0
352 }
353}
354
355#[derive(Clone, Debug, PartialEq)]
374pub struct Interpolation<T: Lerp> {
375 first: (f64, T),
377 rest: Vec<(f64, T)>,
379 extend_start: bool,
381 extend_end: bool,
383}
384
385impl<T: Lerp> Interpolation<T> {
386 #[must_use]
389 pub fn new<const N: usize>(input: [f64; N], output: [T; N]) -> Self {
390 const { assert!(N >= 1, "an interpolation needs at least one stop") };
391 let mut stops = input.into_iter().zip(output);
392 let Some(first) = stops.next() else {
393 unreachable!("N >= 1 is asserted at compile time")
394 };
395 Interpolation {
396 first,
397 rest: stops.collect(),
398 extend_start: false,
399 extend_end: false,
400 }
401 }
402
403 #[must_use]
406 pub fn extend(mut self) -> Self {
407 self.extend_start = true;
408 self.extend_end = true;
409 self
410 }
411
412 #[must_use]
414 pub fn extend_start(mut self) -> Self {
415 self.extend_start = true;
416 self
417 }
418
419 #[must_use]
421 pub fn extend_end(mut self) -> Self {
422 self.extend_end = true;
423 self
424 }
425
426 #[must_use]
428 pub fn at(&self, x: f64) -> T {
429 let mut lo = &self.first;
430 let Some(mut hi) = self.rest.first() else {
431 return lo.1.clone();
432 };
433 if x < lo.0 && !self.extend_start {
434 return lo.1.clone();
435 }
436 for stop in self.rest.iter().skip(1) {
438 if x <= hi.0 {
439 break;
440 }
441 lo = hi;
442 hi = stop;
443 }
444 if x > hi.0 && !self.extend_end {
445 return hi.1.clone();
446 }
447 let span = hi.0 - lo.0;
448 if span <= 0.0 {
449 return if x < lo.0 { lo.1.clone() } else { hi.1.clone() };
450 }
451 lo.1.lerp(&hi.1, (x - lo.0) / span)
452 }
453}
454
455struct Slot<T> {
461 target: T,
463 claim: u64,
466 flight: Option<Playing>,
468 clock: FrameClock,
470}
471
472pub struct Animated<T: Lerp + 'static = f64> {
501 value: Signal<T>,
503 velocity: Signal<f64>,
505 moving: Signal<bool>,
507 slot: Signal<Slot<T>>,
509}
510
511#[expect(
512 clippy::expl_impl_clone_on_copy,
513 reason = "a derive would demand `T: Copy`, and the handle is `Copy` whatever it holds"
514)]
515impl<T: Lerp + 'static> Clone for Animated<T> {
516 fn clone(&self) -> Self {
517 *self
518 }
519}
520impl<T: Lerp + 'static> Copy for Animated<T> {}
521
522impl<T: Lerp + std::fmt::Debug + 'static> std::fmt::Debug for Animated<T> {
523 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
524 f.debug_struct("Animated")
525 .field("value", &self.try_now())
526 .finish_non_exhaustive()
527 }
528}
529
530impl<T: Lerp + 'static> Animated<T> {
531 #[must_use]
533 pub fn new(initial: T) -> Self {
534 Self::on(FrameClock::current(), initial)
535 }
536
537 #[must_use]
539 pub fn on(clock: FrameClock, initial: T) -> Self {
540 Animated {
541 value: Signal::new(initial.clone()),
542 velocity: Signal::new(0.0),
543 moving: Signal::new(false),
544 slot: Signal::new(Slot {
545 target: initial,
546 claim: 0,
547 flight: None,
548 clock,
549 }),
550 }
551 }
552
553 #[must_use]
555 pub fn get(self) -> T {
556 self.value.get()
557 }
558
559 #[must_use]
561 pub fn get_untracked(self) -> T {
562 self.value.get_untracked()
563 }
564
565 #[must_use]
567 pub fn target(self) -> T {
568 self.slot.with_untracked(|slot| slot.target.clone())
569 }
570
571 #[must_use]
574 pub fn is_animating(self) -> bool {
575 self.moving.get()
576 }
577
578 pub fn set(self, value: T) {
580 self.claim(Some(value.clone()));
581 if let Some(flight) = self.take_flight() {
582 flight.stop();
583 }
584 self.value.set(value);
585 self.velocity.set_if_changed(0.0);
586 self.moving.set_if_changed(false);
587 }
588
589 pub fn animate_to(self, target: T, spec: AnimSpec) -> Playing {
594 if let Some(flight) = self.take_flight() {
595 flight.stop();
596 }
597 let playing = Animation::tween(self, target, spec).start();
598 if !playing.is_finished() {
599 let flight = playing.clone();
600 self.slot.update(|slot| slot.flight = Some(flight));
601 }
602 playing
603 }
604
605 pub fn interpolate<U: Lerp + 'static, const N: usize>(
616 self,
617 input: [f64; N],
618 output: [U; N],
619 ) -> impl Fn() -> U + Clone + 'static
620 where
621 T: Into<f64>,
622 {
623 self.interpolate_with(Interpolation::new(input, output))
624 }
625
626 pub fn interpolate_with<U: Lerp + 'static>(
629 self,
630 map: Interpolation<U>,
631 ) -> impl Fn() -> U + Clone + 'static
632 where
633 T: Into<f64>,
634 {
635 let map = Rc::new(map);
636 move || map.at(self.get().into())
637 }
638
639 fn try_now(self) -> Option<T> {
641 day_reactive::untrack(|| self.value.try_get())
642 }
643
644 fn claim(self, target: Option<T>) -> u64 {
647 let mut claim = 0;
648 self.slot.update(|slot| {
649 slot.claim += 1;
650 if let Some(target) = target {
651 slot.target = target;
652 }
653 claim = slot.claim;
654 });
655 claim
656 }
657
658 fn take_flight(self) -> Option<Playing> {
660 let mut flight = None;
661 self.slot.update(|slot| flight = slot.flight.take());
662 flight
663 }
664
665 fn clock(self) -> Option<FrameClock> {
667 day_reactive::untrack(|| self.slot.try_with(|slot| slot.clock))
668 }
669}
670
671impl Animated<f64> {
672 #[must_use]
674 pub fn velocity(self) -> f64 {
675 self.velocity.get()
676 }
677
678 pub fn set_velocity(self, velocity: f64) {
681 self.velocity.set(velocity);
682 }
683}
684
685struct Hold<T: Lerp + 'static> {
687 value: Animated<T>,
689 claim: u64,
691}
692
693impl<T: Lerp + 'static> Hold<T> {
694 fn take(value: Animated<T>, target: Option<T>) -> Option<(Self, T)> {
697 let from = value.try_now()?;
698 let claim = value.claim(target);
699 value.moving.set_if_changed(true);
700 Some((Hold { value, claim }, from))
701 }
702
703 fn owns(&self) -> Option<bool> {
706 day_reactive::untrack(|| self.value.slot.try_with(|slot| slot.claim == self.claim))
707 }
708
709 fn write(&self, next: T, dt: f64) {
711 if dt > 0.0
712 && let Some(next) = (&next as &dyn Any).downcast_ref::<f64>()
713 && let Some(prev) = self
714 .value
715 .try_now()
716 .as_ref()
717 .and_then(|p| (p as &dyn Any).downcast_ref::<f64>().copied())
718 {
719 self.value.velocity.set((next - prev) / dt);
720 }
721 self.value.value.set(next);
722 }
723
724 fn land(&self, end: T) {
726 self.value.value.set(end);
727 self.value.velocity.set_if_changed(0.0);
728 self.release();
729 }
730
731 fn release(&self) {
733 if self.owns() == Some(true) {
734 self.value.moving.set_if_changed(false);
735 }
736 }
737}
738
739#[derive(Clone, Copy, Debug, PartialEq)]
745enum Flow {
746 Running,
748 Ended(f64),
751 Gone,
753}
754
755trait Leaf {
757 fn begin(&self) -> Option<Box<dyn LeafRun>>;
759 fn finish(&self);
761 fn endless(&self) -> bool {
763 false
764 }
765 fn snapshot(&self) -> Option<Box<dyn Fn()>> {
767 None
768 }
769 fn clock(&self) -> Option<FrameClock> {
771 None
772 }
773}
774
775trait LeafRun {
777 fn advance(&mut self, dt: f64) -> Flow;
779 fn release(&self);
781}
782
783fn snapshot_of<T: Lerp + 'static>(value: Animated<T>) -> Option<Box<dyn Fn()>> {
785 let at = value.try_now()?;
786 let velocity = day_reactive::untrack(|| value.velocity.try_get())?;
787 Some(Box::new(move || {
788 value.set(at.clone());
789 value.velocity.set_if_changed(velocity);
790 }))
791}
792
793struct TimingLeaf<T: Lerp + 'static> {
795 value: Animated<T>,
796 to: T,
797 secs: f64,
798 easing: Easing,
799}
800
801impl<T: Lerp + 'static> Leaf for TimingLeaf<T> {
802 fn begin(&self) -> Option<Box<dyn LeafRun>> {
803 let (hold, from) = Hold::take(self.value, Some(self.to.clone()))?;
804 Some(Box::new(TimingRun {
805 hold,
806 from,
807 to: self.to.clone(),
808 secs: self.secs,
809 easing: self.easing,
810 elapsed: 0.0,
811 }))
812 }
813 fn finish(&self) {
814 self.value.set(self.to.clone());
815 }
816 fn snapshot(&self) -> Option<Box<dyn Fn()>> {
817 snapshot_of(self.value)
818 }
819 fn clock(&self) -> Option<FrameClock> {
820 self.value.clock()
821 }
822}
823
824struct TimingRun<T: Lerp + 'static> {
825 hold: Hold<T>,
826 from: T,
827 to: T,
828 secs: f64,
829 easing: Easing,
830 elapsed: f64,
831}
832
833impl<T: Lerp + 'static> LeafRun for TimingRun<T> {
834 fn advance(&mut self, dt: f64) -> Flow {
835 self.elapsed += dt;
836 let left = self.elapsed - self.secs;
837 match self.hold.owns() {
838 None => Flow::Gone,
839 Some(false) if left >= 0.0 => Flow::Ended(left.min(dt)),
841 Some(false) => Flow::Running,
842 Some(true) if left >= 0.0 => {
843 self.hold.land(self.to.clone());
844 Flow::Ended(left.min(dt))
845 }
846 Some(true) => {
847 let t = self.easing.value(self.elapsed / self.secs);
848 self.hold.write(self.from.lerp(&self.to, t), dt);
849 Flow::Running
850 }
851 }
852 }
853 fn release(&self) {
854 self.hold.release();
855 }
856}
857
858struct TweenLeaf<T: Lerp + 'static> {
860 value: Animated<T>,
861 to: T,
862 spec: AnimSpec,
863}
864
865impl<T: Lerp + 'static> Leaf for TweenLeaf<T> {
866 fn begin(&self) -> Option<Box<dyn LeafRun>> {
867 let (hold, from) = Hold::take(self.value, Some(self.to.clone()))?;
868 Some(Box::new(TweenRun {
869 hold,
870 from,
871 to: self.to.clone(),
872 spec: self.spec,
873 elapsed: 0.0,
874 }))
875 }
876 fn finish(&self) {
877 self.value.set(self.to.clone());
878 }
879 fn endless(&self) -> bool {
880 self.spec.repeats_forever()
881 }
882 fn snapshot(&self) -> Option<Box<dyn Fn()>> {
883 snapshot_of(self.value)
884 }
885 fn clock(&self) -> Option<FrameClock> {
886 self.value.clock()
887 }
888}
889
890struct TweenRun<T: Lerp + 'static> {
891 hold: Hold<T>,
892 from: T,
893 to: T,
894 spec: AnimSpec,
895 elapsed: f64,
896}
897
898impl<T: Lerp + 'static> LeafRun for TweenRun<T> {
899 fn advance(&mut self, dt: f64) -> Flow {
900 self.elapsed += dt;
901 let sample = self.spec.sample(self.elapsed);
902 let left = self
903 .spec
904 .total_secs()
905 .map_or(0.0, |total| (self.elapsed - total).clamp(0.0, dt));
906 match self.hold.owns() {
907 None => Flow::Gone,
908 Some(false) if sample.done => Flow::Ended(left),
909 Some(false) => Flow::Running,
910 Some(true) if sample.done => {
911 self.hold.land(self.to.clone());
914 Flow::Ended(left)
915 }
916 Some(true) => {
917 self.hold
918 .write(self.from.lerp(&self.to, sample.progress), dt);
919 Flow::Running
920 }
921 }
922 }
923 fn release(&self) {
924 self.hold.release();
925 }
926}
927
928struct SpringLeaf {
930 value: Animated<f64>,
931 to: f64,
932 spring: Spring,
933}
934
935impl Leaf for SpringLeaf {
936 fn begin(&self) -> Option<Box<dyn LeafRun>> {
937 let (hold, from) = Hold::take(self.value, Some(self.to))?;
938 let velocity = day_reactive::untrack(|| self.value.velocity.try_get())?;
939 let mass = self.spring.mass.max(1e-6);
942 let omega0 = (self.spring.stiffness.max(1e-6) / mass).sqrt();
943 let reach = (self.to - from).abs().max(velocity.abs() / omega0);
944 Some(Box::new(SpringRun {
945 hold,
946 to: self.to,
947 spring: self.spring,
948 rest: (reach * 1e-3).max(f64::EPSILON),
949 rest_speed: (reach * omega0 * 1e-3).max(f64::EPSILON),
950 }))
951 }
952 fn finish(&self) {
953 self.value.set(self.to);
954 }
955 fn snapshot(&self) -> Option<Box<dyn Fn()>> {
956 snapshot_of(self.value)
957 }
958 fn clock(&self) -> Option<FrameClock> {
959 self.value.clock()
960 }
961}
962
963struct SpringRun {
964 hold: Hold<f64>,
965 to: f64,
966 spring: Spring,
967 rest: f64,
969 rest_speed: f64,
971}
972
973impl LeafRun for SpringRun {
974 fn advance(&mut self, dt: f64) -> Flow {
975 match self.hold.owns() {
976 None => return Flow::Gone,
977 Some(false) => return Flow::Ended(0.0),
978 Some(true) => {}
979 }
980 let value = self.hold.value;
981 let (Some(at), Some(velocity)) = (
982 value.try_now(),
983 day_reactive::untrack(|| value.velocity.try_get()),
984 ) else {
985 return Flow::Gone;
986 };
987 let mut state = SpringState {
988 value: at,
989 velocity,
990 };
991 self.spring.step(&mut state, self.to, dt);
992 if (state.value - self.to).abs() < self.rest && state.velocity.abs() < self.rest_speed {
993 self.hold.land(self.to);
994 return Flow::Ended(0.0);
995 }
996 value.value.set(state.value);
997 value.velocity.set(state.velocity);
998 Flow::Running
999 }
1000 fn release(&self) {
1001 self.hold.release();
1002 }
1003}
1004
1005struct DecayLeaf {
1007 value: Animated<f64>,
1008 decay: Decay,
1009}
1010
1011impl DecayLeaf {
1012 fn state(&self) -> Option<SpringState> {
1014 Some(SpringState {
1015 value: self.value.try_now()?,
1016 velocity: day_reactive::untrack(|| self.value.velocity.try_get())?,
1017 })
1018 }
1019}
1020
1021impl Leaf for DecayLeaf {
1022 fn begin(&self) -> Option<Box<dyn LeafRun>> {
1023 let (hold, _) = Hold::take(self.value, self.state().map(|s| self.decay.rest(s)))?;
1024 Some(Box::new(DecayRun {
1025 hold,
1026 decay: self.decay,
1027 }))
1028 }
1029 fn finish(&self) {
1030 if let Some(state) = self.state() {
1031 self.value.set(self.decay.rest(state));
1032 }
1033 }
1034 fn snapshot(&self) -> Option<Box<dyn Fn()>> {
1035 snapshot_of(self.value)
1036 }
1037 fn clock(&self) -> Option<FrameClock> {
1038 self.value.clock()
1039 }
1040}
1041
1042struct DecayRun {
1043 hold: Hold<f64>,
1044 decay: Decay,
1045}
1046
1047impl LeafRun for DecayRun {
1048 fn advance(&mut self, dt: f64) -> Flow {
1049 match self.hold.owns() {
1050 None => return Flow::Gone,
1051 Some(false) => return Flow::Ended(0.0),
1052 Some(true) => {}
1053 }
1054 let value = self.hold.value;
1055 let (Some(at), Some(velocity)) = (
1056 value.try_now(),
1057 day_reactive::untrack(|| value.velocity.try_get()),
1058 ) else {
1059 return Flow::Gone;
1060 };
1061 let mut state = SpringState {
1062 value: at,
1063 velocity,
1064 };
1065 self.decay.step(&mut state, dt);
1066 if self.decay.stopped(state) {
1067 self.hold.land(state.value);
1068 return Flow::Ended(0.0);
1069 }
1070 value.value.set(state.value);
1071 value.velocity.set(state.velocity);
1072 Flow::Running
1073 }
1074 fn release(&self) {
1075 self.hold.release();
1076 }
1077}
1078
1079struct DriveLeaf {
1081 spec: AnimSpec,
1082 step: Rc<RefCell<dyn FnMut(AnimSample)>>,
1083}
1084
1085impl DriveLeaf {
1086 fn call(step: &Rc<RefCell<dyn FnMut(AnimSample)>>, sample: AnimSample) {
1089 if let Ok(mut step) = step.try_borrow_mut() {
1090 step(sample);
1091 }
1092 }
1093}
1094
1095impl Leaf for DriveLeaf {
1096 fn begin(&self) -> Option<Box<dyn LeafRun>> {
1097 Some(Box::new(DriveRun {
1098 spec: self.spec,
1099 step: self.step.clone(),
1100 elapsed: 0.0,
1101 }))
1102 }
1103 fn finish(&self) {
1104 let end = self.spec.total_secs().unwrap_or(0.0);
1105 Self::call(
1106 &self.step,
1107 AnimSample {
1108 done: true,
1109 ..self.spec.sample(end)
1110 },
1111 );
1112 }
1113 fn endless(&self) -> bool {
1114 self.spec.repeats_forever()
1115 }
1116}
1117
1118struct DriveRun {
1119 spec: AnimSpec,
1120 step: Rc<RefCell<dyn FnMut(AnimSample)>>,
1121 elapsed: f64,
1122}
1123
1124impl LeafRun for DriveRun {
1125 fn advance(&mut self, dt: f64) -> Flow {
1126 self.elapsed += dt;
1127 let sample = self.spec.sample(self.elapsed);
1128 DriveLeaf::call(&self.step, sample);
1129 if sample.done {
1130 let total = self.spec.total_secs().unwrap_or(self.elapsed);
1131 Flow::Ended((self.elapsed - total).clamp(0.0, dt))
1132 } else {
1133 Flow::Running
1134 }
1135 }
1136 fn release(&self) {}
1137}
1138
1139#[derive(Clone)]
1141enum Node {
1142 Leaf(Rc<dyn Leaf>),
1144 Delay(f64),
1146 Sequence(Vec<Node>),
1148 Parallel(Vec<Node>),
1150 Repeat(Box<Node>, Option<u32>),
1152}
1153
1154impl Node {
1155 fn endless(&self) -> bool {
1157 match self {
1158 Node::Leaf(leaf) => leaf.endless(),
1159 Node::Delay(_) | Node::Repeat(_, Some(0)) => false,
1161 Node::Sequence(parts) | Node::Parallel(parts) => parts.iter().any(Node::endless),
1162 Node::Repeat(part, times) => times.is_none() || part.endless(),
1163 }
1164 }
1165
1166 fn finish(&self) {
1168 match self {
1169 Node::Leaf(leaf) => leaf.finish(),
1170 Node::Delay(_) | Node::Repeat(_, Some(0)) => {}
1172 Node::Sequence(parts) | Node::Parallel(parts) => parts.iter().for_each(Node::finish),
1173 Node::Repeat(part, _) => part.finish(),
1174 }
1175 }
1176
1177 fn leaves(&self, visit: &mut dyn FnMut(&dyn Leaf)) {
1179 match self {
1180 Node::Leaf(leaf) => visit(leaf.as_ref()),
1181 Node::Delay(_) => {}
1182 Node::Sequence(parts) | Node::Parallel(parts) => {
1183 for part in parts {
1184 part.leaves(visit);
1185 }
1186 }
1187 Node::Repeat(part, _) => part.leaves(visit),
1188 }
1189 }
1190
1191 fn begin(&self) -> Option<Run> {
1194 Some(match self {
1195 Node::Leaf(leaf) => Run::Leaf(leaf.begin()?),
1196 Node::Delay(secs) => Run::Delay(*secs),
1197 Node::Sequence(parts) => Run::Sequence {
1198 parts: parts.clone(),
1199 at: 0,
1200 current: match parts.first() {
1201 Some(first) => Some(Box::new(first.begin()?)),
1202 None => None,
1203 },
1204 },
1205 Node::Parallel(parts) => {
1206 let mut runs = Vec::with_capacity(parts.len());
1207 for part in parts {
1208 let Some(run) = part.begin() else {
1209 for (run, _) in &runs {
1210 Run::release(run);
1211 }
1212 return None;
1213 };
1214 runs.push((run, false));
1215 }
1216 Run::Parallel(runs)
1217 }
1218 Node::Repeat(_, Some(0)) => Run::Delay(0.0),
1220 Node::Repeat(part, times) => Run::Repeat {
1221 part: (**part).clone(),
1222 times: *times,
1223 done: 0,
1224 current: Box::new(part.begin()?),
1225 },
1226 })
1227 }
1228}
1229
1230const INSTANT_PASSES_PER_FRAME: u32 = 64;
1233
1234enum Run {
1236 Leaf(Box<dyn LeafRun>),
1238 Delay(f64),
1240 Sequence {
1243 parts: Vec<Node>,
1244 at: usize,
1245 current: Option<Box<Run>>,
1246 },
1247 Parallel(Vec<(Run, bool)>),
1249 Repeat {
1251 part: Node,
1252 times: Option<u32>,
1253 done: u32,
1254 current: Box<Run>,
1255 },
1256}
1257
1258impl Run {
1259 fn advance(&mut self, dt: f64) -> Flow {
1261 match self {
1262 Run::Leaf(run) => run.advance(dt),
1263 Run::Delay(left) => {
1264 *left -= dt;
1265 if *left <= 0.0 {
1266 Flow::Ended((-*left).min(dt))
1267 } else {
1268 Flow::Running
1269 }
1270 }
1271 Run::Sequence { parts, at, current } => {
1272 let mut dt = dt;
1273 loop {
1274 let Some(run) = current else {
1275 return Flow::Ended(dt);
1276 };
1277 match run.advance(dt) {
1278 Flow::Ended(left) => dt = left,
1279 flow => return flow,
1280 }
1281 *at += 1;
1282 *current = match parts.get(*at) {
1283 Some(next) => match next.begin() {
1284 Some(run) => Some(Box::new(run)),
1285 None => return Flow::Gone,
1286 },
1287 None => None,
1288 };
1289 }
1290 }
1291 Run::Parallel(runs) => {
1292 let mut left = dt;
1293 for (run, ended) in runs.iter_mut().filter(|(_, ended)| !*ended) {
1294 match run.advance(dt) {
1295 Flow::Running => {}
1296 Flow::Ended(unused) => {
1297 *ended = true;
1298 left = left.min(unused);
1299 }
1300 Flow::Gone => return Flow::Gone,
1301 }
1302 }
1303 if runs.iter().all(|(_, ended)| *ended) {
1304 Flow::Ended(left)
1305 } else {
1306 Flow::Running
1307 }
1308 }
1309 Run::Repeat {
1310 part,
1311 times,
1312 done,
1313 current,
1314 } => {
1315 let mut dt = dt;
1316 let mut instant = 0;
1323 loop {
1324 let before = dt;
1325 match current.advance(dt) {
1326 Flow::Ended(left) => {
1327 *done = done.saturating_add(1);
1328 if times.is_some_and(|times| *done >= times) {
1329 return Flow::Ended(left);
1330 }
1331 match part.begin() {
1332 Some(run) => **current = run,
1333 None => return Flow::Gone,
1334 }
1335 if left <= 0.0 {
1336 return Flow::Running;
1337 }
1338 if left < before || times.is_some() {
1339 instant = 0;
1340 } else {
1341 instant += 1;
1342 if instant >= INSTANT_PASSES_PER_FRAME {
1343 return Flow::Running;
1344 }
1345 }
1346 dt = left;
1347 }
1348 flow => return flow,
1349 }
1350 }
1351 }
1352 }
1353 }
1354
1355 fn release(&self) {
1357 match self {
1358 Run::Leaf(run) => run.release(),
1359 Run::Delay(_) => {}
1360 Run::Sequence { current, .. } => {
1361 if let Some(run) = current {
1362 run.release();
1363 }
1364 }
1365 Run::Parallel(runs) => runs
1366 .iter()
1367 .filter(|(_, ended)| !*ended)
1368 .for_each(|(run, _)| run.release()),
1369 Run::Repeat { current, .. } => current.release(),
1370 }
1371 }
1372}
1373
1374#[derive(Clone)]
1402#[must_use = "an animation does nothing until it is started"]
1403pub struct Animation {
1404 node: Node,
1405}
1406
1407impl Animation {
1408 pub fn timing<T: Lerp + 'static>(value: Animated<T>, to: T, ms: u32, easing: Easing) -> Self {
1411 Self::leaf(TimingLeaf {
1412 value,
1413 to,
1414 secs: f64::from(ms) / 1000.0,
1415 easing,
1416 })
1417 }
1418
1419 pub fn tween<T: Lerp + 'static>(value: Animated<T>, to: T, spec: AnimSpec) -> Self {
1424 Self::leaf(TweenLeaf { value, to, spec })
1425 }
1426
1427 pub fn spring(value: Animated<f64>, to: f64, spring: Spring) -> Self {
1431 Self::leaf(SpringLeaf { value, to, spring })
1432 }
1433
1434 pub fn decay(value: Animated<f64>, decay: Decay) -> Self {
1436 Self::leaf(DecayLeaf { value, decay })
1437 }
1438
1439 pub fn drive(spec: AnimSpec, step: impl FnMut(AnimSample) + 'static) -> Self {
1443 Self::leaf(DriveLeaf {
1444 spec,
1445 step: Rc::new(RefCell::new(step)),
1446 })
1447 }
1448
1449 pub fn delay(ms: u32) -> Self {
1451 Animation {
1452 node: Node::Delay(f64::from(ms) / 1000.0),
1453 }
1454 }
1455
1456 pub fn sequence(steps: impl IntoIterator<Item = Animation>) -> Self {
1459 Animation {
1460 node: Node::Sequence(steps.into_iter().map(|step| step.node).collect()),
1461 }
1462 }
1463
1464 pub fn parallel(steps: impl IntoIterator<Item = Animation>) -> Self {
1466 Animation {
1467 node: Node::Parallel(steps.into_iter().map(|step| step.node).collect()),
1468 }
1469 }
1470
1471 pub fn stagger(gap_ms: u32, steps: impl IntoIterator<Item = Animation>) -> Self {
1473 let gap = f64::from(gap_ms) / 1000.0;
1474 Animation {
1475 node: Node::Parallel(
1476 steps
1477 .into_iter()
1478 .enumerate()
1479 .map(|(i, step)| {
1480 if i == 0 {
1481 step.node
1482 } else {
1483 Node::Sequence(vec![Node::Delay(gap * i as f64), step.node])
1484 }
1485 })
1486 .collect(),
1487 ),
1488 }
1489 }
1490
1491 pub fn repeat(self, times: u32) -> Self {
1493 Animation {
1494 node: Node::Repeat(Box::new(self.node), Some(times)),
1495 }
1496 }
1497
1498 pub fn looped(self) -> Self {
1500 Animation {
1501 node: Node::Repeat(Box::new(self.node), None),
1502 }
1503 }
1504
1505 #[must_use]
1507 pub fn is_endless(&self) -> bool {
1508 self.node.endless()
1509 }
1510
1511 pub fn jump_to_end(&self) {
1514 day_reactive::batch(|| self.node.finish());
1515 }
1516
1517 pub fn start(&self) -> Playing {
1520 let mut clock = None;
1521 self.node
1522 .leaves(&mut |leaf| clock = clock.or_else(|| leaf.clock()));
1523 self.start_on(clock.unwrap_or_else(FrameClock::current))
1524 }
1525
1526 pub fn start_on(&self, clock: FrameClock) -> Playing {
1528 let mut restore = Vec::new();
1529 self.node
1530 .leaves(&mut |leaf| restore.extend(leaf.snapshot()));
1531 let shared = Rc::new(Shared {
1532 outcome: Cell::new(None),
1533 handle: RefCell::new(None),
1534 run: RefCell::new(None),
1535 wakers: RefCell::new(Vec::new()),
1536 listeners: RefCell::new(Vec::new()),
1537 restore,
1538 });
1539 let playing = Playing {
1540 shared: shared.clone(),
1541 };
1542 let endless = self.node.endless();
1543 if crate::reduce_motion_now() && !endless {
1544 self.jump_to_end();
1545 shared.end(Outcome::Finished);
1546 return playing;
1547 }
1548 let Some(run) = day_reactive::batch(|| self.node.begin()) else {
1549 shared.end(Outcome::Stopped);
1550 return playing;
1551 };
1552 *shared.run.borrow_mut() = Some(run);
1553 let node = self.node.clone();
1554 let guard = Guard(shared.clone());
1555 let handle = clock.subscribe(move |frame| {
1556 let shared = &guard.0;
1557 if shared.outcome.get().is_some() {
1558 return ControlFlow::Break(());
1559 }
1560 let flow = if crate::reduce_motion_now() && !endless {
1562 node.finish();
1563 Flow::Ended(0.0)
1564 } else {
1565 shared
1566 .run
1567 .try_borrow_mut()
1568 .ok()
1569 .and_then(|mut run| {
1570 run.as_mut()
1571 .map(|run| run.advance(frame.delta.as_secs_f64()))
1572 })
1573 .unwrap_or(Flow::Gone)
1574 };
1575 match flow {
1576 Flow::Running if shared.outcome.get().is_none() => {
1578 return ControlFlow::Continue(());
1579 }
1580 Flow::Running => shared.cleanup(),
1581 Flow::Ended(_) => shared.end(Outcome::Finished),
1582 Flow::Gone => shared.end(Outcome::Stopped),
1583 }
1584 ControlFlow::Break(())
1585 });
1586 if shared.outcome.get().is_none() {
1588 *shared.handle.borrow_mut() = Some(handle);
1589 }
1590 playing
1591 }
1592
1593 fn leaf(leaf: impl Leaf + 'static) -> Self {
1595 Animation {
1596 node: Node::Leaf(Rc::new(leaf)),
1597 }
1598 }
1599}
1600
1601#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1607pub enum Outcome {
1608 Finished,
1610 Stopped,
1613}
1614
1615type Listener = Box<dyn FnOnce(Outcome)>;
1617
1618struct Shared {
1620 outcome: Cell<Option<Outcome>>,
1622 handle: RefCell<Option<FrameHandle>>,
1624 run: RefCell<Option<Run>>,
1626 wakers: RefCell<Vec<Waker>>,
1628 listeners: RefCell<Vec<Listener>>,
1630 restore: Vec<Box<dyn Fn()>>,
1632}
1633
1634impl Shared {
1635 fn end(&self, outcome: Outcome) {
1637 if self.outcome.get().is_some() {
1638 return;
1639 }
1640 self.outcome.set(Some(outcome));
1641 self.cleanup();
1642 }
1643
1644 fn cleanup(&self) {
1648 let Some(outcome) = self.outcome.get() else {
1649 return;
1650 };
1651 let Ok(mut run) = self.run.try_borrow_mut() else {
1652 return;
1653 };
1654 if let Some(run) = run.take() {
1655 day_reactive::batch(|| run.release());
1656 }
1657 drop(run);
1658 let handle = self.handle.borrow_mut().take();
1660 drop(handle);
1661 for waker in std::mem::take(&mut *self.wakers.borrow_mut()) {
1662 waker.wake();
1663 }
1664 for listener in std::mem::take(&mut *self.listeners.borrow_mut()) {
1665 listener(outcome);
1666 }
1667 }
1668}
1669
1670struct Guard(Rc<Shared>);
1673
1674impl Drop for Guard {
1675 fn drop(&mut self) {
1676 if crate::frame::alive() {
1678 self.0.end(Outcome::Stopped);
1679 }
1680 }
1681}
1682
1683#[derive(Clone)]
1690pub struct Playing {
1691 shared: Rc<Shared>,
1692}
1693
1694impl Playing {
1695 #[expect(
1698 clippy::must_use_candidate,
1699 reason = "stopping is the point; whether it was running is incidental"
1700 )]
1701 pub fn stop(&self) -> bool {
1702 let running = self.is_running();
1703 self.shared.end(Outcome::Stopped);
1704 running
1705 }
1706
1707 pub fn reset(&self) {
1709 self.stop();
1710 day_reactive::batch(|| self.shared.restore.iter().for_each(|restore| restore()));
1711 }
1712
1713 #[must_use]
1715 pub fn is_running(&self) -> bool {
1716 self.shared.outcome.get().is_none()
1717 }
1718
1719 #[must_use]
1721 pub fn is_finished(&self) -> bool {
1722 self.shared.outcome.get() == Some(Outcome::Finished)
1723 }
1724
1725 #[must_use]
1727 pub fn outcome(&self) -> Option<Outcome> {
1728 self.shared.outcome.get()
1729 }
1730
1731 pub fn on_end(&self, f: impl FnOnce(Outcome) + 'static) {
1734 match self.shared.outcome.get() {
1735 Some(outcome) => f(outcome),
1736 None => self.shared.listeners.borrow_mut().push(Box::new(f)),
1737 }
1738 }
1739}
1740
1741impl std::fmt::Debug for Playing {
1742 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1743 f.debug_struct("Playing")
1744 .field("outcome", &self.shared.outcome.get())
1745 .finish()
1746 }
1747}
1748
1749impl Future for Playing {
1750 type Output = Outcome;
1751
1752 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Outcome> {
1753 if let Some(outcome) = self.shared.outcome.get() {
1754 return Poll::Ready(outcome);
1755 }
1756 self.shared.wakers.borrow_mut().push(cx.waker().clone());
1757 Poll::Pending
1758 }
1759}
1760
1761#[cfg(test)]
1762mod tests {
1763 use super::*;
1764
1765 #[test]
1766 fn every_curve_starts_at_zero_and_ends_at_one() {
1767 let curves = [
1768 Easing::Linear,
1769 Easing::EASE,
1770 Easing::EASE_IN_OUT,
1771 Easing::Power(Ease::Out, 2.0),
1772 Easing::Power(Ease::InOut, 3.0),
1773 Easing::Sine(Ease::In),
1774 Easing::Circle(Ease::Out),
1775 Easing::Exponential(Ease::InOut),
1776 Easing::Back(Ease::Out, 1.70158),
1777 Easing::ElasticOut(1.0),
1778 Easing::BounceOut,
1779 ];
1780 for curve in curves {
1781 assert!(curve.value(0.0).abs() < 1e-3, "{curve:?} at 0");
1782 assert!((curve.value(1.0) - 1.0).abs() < 1e-3, "{curve:?} at 1");
1783 }
1784 }
1785
1786 #[test]
1787 fn back_out_overshoots_and_linear_bezier_is_linear() {
1788 let peak = Easing::Back(Ease::Out, 1.70158)
1789 .samples(101)
1790 .into_iter()
1791 .fold(0.0, f64::max);
1792 assert!(peak > 1.05 && peak < 1.2, "{peak}");
1793 let straight = Easing::Bezier(0.25, 0.25, 0.75, 0.75);
1794 assert!((straight.value(0.3) - 0.3).abs() < 1e-3);
1795 }
1796
1797 #[test]
1798 fn a_spring_settles_on_its_target_and_a_loose_one_overshoots() {
1799 let firm = Spring::new(400.0, 30.0);
1800 let mut state = SpringState::default();
1801 for _ in 0..240 {
1802 firm.step(&mut state, 100.0, 1.0 / 60.0);
1803 }
1804 assert!(firm.settled(state, 100.0), "{state:?}");
1805
1806 let peak = Spring::new(180.0, 8.0)
1807 .response(1.8, 200)
1808 .into_iter()
1809 .fold(0.0, f64::max);
1810 assert!(peak > 1.2, "{peak}");
1811 }
1812
1813 #[test]
1814 fn a_decay_stops_at_a_finite_distance() {
1815 let decay = Decay { rate: 0.992 };
1816 let mut state = SpringState {
1817 value: 0.0,
1818 velocity: 1000.0,
1819 };
1820 for _ in 0..600 {
1821 decay.step(&mut state, 1.0 / 60.0);
1822 }
1823 assert!(decay.stopped(state));
1824 assert!((state.value - 124.5).abs() < 2.0, "{}", state.value);
1826 }
1827
1828 use crate::tree::RNode;
1831 use day_spec::{Color, FrameStamp};
1832 use std::collections::VecDeque;
1833
1834 struct Frames {
1836 pending: Rc<RefCell<VecDeque<day_spec::FrameCallback>>>,
1837 now: Cell<f64>,
1838 }
1839
1840 impl Frames {
1841 fn new() -> Self {
1842 let pending: Rc<RefCell<VecDeque<day_spec::FrameCallback>>> = Rc::default();
1843 let q = pending.clone();
1844 crate::frame::install_frame_requester(move |_, cb| {
1845 q.borrow_mut().push_back(cb);
1846 Box::new(|| {})
1847 });
1848 Frames {
1849 pending,
1850 now: Cell::new(10.0),
1851 }
1852 }
1853
1854 fn clock() -> FrameClock {
1855 FrameClock::for_root(RNode::default())
1856 }
1857
1858 fn step(&self, secs: f64) -> bool {
1860 self.now.set(self.now.get() + secs);
1861 let due: Vec<_> = self.pending.borrow_mut().drain(..).collect();
1863 let wanted = !due.is_empty();
1864 for cb in due {
1865 cb(FrameStamp::new(self.now.get()));
1866 }
1867 wanted
1868 }
1869
1870 fn run(&self, secs: f64) {
1872 for _ in 0..(secs * 60.0).round() as usize {
1873 self.step(1.0 / 60.0);
1874 }
1875 }
1876
1877 fn idle() -> bool {
1878 crate::frame_consumer_count() == 0
1879 }
1880 }
1881
1882 fn close(a: f64, b: f64) -> bool {
1883 (a - b).abs() < 1e-6
1884 }
1885
1886 #[test]
1887 fn a_timing_moves_its_value_and_releases_the_clock_on_arrival() {
1888 let frames = Frames::new();
1889 let v = Animated::on(Frames::clock(), 0.0);
1890 let playing = Animation::timing(v, 100.0, 100, Easing::Linear).start();
1891 assert!(v.is_animating() && playing.is_running());
1892 assert!(close(v.target(), 100.0));
1893 frames.step(0.0); assert!(close(v.get_untracked(), 0.0));
1895 frames.step(0.05);
1896 assert!(close(v.get_untracked(), 50.0));
1897 assert!(close(v.velocity.get_untracked(), 1000.0));
1898 frames.step(0.06);
1899 assert!(close(v.get_untracked(), 100.0));
1900 assert_eq!(playing.outcome(), Some(Outcome::Finished));
1901 assert!(!v.is_animating());
1902 assert!(Frames::idle(), "no frames wanted after arrival");
1903 }
1904
1905 #[test]
1906 fn animate_to_retargets_from_the_value_on_screen() {
1907 let frames = Frames::new();
1908 let v = Animated::on(Frames::clock(), 0.0);
1909 let first = v.animate_to(100.0, AnimSpec::linear(100));
1910 frames.step(0.0);
1911 frames.step(0.05);
1912 assert!(close(v.get_untracked(), 50.0));
1913 let second = v.animate_to(0.0, AnimSpec::linear(100));
1914 assert_eq!(first.outcome(), Some(Outcome::Stopped));
1915 frames.step(0.01); assert!(close(v.get_untracked(), 50.0));
1917 frames.step(0.05);
1918 assert!(close(v.get_untracked(), 25.0));
1919 frames.step(0.06);
1920 assert!(close(v.get_untracked(), 0.0));
1921 assert!(second.is_finished() && !v.is_animating() && Frames::idle());
1922 }
1923
1924 #[test]
1925 fn a_tween_follows_its_spec_and_rests_on_the_target() {
1926 let frames = Frames::new();
1927 let v = Animated::on(Frames::clock(), 0.0);
1928 let spec = AnimSpec::linear(100).delay(100).repeat(1, true);
1930 let playing = Animation::tween(v, 10.0, spec).start();
1931 frames.step(0.0);
1932 frames.step(0.05);
1933 assert!(close(v.get_untracked(), 0.0), "held through the delay");
1934 frames.step(0.1); assert!(close(v.get_untracked(), 5.0));
1936 frames.step(0.125); assert!(close(v.get_untracked(), 2.5));
1938 frames.step(0.05);
1939 assert!(close(v.get_untracked(), 10.0));
1940 assert!(playing.is_finished());
1941 }
1942
1943 #[test]
1944 fn a_sequence_runs_in_order_and_carries_time_across_its_steps() {
1945 let frames = Frames::new();
1946 let (a, b) = (
1947 Animated::on(Frames::clock(), 0.0),
1948 Animated::on(Frames::clock(), 0.0),
1949 );
1950 let playing = Animation::sequence([
1951 Animation::timing(a, 1.0, 100, Easing::Linear),
1952 Animation::delay(100),
1953 Animation::timing(b, 1.0, 100, Easing::Linear),
1954 ])
1955 .start();
1956 frames.step(0.0);
1957 frames.step(0.15);
1958 assert!(close(a.get_untracked(), 1.0) && close(b.get_untracked(), 0.0));
1959 assert!(!b.is_animating());
1960 frames.step(0.1);
1962 assert!(close(b.get_untracked(), 0.5), "{}", b.get_untracked());
1963 frames.step(0.06);
1964 assert!(playing.is_finished() && close(b.get_untracked(), 1.0));
1965 }
1966
1967 #[test]
1968 fn a_stagger_starts_each_step_a_gap_after_the_one_before() {
1969 let frames = Frames::new();
1970 let values: Vec<Animated> = (0..3).map(|_| Animated::on(Frames::clock(), 0.0)).collect();
1971 let playing = Animation::stagger(
1972 100,
1973 values
1974 .iter()
1975 .map(|&v| Animation::timing(v, 1.0, 200, Easing::Linear)),
1976 )
1977 .start();
1978 frames.step(0.0);
1979 frames.step(0.2);
1980 let at: Vec<f64> = values.iter().map(|v| v.get_untracked()).collect();
1981 assert!(
1982 close(at[0], 1.0) && close(at[1], 0.5) && close(at[2], 0.0),
1983 "{at:?}"
1984 );
1985 frames.step(0.2);
1986 assert!(playing.is_finished());
1987 assert!(values.iter().all(|v| close(v.get_untracked(), 1.0)));
1988 }
1989
1990 #[test]
1991 fn repeat_plays_a_number_of_times_and_looped_never_ends() {
1992 let frames = Frames::new();
1993 let v = Animated::on(Frames::clock(), 0.0);
1994 let there_and_back = Animation::sequence([
1995 Animation::timing(v, 1.0, 100, Easing::Linear),
1996 Animation::timing(v, 0.0, 100, Easing::Linear),
1997 ]);
1998 assert!(!there_and_back.is_endless());
1999 let twice = there_and_back.clone().repeat(2).start();
2000 frames.step(0.0);
2001 frames.step(0.25); assert!(close(v.get_untracked(), 0.5), "{}", v.get_untracked());
2003 assert!(twice.is_running());
2004 frames.step(0.2);
2005 assert!(twice.is_finished() && close(v.get_untracked(), 0.0));
2006
2007 let pulse = there_and_back.looped();
2008 assert!(pulse.is_endless());
2009 let playing = pulse.start();
2010 frames.run(3.0);
2011 assert!(playing.is_running());
2012 assert!(playing.stop());
2013 assert_eq!(playing.outcome(), Some(Outcome::Stopped));
2014 assert!(!v.is_animating() && Frames::idle());
2015 assert!(!playing.stop(), "stopping twice is harmless");
2016 }
2017
2018 #[test]
2019 fn a_spring_settles_carries_velocity_and_a_decay_coasts_to_its_rest() {
2020 let frames = Frames::new();
2021 let v = Animated::on(Frames::clock(), 0.0);
2022 let playing = Animation::spring(v, 100.0, Spring::new(180.0, 8.0)).start();
2023 let mut peak = 0.0_f64;
2024 frames.step(0.0);
2025 for _ in 0..600 {
2026 frames.step(1.0 / 60.0);
2027 peak = peak.max(v.get_untracked());
2028 }
2029 assert!(peak > 110.0, "a loose spring overshoots: {peak}");
2030 assert!(playing.is_finished() && close(v.get_untracked(), 100.0));
2031 assert!(close(v.velocity.get_untracked(), 0.0));
2032
2033 v.set(0.0);
2035 v.set_velocity(-2000.0);
2036 let back = Animation::spring(v, 0.0, Spring::new(180.0, 26.0)).start();
2037 frames.step(0.0);
2038 frames.step(1.0 / 60.0);
2039 assert!(v.get_untracked() < -10.0);
2040 frames.run(5.0);
2041 assert!(back.is_finished() && close(v.get_untracked(), 0.0));
2042
2043 let decay = Decay { rate: 0.992 };
2044 v.set(0.0);
2045 v.set_velocity(1000.0);
2046 let rest = decay.rest(SpringState {
2047 value: 0.0,
2048 velocity: 1000.0,
2049 });
2050 assert!((rest - 124.5).abs() < 0.1, "{rest}");
2051 let fling = Animation::decay(v, decay).start();
2052 assert!(close(v.target(), rest));
2053 frames.run(10.0);
2054 assert!(fling.is_finished());
2055 assert!(
2056 (v.get_untracked() - rest).abs() < 1.0,
2057 "{}",
2058 v.get_untracked()
2059 );
2060 }
2061
2062 #[test]
2063 fn the_latest_step_owns_a_value_and_set_takes_it_from_any() {
2064 let frames = Frames::new();
2065 let v = Animated::on(Frames::clock(), 0.0);
2066 let slow = Animation::timing(v, 100.0, 1000, Easing::Linear).start();
2067 frames.step(0.0);
2068 frames.step(0.1);
2069 let quick = Animation::timing(v, -10.0, 100, Easing::Linear).start();
2070 frames.step(0.0);
2071 frames.step(0.2);
2072 assert!(quick.is_finished() && close(v.get_untracked(), -10.0));
2073 frames.run(1.0);
2075 assert!(slow.is_finished() && close(v.get_untracked(), -10.0));
2076
2077 let again = Animation::timing(v, 100.0, 1000, Easing::Linear).start();
2078 frames.step(0.0);
2079 frames.step(0.1);
2080 v.set(7.0);
2081 assert!(!v.is_animating());
2082 frames.run(1.5);
2083 assert!(again.is_finished() && close(v.get_untracked(), 7.0));
2084 }
2085
2086 #[test]
2087 fn reset_puts_values_back_and_jump_to_end_lands_them() {
2088 let frames = Frames::new();
2089 let (a, b) = (
2090 Animated::on(Frames::clock(), 1.0),
2091 Animated::on(Frames::clock(), 2.0),
2092 );
2093 let animation = Animation::parallel([
2094 Animation::timing(a, 10.0, 100, Easing::Linear),
2095 Animation::sequence([
2096 Animation::delay(50),
2097 Animation::spring(b, 20.0, Spring::default()),
2098 ]),
2099 ]);
2100 let playing = animation.start();
2101 frames.step(0.0);
2102 frames.step(0.08);
2103 assert!(a.get_untracked() > 1.0 && b.get_untracked() > 2.0);
2104 playing.reset();
2105 assert_eq!(playing.outcome(), Some(Outcome::Stopped));
2106 assert!(close(a.get_untracked(), 1.0) && close(b.get_untracked(), 2.0));
2107 assert!(Frames::idle());
2108 animation.jump_to_end();
2109 assert!(close(a.get_untracked(), 10.0) && close(b.get_untracked(), 20.0));
2110 }
2111
2112 #[test]
2113 fn an_animation_stops_when_a_value_it_moves_is_disposed() {
2114 let frames = Frames::new();
2115 let scope = day_reactive::Scope::root().create_child();
2116 let v = scope.enter(|| Animated::on(Frames::clock(), 0.0));
2117 let kept = Animated::on(Frames::clock(), 0.0);
2118 let playing = Animation::parallel([
2119 Animation::timing(v, 1.0, 1000, Easing::Linear),
2120 Animation::timing(kept, 1.0, 1000, Easing::Linear),
2121 ])
2122 .looped()
2123 .start();
2124 frames.step(0.0);
2125 frames.step(0.1);
2126 scope.dispose();
2127 frames.step(0.1);
2128 assert_eq!(playing.outcome(), Some(Outcome::Stopped));
2129 assert!(!kept.is_animating() && Frames::idle());
2130 let late = Animation::timing(v, 1.0, 100, Easing::Linear).start_on(Frames::clock());
2132 assert_eq!(late.outcome(), Some(Outcome::Stopped));
2133 }
2134
2135 #[test]
2136 fn a_group_that_cannot_start_lets_go_of_what_it_started() {
2137 let _frames = Frames::new();
2138 let scope = day_reactive::Scope::root().create_child();
2139 let gone = scope.enter(|| Animated::on(Frames::clock(), 0.0));
2140 scope.dispose();
2141 let step = |v: Animated<f64>| Animation::timing(v, 1.0, 100, Easing::Linear);
2142 for gone_at in 0..3 {
2144 let live: Vec<Animated<f64>> =
2145 (0..2).map(|_| Animated::on(Frames::clock(), 0.0)).collect();
2146 let mut parts: Vec<Animation> = live.iter().map(|v| step(*v)).collect();
2147 parts.insert(gone_at, step(gone));
2148 let nested = Animation::parallel([
2149 Animation::sequence([step(live[0]), step(live[1])]),
2150 Animation::parallel(parts),
2151 ]);
2152 for playing in [
2153 nested.start(),
2154 Animation::parallel([step(live[1]), step(gone)]).start(),
2155 ] {
2156 assert_eq!(playing.outcome(), Some(Outcome::Stopped), "at {gone_at}");
2157 assert!(
2158 live.iter()
2159 .all(|v| !v.is_animating() && close(v.get_untracked(), 0.0)),
2160 "a live value stayed claimed (gone at {gone_at})"
2161 );
2162 }
2163 }
2164 assert!(Frames::idle());
2165 }
2166
2167 #[test]
2168 fn a_repeat_of_zero_plays_nothing_and_a_late_frame_plays_every_pass_it_covers() {
2169 let frames = Frames::new();
2170 let v = Animated::on(Frames::clock(), 0.0);
2171 let none = Animation::timing(v, 10.0, 100, Easing::Linear).repeat(0);
2172 assert!(!none.is_endless());
2173 let playing = none.start();
2174 frames.step(0.0);
2175 frames.step(0.2);
2176 assert_eq!(playing.outcome(), Some(Outcome::Finished));
2177 assert!(close(v.get_untracked(), 0.0) && !v.is_animating());
2178
2179 let ten = Animation::delay(10).repeat(10).start_on(Frames::clock());
2181 frames.step(0.0);
2182 frames.step(0.2);
2183 assert_eq!(ten.outcome(), Some(Outcome::Finished));
2184
2185 let ticks = Animated::on(Frames::clock(), 0.0);
2187 let counted = Animation::sequence([
2188 Animation::delay(1),
2189 Animation::timing(ticks, 1.0, 0, Easing::Linear),
2190 ])
2191 .repeat(1000)
2192 .start();
2193 frames.step(0.0);
2194 frames.step(2.0);
2195 assert_eq!(counted.outcome(), Some(Outcome::Finished));
2196
2197 let after = Animation::sequence([Animation::delay(0).repeat(100), Animation::delay(100)])
2200 .start_on(Frames::clock());
2201 frames.step(0.0);
2202 frames.step(0.2);
2203 assert_eq!(after.outcome(), Some(Outcome::Finished));
2204
2205 let forever = Animation::delay(0).looped().start_on(Frames::clock());
2207 frames.step(0.0);
2208 frames.step(0.1);
2209 assert!(forever.is_running());
2210 assert!(forever.stop() && Frames::idle());
2211 }
2212
2213 #[test]
2214 fn the_handle_resolves_for_callbacks_and_for_tasks() {
2215 let frames = Frames::new();
2216 let v = Animated::on(Frames::clock(), 0.0);
2217 let playing = Animation::timing(v, 1.0, 100, Easing::Linear).start();
2218 let heard = Rc::new(Cell::new(None));
2219 let h = heard.clone();
2220 playing.on_end(move |outcome| h.set(Some(outcome)));
2221 let mut task = Box::pin(playing.clone());
2222 let waker = std::task::Waker::noop();
2223 let mut cx = Context::from_waker(waker);
2224 assert!(task.as_mut().poll(&mut cx).is_pending());
2225 frames.run(0.2);
2226 assert_eq!(heard.get(), Some(Outcome::Finished));
2227 assert_eq!(task.as_mut().poll(&mut cx), Poll::Ready(Outcome::Finished));
2228 let late = Rc::new(Cell::new(false));
2230 let l = late.clone();
2231 playing.on_end(move |_| l.set(true));
2232 assert!(late.get());
2233 }
2234
2235 #[test]
2236 fn every_write_of_a_frame_reaches_a_binding_in_one_pass() {
2237 let frames = Frames::new();
2238 let values: Vec<Animated> = (0..4).map(|_| Animated::on(Frames::clock(), 0.0)).collect();
2239 let runs = Rc::new(Cell::new(0));
2240 let (r, read) = (runs.clone(), values.clone());
2241 day_reactive::Effect::new(move || {
2242 let _sum: f64 = read.iter().map(|v| v.get()).sum();
2244 r.set(r.get() + 1);
2245 });
2246 day_reactive::flush_sync();
2247 let before = runs.get();
2248 let playing = Animation::parallel(
2249 values
2250 .iter()
2251 .map(|&v| Animation::timing(v, 1.0, 1000, Easing::Linear)),
2252 )
2253 .start();
2254 frames.step(0.0);
2255 let started = runs.get();
2256 assert!(started <= before + 2);
2257 for _ in 0..10 {
2258 frames.step(1.0 / 60.0);
2259 }
2260 assert_eq!(runs.get() - started, 10);
2262 playing.stop();
2263 }
2264
2265 #[test]
2266 fn interpolation_clamps_extends_and_blends_colors() {
2267 let fade = Interpolation::new([0.0, 120.0], [1.0, 0.0]);
2268 assert!(close(fade.at(60.0), 0.5));
2269 assert!(close(fade.at(-30.0), 1.0) && close(fade.at(500.0), 0.0));
2270 let open = fade.clone().extend();
2271 assert!(close(open.at(-60.0), 1.5) && close(open.at(240.0), -1.0));
2272 let one_way = Interpolation::new([0.0, 1.0], [0.0, 10.0]).extend_end();
2273 assert!(close(one_way.at(-1.0), 0.0) && close(one_way.at(2.0), 20.0));
2274
2275 let steps = Interpolation::new([0.0, 1.0, 3.0], [0.0, 10.0, 30.0]);
2276 assert!(close(steps.at(0.5), 5.0) && close(steps.at(2.0), 20.0));
2277 assert!(close(steps.at(1.0), 10.0) && close(steps.at(9.0), 30.0));
2278 assert!(close(Interpolation::new([4.0], [7.0]).at(100.0), 7.0));
2279
2280 let (blue, yellow) = (Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0));
2281 let heat = Interpolation::new([0.0, 1.0], [blue, yellow]);
2282 assert_eq!(heat.at(0.0), blue);
2283 assert_eq!(heat.at(1.0), yellow);
2284 assert_eq!(heat.at(0.5), crate::tween::mix_oklab(blue, yellow, 0.5));
2285 assert_eq!(heat.at(7.0), yellow);
2286
2287 let _frames = Frames::new();
2288 let scroll = Animated::on(Frames::clock(), 60.0);
2289 let opacity = scroll.interpolate([0.0, 120.0], [1.0, 0.0]);
2290 assert!(close(opacity(), 0.5));
2291 scroll.set(120.0);
2292 assert!(close(opacity(), 0.0));
2293 }
2294
2295 #[test]
2296 fn a_spring_and_its_curve_describe_the_same_motion() {
2297 let spring = Spring::from_response(0.5, 0.4);
2298 let Curve::Spring { response, damping } = spring.curve() else {
2299 panic!("a spring's curve is a spring");
2300 };
2301 assert!(close(response, 0.5) && close(damping, 0.4));
2302 let spec = AnimSpec::spring(0.5, 0.4);
2304 let mut state = SpringState::default();
2305 for i in 1..=60 {
2306 spring.step(&mut state, 1.0, 0.01);
2307 let exact = spec.curve.fraction(f64::from(i) * 0.01, 0.0);
2308 assert!(
2309 (state.value - exact).abs() < 0.01,
2310 "{i}: {} {exact}",
2311 state.value
2312 );
2313 }
2314 }
2315}