1use alloc::boxed::Box;
2use alloc::vec::Vec;
3use core::time::Duration;
4
5use crate::color::Color;
6use crate::transform::{Transform, sin_cos};
7
8const TWO_PI: f32 = 2.0 * core::f32::consts::PI;
9
10#[allow(clippy::manual_clamp)]
11fn clamp01(t: f32) -> f32 {
12 if t < 0.0 {
13 0.0
14 } else if t > 1.0 {
15 1.0
16 } else {
17 t
18 }
19}
20
21fn manual_exp(x: f32) -> f32 {
25 let mut term = 1.0;
26 let mut sum = 1.0;
27 let mut n = 1.0;
28 while n < 16.0 {
29 term *= x / n;
30 sum += term;
31 n += 1.0;
32 }
33 sum
34}
35
36pub trait Animatable: Clone {
38 fn lerp(&self, other: &Self, t: f32) -> Self;
39}
40
41impl Animatable for f32 {
42 fn lerp(&self, other: &Self, t: f32) -> Self {
43 let t = clamp01(t);
44 *self + (*other - *self) * t
45 }
46}
47
48impl Animatable for Color {
49 fn lerp(&self, other: &Self, t: f32) -> Self {
50 let t = clamp01(t);
51 let inv = 1.0 - t;
52 let r = self.r as f32 / 255.0 * inv + other.r as f32 / 255.0 * t;
53 let g = self.g as f32 / 255.0 * inv + other.g as f32 / 255.0 * t;
54 let b = self.b as f32 / 255.0 * inv + other.b as f32 / 255.0 * t;
55 let a = self.a as f32 / 255.0 * inv + other.a as f32 / 255.0 * t;
56 Color::from_f32(r, g, b, a)
57 }
58}
59
60impl Animatable for Transform {
61 fn lerp(&self, other: &Self, t: f32) -> Self {
62 let t = clamp01(t);
63 let inv = 1.0 - t;
64 Transform {
65 m11: self.m11 * inv + other.m11 * t,
66 m12: self.m12 * inv + other.m12 * t,
67 m21: self.m21 * inv + other.m21 * t,
68 m22: self.m22 * inv + other.m22 * t,
69 m31: self.m31 * inv + other.m31 * t,
70 m32: self.m32 * inv + other.m32 * t,
71 }
72 }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Default)]
77pub enum AnimationCurve {
78 #[default]
79 Linear,
80 EaseInOut,
81 Spring,
82}
83
84impl AnimationCurve {
85 pub fn ease(&self, t: f32) -> f32 {
90 let t = clamp01(t);
91 match self {
92 AnimationCurve::Linear => t,
93 AnimationCurve::EaseInOut => t * t * (3.0 - 2.0 * t),
94 AnimationCurve::Spring => {
95 const DAMPING: f32 = 6.0;
96 const FREQUENCY: f32 = 3.0;
97 let omega = TWO_PI * FREQUENCY;
98 let (sin, cos) = sin_cos(omega * t);
99 let envelope = manual_exp(-DAMPING * t);
102 let oscillation = cos + (DAMPING / omega) * sin;
103 1.0 - envelope * oscillation
104 }
105 }
106 }
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Default)]
111pub enum AnimationState {
112 #[default]
113 Idle,
114 Running,
115 Paused,
116 Completed,
117 Stopped,
118}
119
120#[derive(Debug, Clone, Copy, PartialEq)]
122pub enum AnimationTick<T: Animatable> {
123 Running(T),
124 Completed(T),
125}
126
127pub struct Animation<T: Animatable> {
129 from: T,
130 to: T,
131 duration: Duration,
132 elapsed: Duration,
133 curve: AnimationCurve,
134 state: AnimationState,
135 on_complete: Option<Box<dyn FnOnce()>>,
136}
137
138impl<T: Animatable> Animation<T> {
139 pub fn new(from: T, to: T, duration: Duration) -> Self {
141 Self {
142 from,
143 to,
144 duration,
145 elapsed: Duration::ZERO,
146 curve: AnimationCurve::Linear,
147 state: AnimationState::Idle,
148 on_complete: None,
149 }
150 }
151
152 pub fn with_curve(mut self, curve: AnimationCurve) -> Self {
154 self.curve = curve;
155 self
156 }
157
158 pub fn on_complete<F: FnOnce() + 'static>(mut self, f: F) -> Self {
160 self.on_complete = Some(Box::new(f));
161 self
162 }
163
164 pub fn start(&mut self) {
166 self.elapsed = Duration::ZERO;
167 self.state = AnimationState::Running;
168 }
169
170 pub fn stop(&mut self) {
173 self.state = AnimationState::Stopped;
174 }
175
176 pub fn pause(&mut self) {
178 if self.state == AnimationState::Running {
179 self.state = AnimationState::Paused;
180 }
181 }
182
183 pub fn resume(&mut self) {
185 if self.state == AnimationState::Paused {
186 self.state = AnimationState::Running;
187 }
188 }
189
190 pub fn restart(&mut self) {
192 self.start();
193 }
194
195 pub fn state(&self) -> AnimationState {
197 self.state
198 }
199
200 pub fn elapsed(&self) -> Duration {
202 self.elapsed
203 }
204
205 pub fn duration(&self) -> Duration {
207 self.duration
208 }
209
210 pub fn value(&self) -> T {
212 let t = normalized_time(self.elapsed, self.duration);
213 self.from.lerp(&self.to, self.curve.ease(t))
214 }
215
216 pub fn tick(&mut self, dt: Duration) -> Option<AnimationTick<T>> {
221 if self.state != AnimationState::Running {
222 return None;
223 }
224
225 self.elapsed = self.elapsed.saturating_add(dt);
226
227 if self.elapsed >= self.duration || self.duration.is_zero() {
228 self.elapsed = self.duration;
229 self.state = AnimationState::Completed;
230 let value = self.to.clone();
231 if let Some(cb) = self.on_complete.take() {
232 cb();
233 }
234 Some(AnimationTick::Completed(value))
235 } else {
236 Some(AnimationTick::Running(self.value()))
237 }
238 }
239}
240
241fn normalized_time(elapsed: Duration, duration: Duration) -> f32 {
242 if duration.is_zero() {
243 return 1.0;
244 }
245 elapsed.as_secs_f32() / duration.as_secs_f32()
246}
247
248pub type AnimationId = u64;
250
251#[derive(Debug, Clone, PartialEq)]
253pub enum AnimationEvent<T: Animatable> {
254 Value { id: AnimationId, value: T },
255 Completed { id: AnimationId, value: T },
256}
257
258struct ActiveAnimation<T: Animatable> {
259 id: AnimationId,
260 animation: Animation<T>,
261}
262
263pub struct AnimationController<T: Animatable> {
268 active: Vec<ActiveAnimation<T>>,
269 removals: Vec<usize>,
270 next_id: AnimationId,
271}
272
273impl<T: Animatable> Default for AnimationController<T> {
274 fn default() -> Self {
275 Self::new()
276 }
277}
278
279impl<T: Animatable> AnimationController<T> {
280 pub fn new() -> Self {
282 Self {
283 active: Vec::new(),
284 removals: Vec::new(),
285 next_id: 1,
286 }
287 }
288
289 pub fn start(&mut self, mut animation: Animation<T>) -> AnimationId {
291 animation.start();
292 let id = self.next_id;
293 self.next_id += 1;
294 self.active.push(ActiveAnimation { id, animation });
295 id
296 }
297
298 pub fn stop(&mut self, id: AnimationId) -> bool {
300 if let Some(entry) = self.active.iter_mut().find(|e| e.id == id) {
301 entry.animation.stop();
302 return true;
303 }
304 false
305 }
306
307 pub fn pause(&mut self, id: AnimationId) -> bool {
309 if let Some(entry) = self.active.iter_mut().find(|e| e.id == id) {
310 entry.animation.pause();
311 return true;
312 }
313 false
314 }
315
316 pub fn resume(&mut self, id: AnimationId) -> bool {
318 if let Some(entry) = self.active.iter_mut().find(|e| e.id == id) {
319 entry.animation.resume();
320 return true;
321 }
322 false
323 }
324
325 pub fn restart(&mut self, id: AnimationId) -> bool {
327 if let Some(entry) = self.active.iter_mut().find(|e| e.id == id) {
328 entry.animation.restart();
329 return true;
330 }
331 false
332 }
333
334 pub fn len(&self) -> usize {
336 self.active.len()
337 }
338
339 pub fn is_empty(&self) -> bool {
341 self.active.is_empty()
342 }
343
344 pub fn tick<F: FnMut(AnimationEvent<T>)>(&mut self, dt: Duration, mut on_event: F) {
349 self.removals.clear();
350
351 for (index, entry) in self.active.iter_mut().enumerate() {
352 match entry.animation.tick(dt) {
353 Some(AnimationTick::Running(value)) => {
354 on_event(AnimationEvent::Value {
355 id: entry.id,
356 value,
357 });
358 }
359 Some(AnimationTick::Completed(value)) => {
360 on_event(AnimationEvent::Completed {
361 id: entry.id,
362 value,
363 });
364 self.removals.push(index);
365 }
366 None => {
367 if entry.animation.state() == AnimationState::Stopped {
368 self.removals.push(index);
369 }
370 }
371 }
372 }
373
374 for index in self.removals.iter().rev().copied() {
376 self.active.swap_remove(index);
377 }
378 }
379}
380
381#[cfg(test)]
382mod tests {
383 use super::*;
384 use alloc::rc::Rc;
385 use alloc::vec::Vec;
386 use core::cell::Cell;
387
388 #[test]
389 fn linear_animation_completes() {
390 let completed = Rc::new(Cell::new(false));
391 let cb = completed.clone();
392 let mut anim = Animation::new(0.0_f32, 1.0_f32, Duration::from_millis(100))
393 .on_complete(move || cb.set(true));
394 anim.start();
395
396 let result = anim.tick(Duration::from_millis(100));
397 assert!(matches!(result, Some(AnimationTick::Completed(1.0))));
398 assert!(completed.get());
399 assert_eq!(anim.state(), AnimationState::Completed);
400 }
401
402 #[test]
403 fn linear_animation_progresses_each_frame() {
404 let mut anim = Animation::new(0.0_f32, 10.0_f32, Duration::from_millis(100));
405 anim.start();
406
407 let half = anim.tick(Duration::from_millis(50));
408 assert!(matches!(half, Some(AnimationTick::Running(v)) if v == 5.0));
409 assert_eq!(anim.state(), AnimationState::Running);
410 }
411
412 #[test]
413 fn ease_in_out_bounds() {
414 let curve = AnimationCurve::EaseInOut;
415 let steps = 11;
416 for i in 0..steps {
417 let t = i as f32 / (steps - 1) as f32;
418 let v = curve.ease(t);
419 assert!(
420 (0.0..=1.0).contains(&v),
421 "ease-in-out produced out-of-bounds value {v} at t={t}"
422 );
423 }
424 }
425
426 #[test]
427 fn spring_overshoots() {
428 let curve = AnimationCurve::Spring;
429 let v = curve.ease(0.2);
431 assert!(v > 1.1, "expected spring overshoot above 1.1, got {v}");
432 }
433
434 #[test]
435 fn cancellation_removes_animation() {
436 let mut controller = AnimationController::<f32>::new();
437 let id = controller.start(Animation::new(0.0, 1.0, Duration::from_millis(100)));
438 assert_eq!(controller.len(), 1);
439
440 assert!(controller.stop(id));
441 let mut events = Vec::new();
442 controller.tick(Duration::from_millis(50), |e| events.push(e));
443 assert!(events.is_empty());
444 assert!(controller.is_empty());
445 }
446
447 #[test]
448 fn restart_resets_and_completes() {
449 let mut controller = AnimationController::<f32>::new();
450 let id = controller.start(Animation::new(0.0, 1.0, Duration::from_millis(100)));
451
452 let mut events = Vec::new();
453 controller.tick(Duration::from_millis(60), |e| events.push(e));
454 assert_eq!(events.len(), 1);
455 assert!(matches!(events[0], AnimationEvent::Value { value, .. } if value > 0.0));
456
457 assert!(controller.restart(id));
458 events.clear();
459 controller.tick(Duration::from_millis(100), |e| events.push(e));
460 assert!(matches!(
461 events.last(),
462 Some(AnimationEvent::Completed { value: 1.0, .. })
463 ));
464 }
465
466 #[test]
467 fn concurrent_independent_animations() {
468 let mut controller = AnimationController::<f32>::new();
469 let short = controller.start(Animation::new(0.0, 1.0, Duration::from_millis(50)));
470 let long = controller.start(Animation::new(10.0, 20.0, Duration::from_millis(100)));
471
472 let mut events = Vec::new();
473 controller.tick(Duration::from_millis(60), |e| events.push(e));
474
475 let short_completed = events
476 .iter()
477 .any(|e| matches!(e, AnimationEvent::Completed { id, value: 1.0 } if *id == short));
478 let long_running = events
479 .iter()
480 .any(|e| matches!(e, AnimationEvent::Value { id, value } if *id == long && *value > 10.0 && *value < 20.0));
481
482 assert!(short_completed, "short animation should have completed");
483 assert!(long_running, "long animation should still be running");
484
485 events.clear();
486 controller.tick(Duration::from_millis(50), |e| events.push(e));
487 assert!(
488 events
489 .iter()
490 .any(|e| matches!(e, AnimationEvent::Completed { id, value: 20.0 } if *id == long))
491 );
492 assert!(controller.is_empty());
493 }
494
495 #[test]
496 fn color_animatable_interpolates() {
497 let a = Color::from_rgb(0, 0, 0);
498 let b = Color::from_rgb(255, 255, 255);
499 let mid = a.lerp(&b, 0.5);
500 assert_eq!(mid, Color::from_rgb(128, 128, 128));
501 }
502
503 #[test]
504 fn transform_animatable_interpolates() {
505 let a = Transform::identity();
506 let b = Transform::translate(10.0, 20.0);
507 let mid = a.lerp(&b, 0.5);
508 assert_eq!(mid, Transform::translate(5.0, 10.0));
509 }
510
511 #[test]
512 fn pause_and_resume_preserves_state() {
513 let mut anim = Animation::new(0.0_f32, 1.0, Duration::from_millis(100));
514 anim.start();
515 anim.tick(Duration::from_millis(40));
516 let value_before = anim.value();
517
518 anim.pause();
519 anim.tick(Duration::from_millis(100));
520 assert_eq!(anim.value(), value_before);
521 assert_eq!(anim.state(), AnimationState::Paused);
522
523 anim.resume();
524 let result = anim.tick(Duration::from_millis(60));
525 assert!(matches!(result, Some(AnimationTick::Completed(1.0))));
526 }
527}