1use std::collections::HashMap;
8
9#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
10pub enum MotionPreference {
11 #[default]
12 Full,
13 Reduced,
14}
15
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
17pub enum MotionScheme {
18 #[default]
19 Standard,
20 Expressive,
21}
22impl MotionScheme {
23 pub fn spatial(self) -> Spring {
24 match self {
25 Self::Standard => Spring::SPATIAL,
26 Self::Expressive => Spring {
27 stiffness: 380.0,
28 damping: 0.8,
29 },
30 }
31 }
32 pub fn fast_spatial(self) -> Spring {
33 match self {
34 Self::Standard => Spring {
35 stiffness: 1400.0,
36 damping: 0.9,
37 },
38 Self::Expressive => Spring {
39 stiffness: 800.0,
40 damping: 0.6,
41 },
42 }
43 }
44 pub fn slow_spatial(self) -> Spring {
45 match self {
46 Self::Standard => Spring {
47 stiffness: 300.0,
48 damping: 0.9,
49 },
50 Self::Expressive => Spring {
51 stiffness: 200.0,
52 damping: 0.8,
53 },
54 }
55 }
56}
57
58#[derive(Clone, Copy, Debug)]
60pub struct Spring {
61 stiffness: f64,
62 damping: f64,
63}
64
65impl Spring {
66 pub const PROGRESS: Self = Self {
67 stiffness: 50.0,
68 damping: 1.0,
69 };
70 pub const EFFECTS: Self = Self {
71 stiffness: 1600.0,
72 damping: 1.0,
73 };
74 pub const SPATIAL: Self = Self {
76 stiffness: 700.0,
77 damping: 0.9,
78 };
79 pub const FAST_EFFECTS: Self = Self {
80 stiffness: 3800.0,
81 damping: 1.0,
82 };
83}
84
85#[derive(Clone, Copy, Debug)]
86struct Track {
87 value: f64,
88 velocity: f64,
89 target: f64,
90 time: f64,
91 seen: u64,
92 spring: Spring,
93}
94
95impl Track {
96 fn advance(&mut self, time: f64, spring: Spring) {
97 let dt = (time - self.time).max(0.0);
98 self.time = time;
99 if dt == 0.0 {
100 return;
101 }
102 let omega = spring.stiffness.max(1.0).sqrt();
105 let displacement = self.value - self.target;
106 if spring.damping < 1.0 {
107 let rate = spring.damping * omega;
108 let frequency = omega * (1.0 - spring.damping * spring.damping).sqrt();
109 let c = (self.velocity + rate * displacement) / frequency;
110 let phase = frequency * dt;
111 let wave = displacement * phase.cos() + c * phase.sin();
112 let decay = (-rate * dt).exp();
113 self.value = self.target + wave * decay;
114 self.velocity =
115 (frequency * (-displacement * phase.sin() + c * phase.cos()) - rate * wave) * decay;
116 } else {
117 let c = self.velocity + omega * displacement;
118 let decay = (-omega * dt).exp();
119 self.value = self.target + (displacement + c * dt) * decay;
120 self.velocity = (self.velocity - omega * c * dt) * decay;
121 }
122 if (self.value - self.target).abs() < 0.0005 && self.velocity.abs() < 0.01 {
123 self.value = self.target;
124 self.velocity = 0.0;
125 }
126 }
127 fn moving(self) -> bool {
128 self.value != self.target || self.velocity != 0.0
129 }
130}
131
132pub struct Motion {
135 tracks: HashMap<(u64, u8), Track>,
136 tweens: HashMap<(u64, u8), (crate::timing::Tween, u64)>,
137 clocks: HashMap<(u64, u8), (f64, u64)>,
138 capacity: usize,
139 epoch: u64,
140 time: f64,
141 preference: MotionPreference,
142}
143
144impl Default for Motion {
145 fn default() -> Self {
146 Self::new(4096)
147 }
148}
149
150impl Motion {
151 pub fn new(capacity: usize) -> Self {
152 Self {
153 tracks: HashMap::new(),
154 tweens: HashMap::new(),
155 clocks: HashMap::new(),
156 capacity,
157 epoch: 0,
158 time: 0.0,
159 preference: MotionPreference::Full,
160 }
161 }
162 pub fn begin(&mut self, time: f64, preference: MotionPreference) {
163 if time.is_finite() {
164 self.time = time.max(self.time);
165 }
166 self.preference = preference;
167 self.epoch = self.epoch.wrapping_add(1);
168 }
169 pub fn effect(
172 &mut self,
173 id: u64,
174 property: u8,
175 target: f32,
176 initial: f32,
177 spring: Spring,
178 ) -> f32 {
179 let target = if target.is_finite() {
180 target.clamp(0.0, 1.0) as f64
181 } else {
182 0.0
183 };
184 let initial = if initial.is_finite() {
185 initial.clamp(0.0, 1.0) as f64
186 } else {
187 target
188 };
189 let key = (id, property);
190 if !self.tracks.contains_key(&key)
191 && self.tracks.len() + self.tweens.len() + self.clocks.len() >= self.capacity
192 {
193 return target as f32;
194 }
195 let track = self.tracks.entry(key).or_insert(Track {
196 value: initial,
197 velocity: 0.0,
198 target: initial,
199 time: self.time,
200 seen: self.epoch,
201 spring,
202 });
203 track.advance(self.time, track.spring);
204 track.spring = spring;
205 track.target = target;
206 track.seen = self.epoch;
207 if self.preference == MotionPreference::Reduced {
210 track.value = target;
211 track.velocity = 0.0;
212 }
213 track.value.clamp(0.0, 1.0) as f32
214 }
215 #[allow(clippy::too_many_arguments)]
216 pub fn tween(
217 &mut self,
218 id: u64,
219 property: u8,
220 target: f32,
221 initial: f32,
222 enter: crate::timing::TweenSpec,
223 exit: crate::timing::TweenSpec,
224 ) -> f32 {
225 self.tween_inner(id, property, target, initial, enter, exit, false)
226 }
227 #[allow(clippy::too_many_arguments)]
228 pub(crate) fn css_tween(
229 &mut self,
230 id: u64,
231 property: u8,
232 target: f32,
233 initial: f32,
234 enter: crate::timing::TweenSpec,
235 exit: crate::timing::TweenSpec,
236 ) -> f32 {
237 self.tween_inner(id, property, target, initial, enter, exit, true)
238 }
239 #[allow(clippy::too_many_arguments)]
240 fn tween_inner(
241 &mut self,
242 id: u64,
243 property: u8,
244 target: f32,
245 initial: f32,
246 enter: crate::timing::TweenSpec,
247 exit: crate::timing::TweenSpec,
248 css: bool,
249 ) -> f32 {
250 let key = (id, property);
251 let target = if target.is_finite() {
252 target.clamp(0.0, 1.0)
253 } else {
254 0.0
255 };
256 if !self.tweens.contains_key(&key)
257 && self.tracks.len() + self.tweens.len() + self.clocks.len() >= self.capacity
258 {
259 return target;
260 }
261 let (track, seen) = self.tweens.entry(key).or_insert((
262 crate::timing::Tween::at(if initial.is_finite() {
263 initial.clamp(0.0, 1.0)
264 } else {
265 target
266 }),
267 self.epoch,
268 ));
269 *seen = self.epoch;
270 let sample = if css {
271 crate::timing::Tween::sample_css
272 } else {
273 crate::timing::Tween::sample
274 };
275 sample(
276 track,
277 self.time,
278 target,
279 enter,
280 exit,
281 self.preference == MotionPreference::Reduced,
282 )
283 }
284 pub fn elapsed(&mut self, id: u64, property: u8) -> f64 {
285 let key = (id, property);
286 if !self.clocks.contains_key(&key) && self.retained_properties() >= self.capacity {
287 return self.time;
288 }
289 let (start, seen) = self.clocks.entry(key).or_insert((self.time, self.epoch));
290 *seen = self.epoch;
291 (self.time - *start).max(0.0)
292 }
293 pub fn pause_clocks(&mut self) {
294 self.clocks.clear();
295 }
296 pub fn finish(&mut self) {
297 let epoch = self.epoch;
298 self.tracks.retain(|_, track| track.seen == epoch);
299 self.tweens.retain(|_, (_, seen)| *seen == epoch);
300 self.clocks.retain(|_, (_, seen)| *seen == epoch);
301 }
302 pub fn is_animating(&self) -> bool {
303 self.tracks.values().any(|track| track.moving())
304 || self.tweens.values().any(|(track, _)| track.moving())
305 }
306 pub fn retained_properties(&self) -> usize {
307 self.tracks.len() + self.tweens.len() + self.clocks.len()
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314 #[test]
315 fn standard_spatial_spring_is_animated_stable_and_frame_independent() {
316 fn run(times: &[f64]) -> f32 {
317 let mut m = Motion::default();
318 m.begin(0.0, MotionPreference::Full);
319 m.effect(1, 0, 1.0, 0.0, Spring::SPATIAL);
320 let mut value = 0.0;
321 for &time in times {
322 m.begin(time, MotionPreference::Full);
323 value = m.effect(1, 0, 1.0, 0.0, Spring::SPATIAL);
324 }
325 value
326 }
327 let a = run(&[0.1]);
328 let b = run(&[0.02, 0.04, 0.06, 0.08, 0.1]);
329 assert!(a > 0.0 && a < 1.0);
330 assert!((a - b).abs() < 0.00001);
331 assert_eq!(run(&[3.0]), 1.0);
332 }
333 #[test]
334 fn springs_tweens_and_clocks_share_one_bound_and_removed_tracks_are_pruned() {
335 let mut m = Motion::new(4);
336 m.begin(0.0, MotionPreference::Full);
337 let s = crate::timing::TweenSpec::new(0.5, crate::timing::Easing::Linear);
338 for i in 0..20 {
339 m.tween(i, 1, 1.0, 0.0, s, s);
340 m.elapsed(i, 2);
341 m.effect(i, 3, 1.0, 0.0, Spring::EFFECTS);
342 }
343 assert_eq!(m.retained_properties(), 4);
344 m.finish();
345 m.begin(1.0, MotionPreference::Full);
346 m.finish();
347 assert_eq!(m.retained_properties(), 0);
348 assert!(!m.is_animating());
349 }
350 fn sample(motion: &mut Motion, time: f64, target: f32, preference: MotionPreference) -> f32 {
351 motion.begin(time, preference);
352 let value = motion.effect(1, 0, target, 0.0, Spring::EFFECTS);
353 motion.finish();
354 value
355 }
356 #[test]
357 fn settles_exactly_and_stops_scheduling() {
358 let mut motion = Motion::default();
359 assert_eq!(sample(&mut motion, 0.0, 1.0, MotionPreference::Full), 0.0);
360 assert!(motion.is_animating());
361 let mid = sample(&mut motion, 0.05, 1.0, MotionPreference::Full);
362 assert!(mid > 0.0 && mid < 1.0);
363 assert_eq!(sample(&mut motion, 2.0, 1.0, MotionPreference::Full), 1.0);
364 assert!(!motion.is_animating());
365 }
366 #[test]
367 fn reversal_has_no_position_jump_and_eventually_settles() {
368 let mut m = Motion::default();
369 sample(&mut m, 0.0, 1.0, MotionPreference::Full);
370 let before = sample(&mut m, 0.06, 1.0, MotionPreference::Full);
371 assert_eq!(sample(&mut m, 0.06, 0.0, MotionPreference::Full), before);
372 assert_eq!(sample(&mut m, 2.0, 0.0, MotionPreference::Full), 0.0);
373 assert!(!m.is_animating());
374 }
375 #[test]
376 fn analytic_sampling_is_independent_of_frame_count() {
377 let mut a = Motion::default();
378 let mut b = Motion::default();
379 sample(&mut a, 0.0, 1.0, MotionPreference::Full);
380 sample(&mut b, 0.0, 1.0, MotionPreference::Full);
381 for i in 1..6 {
382 sample(&mut a, i as f64 * 0.01, 1.0, MotionPreference::Full);
383 }
384 assert!(
385 (sample(&mut a, 0.06, 1.0, MotionPreference::Full)
386 - sample(&mut b, 0.06, 1.0, MotionPreference::Full))
387 .abs()
388 < 0.00001
389 );
390 }
391 #[test]
392 fn reduced_motion_finishes_in_flight_effects() {
393 let mut m = Motion::default();
394 sample(&mut m, 0.0, 1.0, MotionPreference::Full);
395 assert_eq!(sample(&mut m, 0.01, 1.0, MotionPreference::Reduced), 1.0);
396 assert!(!m.is_animating());
397 }
398 #[test]
399 fn removed_properties_are_reclaimed_and_cache_is_bounded() {
400 let mut m = Motion::new(2);
401 m.begin(0.0, MotionPreference::Full);
402 for id in 0..100 {
403 m.effect(id, 0, 1.0, 0.0, Spring::EFFECTS);
404 }
405 m.finish();
406 assert_eq!(m.retained_properties(), 2);
407 m.begin(1.0, MotionPreference::Full);
408 m.finish();
409 assert_eq!(m.retained_properties(), 0);
410 assert!(!m.is_animating());
411 }
412 #[test]
413 fn nonfinite_and_backwards_time_does_not_corrupt_values() {
414 let mut m = Motion::default();
415 sample(&mut m, 1.0, 1.0, MotionPreference::Full);
416 for t in [f64::NAN, -1.0, f64::INFINITY, 1e20] {
417 let value = sample(&mut m, t, 1.0, MotionPreference::Full);
418 assert!(value.is_finite() && (0.0..=1.0).contains(&value));
419 }
420 }
421}