1use serde::{Deserialize, Serialize};
13
14#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
20#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
21#[serde(deny_unknown_fields)]
22pub struct CubicBezier {
23 pub x1: f32,
25 pub y1: f32,
27 pub x2: f32,
29 pub y2: f32,
31}
32
33const NEWTON_STEPS: usize = 8;
35const BISECTION_STEPS: usize = 64;
37const TOLERANCE: f64 = 1e-12;
39const MIN_SLOPE: f64 = 1e-9;
41
42impl CubicBezier {
43 #[must_use]
45 pub const fn new(x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
46 Self { x1, y1, x2, y2 }
47 }
48
49 #[must_use]
52 pub fn is_valid(self) -> bool {
53 self.y1.is_finite() && self.y2.is_finite() && time_handles_valid(self.x1, self.x2)
54 }
55
56 #[must_use]
61 pub fn apply(self, progress: f64) -> f64 {
62 let x = progress.clamp(0.0, 1.0);
63 if x <= 0.0 {
64 return 0.0;
65 }
66 if x >= 1.0 {
67 return 1.0;
68 }
69 let parameter = self.time().parameter_at(x);
70 component(parameter, f64::from(self.y1), f64::from(self.y2))
71 }
72
73 #[must_use]
81 #[allow(clippy::cast_possible_truncation)]
82 pub fn between(self, from: f64, to: f64) -> Option<Self> {
83 let parameter = |progress: f64| {
84 if progress <= 0.0 {
85 0.0
86 } else if progress >= 1.0 {
87 1.0
88 } else {
89 self.time().parameter_at(progress)
90 }
91 };
92 let (u, v) = (parameter(from), parameter(to));
93 let part = |p1: f32, p2: f32| {
94 let points = [0.0, f64::from(p1), f64::from(p2), 1.0];
95 [
96 blossom(points, u, u, u),
97 blossom(points, u, u, v),
98 blossom(points, u, v, v),
99 blossom(points, v, v, v),
100 ]
101 };
102 let (x, y) = (part(self.x1, self.x2), part(self.y1, self.y2));
103 let (width, height) = (x[3] - x[0], y[3] - y[0]);
104 if width <= 0.0 || height == 0.0 {
105 return None;
106 }
107 let (x1, x2) = settle_time_handles((x[1] - x[0]) / width, (x[2] - x[0]) / width);
108 let curve = Self::new(
109 x1,
110 ((y[1] - y[0]) / height) as f32,
111 x2,
112 ((y[2] - y[0]) / height) as f32,
113 );
114 curve.is_valid().then_some(curve)
115 }
116
117 #[must_use]
120 pub fn reversed(self) -> Self {
121 let (x1, x2) = settle_time_handles(1.0 - f64::from(self.x2), 1.0 - f64::from(self.x1));
122 Self::new(x1, 1.0 - self.y2, x2, 1.0 - self.y1)
123 }
124
125 #[must_use]
129 pub fn slope(self, progress: f64) -> f64 {
130 let time = self.time();
131 let u = time.parameter_within(progress);
132 rise_over_run(
133 slope(u, f64::from(self.y1), f64::from(self.y2)),
134 slope(u, time.x1, time.x2),
135 )
136 }
137
138 #[must_use]
141 pub fn end_slope(self, at_end: bool) -> f64 {
142 let (x1, y1) = (f64::from(self.x1), f64::from(self.y1));
143 let (x2, y2) = (f64::from(self.x2), f64::from(self.y2));
144 let legs = if at_end {
145 [(1.0 - x2, 1.0 - y2), (1.0 - x1, 1.0 - y1)]
146 } else {
147 [(x1, y1), (x2, y2)]
148 };
149 first_leg_slope(legs).unwrap_or(1.0)
150 }
151
152 #[must_use]
155 pub fn turns(self) -> [Option<f64>; 2] {
156 let time = self.time();
157 let (y1, y2) = (f64::from(self.y1), f64::from(self.y2));
158 let c = 3.0 * y1;
159 let b = 3.0 * (y2 - y1) - c;
160 let a = 1.0 - c - b;
161 quadratic_roots(3.0 * a, 2.0 * b, c)
162 .map(|turn| turn.filter(|u| *u > 0.0 && *u < 1.0))
163 .map(|turn| turn.map(|u| component(u, time.x1, time.x2)))
164 }
165
166 fn time(self) -> TimeCurve {
167 TimeCurve::new(self.x1, self.x2)
168 }
169}
170
171fn quadratic_roots(qa: f64, qb: f64, qc: f64) -> [Option<f64>; 2] {
172 if qa.abs() <= f64::EPSILON {
173 return [(qb.abs() > f64::EPSILON).then(|| -qc / qb), None];
174 }
175 let discriminant = qb * qb - 4.0 * qa * qc;
176 if discriminant < 0.0 {
177 return [None, None];
178 }
179 let root = discriminant.sqrt();
180 [
181 Some((-qb + root) / (2.0 * qa)),
182 Some((-qb - root) / (2.0 * qa)),
183 ]
184}
185
186fn rise_over_run(rise: f64, run: f64) -> f64 {
187 if run >= MIN_RUN {
188 rise / run
189 } else if rise > 0.0 {
190 VERTICAL_SLOPE
191 } else if rise < 0.0 {
192 -VERTICAL_SLOPE
193 } else {
194 0.0
195 }
196}
197
198const SETTLE_STEPS: usize = 32;
199
200#[expect(
201 clippy::cast_possible_truncation,
202 reason = "time handles are stored as `f32`"
203)]
204fn settle_time_handles(x1: f64, x2: f64) -> (f32, f32) {
205 let step = |value: f32, direction: f64| {
206 if direction > 0.0 {
207 value.next_up()
208 } else if direction < 0.0 {
209 value.next_down()
210 } else {
211 value
212 }
213 };
214 let rounded = (
215 if x1 > 0.0 { x1 } else { 0.0 } as f32,
216 if x2 < 1.0 { x2 } else { 1.0 } as f32,
217 );
218 let (mut first, mut second) = rounded;
219 for _ in 0..SETTLE_STEPS {
220 if time_handles_valid(first, second) {
221 return (first, second);
222 }
223 let apart = 2.0 * (f64::from(first) - f64::from(second));
226 (first, second) = (
227 step(first, (1.0 - f64::from(second)) - apart),
228 step(second, apart - f64::from(first)),
229 );
230 }
231 if time_handles_valid(first, second) {
232 return (first, second);
233 }
234 (rounded.0.clamp(0.0, 1.0), rounded.1.clamp(0.0, 1.0))
235}
236
237fn first_leg_slope(legs: [(f64, f64); 2]) -> Option<f64> {
238 legs.into_iter()
239 .find(|(run, _)| *run > 0.0)
240 .map(|(run, rise)| rise / run)
241}
242
243#[must_use]
247pub fn time_handles_valid(x1: f32, x2: f32) -> bool {
248 if !(x1.is_finite() && x2.is_finite()) {
249 return false;
250 }
251 let (first, last) = (f64::from(x1), 1.0 - f64::from(x2));
252 let middle = f64::from(x2) - f64::from(x1);
253 first >= 0.0 && last >= 0.0 && (middle >= 0.0 || middle * middle <= first * last)
254}
255
256#[derive(Copy, Clone)]
257struct TimeCurve {
258 x1: f64,
259 x2: f64,
260}
261
262impl TimeCurve {
263 fn new(x1: f32, x2: f32) -> Self {
264 Self {
265 x1: f64::from(x1),
266 x2: f64::from(x2),
267 }
268 }
269
270 fn parameter_within(self, progress: f64) -> f64 {
271 if progress <= 0.0 {
272 0.0
273 } else if progress >= 1.0 {
274 1.0
275 } else {
276 self.parameter_at(progress)
277 }
278 }
279
280 fn parameter_at(self, x: f64) -> f64 {
282 self.newton(x).unwrap_or_else(|| self.bisection(x))
283 }
284
285 fn newton(self, x: f64) -> Option<f64> {
287 let Self { x1, x2 } = self;
288 let mut parameter = x;
289 for _ in 0..NEWTON_STEPS {
290 let error = component(parameter, x1, x2) - x;
291 if error.abs() < TOLERANCE {
292 return (0.0..=1.0).contains(¶meter).then_some(parameter);
293 }
294 let slope = slope(parameter, x1, x2);
295 if slope.abs() < MIN_SLOPE {
296 return None;
297 }
298 parameter -= error / slope;
299 }
300 None
301 }
302
303 fn bisection(self, x: f64) -> f64 {
306 let Self { x1, x2 } = self;
307 let (mut low, mut high) = (0.0_f64, 1.0_f64);
308 let mut parameter = x;
309 for _ in 0..BISECTION_STEPS {
310 let value = component(parameter, x1, x2);
311 if (value - x).abs() < TOLERANCE {
312 break;
313 }
314 if value < x {
315 low = parameter;
316 } else {
317 high = parameter;
318 }
319 parameter = low + (high - low) * 0.5;
320 }
321 parameter
322 }
323}
324
325fn component(t: f64, p1: f64, p2: f64) -> f64 {
328 let c = 3.0 * p1;
329 let b = 3.0 * (p2 - p1) - c;
330 let a = 1.0 - c - b;
331 ((a * t + b) * t + c) * t
332}
333
334fn blossom(points: [f64; 4], u: f64, v: f64, w: f64) -> f64 {
337 let lerp = |a: f64, b: f64, t: f64| a + (b - a) * t;
338 let first = [
339 lerp(points[0], points[1], u),
340 lerp(points[1], points[2], u),
341 lerp(points[2], points[3], u),
342 ];
343 let second = [lerp(first[0], first[1], v), lerp(first[1], first[2], v)];
344 lerp(second[0], second[1], w)
345}
346
347fn slope(t: f64, p1: f64, p2: f64) -> f64 {
349 let c = 3.0 * p1;
350 let b = 3.0 * (p2 - p1) - c;
351 let a = 1.0 - c - b;
352 (3.0 * a * t + 2.0 * b) * t + c
353}
354
355#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
361#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
362#[serde(deny_unknown_fields)]
363pub struct ValueBezier {
364 #[serde(default, skip_serializing_if = "Option::is_none")]
367 pub x1: Option<f32>,
368 pub leave: f32,
370 #[serde(default, skip_serializing_if = "Option::is_none")]
373 pub x2: Option<f32>,
374 pub arrive: f32,
376}
377
378const VERTICAL_SLOPE: f64 = f64::MAX;
379const MIN_RUN: f64 = 1e-12;
380
381impl ValueBezier {
382 #[must_use]
384 pub const fn unweighted(leave: f32, arrive: f32) -> Self {
385 Self {
386 x1: None,
387 leave,
388 x2: None,
389 arrive,
390 }
391 }
392
393 #[must_use]
395 pub const fn weighted(x1: f32, leave: f32, x2: f32, arrive: f32) -> Self {
396 Self {
397 x1: Some(x1),
398 leave,
399 x2: Some(x2),
400 arrive,
401 }
402 }
403
404 #[must_use]
407 pub fn is_valid(self) -> bool {
408 self.leave.is_finite()
409 && self.arrive.is_finite()
410 && match (self.x1, self.x2) {
411 (None, None) => true,
412 (Some(x1), Some(x2)) => time_handles_valid(x1, x2),
413 _ => false,
414 }
415 }
416
417 #[must_use]
419 pub fn weights(self) -> Option<(f32, f32)> {
420 self.x1.zip(self.x2)
421 }
422
423 #[must_use]
428 pub fn value(self, from: f32, to: f32, progress: f64) -> f64 {
429 self.value_between(f64::from(from), f64::from(to), progress)
430 }
431
432 #[must_use]
436 pub fn value_between(self, from: f64, to: f64, progress: f64) -> f64 {
437 if progress <= 0.0 {
438 return from;
439 }
440 if progress >= 1.0 {
441 return to;
442 }
443 let u = match self.weights() {
444 None => progress,
445 Some((x1, x2)) => TimeCurve::new(x1, x2).parameter_at(progress),
446 };
447 let [a, b, c] = self.polynomial(from, to);
448 from + ((a * u + b) * u + c) * u
449 }
450
451 #[must_use]
454 pub fn slope(self, from: f32, to: f32, progress: f64) -> f64 {
455 self.slope_between(f64::from(from), f64::from(to), progress)
456 }
457
458 #[must_use]
460 pub fn slope_between(self, from: f64, to: f64, progress: f64) -> f64 {
461 let progress = progress.clamp(0.0, 1.0);
462 let [a, b, c] = self.polynomial(from, to);
463 let rise = |u: f64| (3.0 * a * u + 2.0 * b) * u + c;
464 let Some((x1, x2)) = self.weights() else {
465 return rise(progress);
466 };
467 let time = TimeCurve::new(x1, x2);
468 let u = time.parameter_within(progress);
469 rise_over_run(rise(u), slope(u, time.x1, time.x2))
470 }
471
472 #[must_use]
478 #[expect(
479 clippy::cast_possible_truncation,
480 reason = "values and handles are stored as `f32`"
481 )]
482 pub fn between(self, from: f32, to: f32, start: f64, end: f64) -> (f32, f32, Self) {
483 let narrow = |value: f64| value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32;
484 let (low, high) = (
485 narrow(self.value(from, to, start)),
486 narrow(self.value(from, to, end)),
487 );
488 let part = self.part_between(
489 (f64::from(from), f64::from(to)),
490 (start, end),
491 (f64::from(low), f64::from(high)),
492 );
493 (low, high, part)
494 }
495
496 #[must_use]
500 #[expect(
501 clippy::cast_possible_truncation,
502 reason = "handles are stored as `f32`"
503 )]
504 pub fn part_between(self, ends: (f64, f64), span: (f64, f64), part_ends: (f64, f64)) -> Self {
505 let time = self.weights().map(|(x1, x2)| TimeCurve::new(x1, x2));
506 let parameter = |progress: f64| {
507 time.map_or(progress.clamp(0.0, 1.0), |time| {
508 time.parameter_within(progress)
509 })
510 };
511 let (u, v) = (parameter(span.0), parameter(span.1));
512 let part = |points: [f64; 4]| {
513 [
514 blossom(points, u, u, u),
515 blossom(points, u, u, v),
516 blossom(points, u, v, v),
517 blossom(points, v, v, v),
518 ]
519 };
520 let narrow = |value: f64| value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32;
521 let (from, to) = ends;
522 let y = part([
523 from,
524 from + f64::from(self.leave),
525 to + f64::from(self.arrive),
526 to,
527 ]);
528 let weights = time.and_then(|time| {
529 let x = part([0.0, time.x1, time.x2, 1.0]);
530 let width = x[3] - x[0];
531 (width > 0.0).then(|| settle_time_handles((x[1] - x[0]) / width, (x[2] - x[0]) / width))
532 });
533 Self {
534 x1: weights.map(|(x1, _)| x1),
535 leave: narrow(y[1] - part_ends.0),
536 x2: weights.map(|(_, x2)| x2),
537 arrive: narrow(y[2] - part_ends.1),
538 }
539 }
540
541 #[must_use]
543 pub fn reversed(self) -> Self {
544 let weights = self
545 .weights()
546 .map(|(x1, x2)| settle_time_handles(1.0 - f64::from(x2), 1.0 - f64::from(x1)));
547 Self {
548 x1: weights.map(|(x1, _)| x1),
549 leave: self.arrive,
550 x2: weights.map(|(_, x2)| x2),
551 arrive: self.leave,
552 }
553 }
554
555 #[must_use]
558 pub fn rebased(self, from: f32, to: f32, new_from: f32, new_to: f32) -> Self {
559 self.rebased_between(
560 (f64::from(from), f64::from(to)),
561 (f64::from(new_from), f64::from(new_to)),
562 )
563 }
564
565 #[must_use]
567 #[expect(
568 clippy::cast_possible_truncation,
569 reason = "clamped to the `f32` range first"
570 )]
571 pub fn rebased_between(self, ends: (f64, f64), new_ends: (f64, f64)) -> Self {
572 let narrow = |value: f64| value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32;
573 Self {
574 leave: narrow(ends.0 + f64::from(self.leave) - new_ends.0),
575 arrive: narrow(ends.1 + f64::from(self.arrive) - new_ends.1),
576 ..self
577 }
578 }
579
580 #[must_use]
582 pub fn range(self, from: f32, to: f32) -> [f64; 2] {
583 let (from, to) = (f64::from(from), f64::from(to));
584 let [a, b, c] = self.polynomial(from, to);
585 let value = |u: f64| from + ((a * u + b) * u + c) * u;
586 quadratic_roots(3.0 * a, 2.0 * b, c)
587 .into_iter()
588 .flatten()
589 .filter(|u| *u > 0.0 && *u < 1.0)
590 .map(value)
591 .fold([from.min(to), from.max(to)], |[low, high], value| {
592 [low.min(value), high.max(value)]
593 })
594 }
595
596 #[must_use]
600 pub fn end_slope(self, from: f32, to: f32, at_end: bool) -> f64 {
601 self.end_slope_between(f64::from(from), f64::from(to), at_end)
602 }
603
604 #[must_use]
606 pub fn end_slope_between(self, from: f64, to: f64, at_end: bool) -> f64 {
607 let (x1, x2) = self.weights().map_or((1.0 / 3.0, 2.0 / 3.0), |(x1, x2)| {
608 (f64::from(x1), f64::from(x2))
609 });
610 let change = to - from;
611 let (leave, arrive) = (f64::from(self.leave), f64::from(self.arrive));
612 let legs = if at_end {
613 [(1.0 - x2, -arrive), (1.0 - x1, change - leave)]
614 } else {
615 [(x1, leave), (x2, change + arrive)]
616 };
617 first_leg_slope(legs).unwrap_or(change)
618 }
619
620 #[must_use]
623 pub fn turns_between(self, from: f64, to: f64) -> [Option<f64>; 2] {
624 let [a, b, c] = self.polynomial(from, to);
625 let time = self.weights().map(|(x1, x2)| TimeCurve::new(x1, x2));
626 quadratic_roots(3.0 * a, 2.0 * b, c)
627 .map(|turn| turn.filter(|u| *u > 0.0 && *u < 1.0))
628 .map(|turn| turn.map(|u| time.map_or(u, |time| component(u, time.x1, time.x2))))
629 }
630
631 fn polynomial(self, from: f64, to: f64) -> [f64; 3] {
632 let change = to - from;
633 let c = 3.0 * f64::from(self.leave);
634 let b = 3.0 * (change + f64::from(self.arrive) - f64::from(self.leave)) - c;
635 let a = change - c - b;
636 [a, b, c]
637 }
638}
639
640pub const MAX_EASING_STEPS: u32 = 65_536;
642
643pub const MAX_EASING_POINTS: usize = 256;
645
646#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
648#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
649#[serde(rename_all = "snake_case")]
650pub enum StepPosition {
651 Start,
653 #[default]
655 End,
656 None,
658 Both,
660}
661
662impl StepPosition {
663 #[expect(
664 clippy::trivially_copy_pass_by_ref,
665 reason = "serde passes a field by reference"
666 )]
667 fn is_end(&self) -> bool {
668 *self == Self::End
669 }
670}
671
672#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
674#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
675#[serde(deny_unknown_fields)]
676pub struct Steps {
677 #[serde(deserialize_with = "step_count")]
679 #[cfg_attr(
680 feature = "schema",
681 schemars(range(min = 1, max = MAX_EASING_STEPS))
682 )]
683 pub count: u32,
684 #[serde(default, skip_serializing_if = "StepPosition::is_end")]
686 pub position: StepPosition,
687}
688
689fn step_count<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<u32, D::Error> {
690 let count = u32::deserialize(deserializer)?;
691 if (1..=MAX_EASING_STEPS).contains(&count) {
692 Ok(count)
693 } else {
694 Err(serde::de::Error::custom(format!(
695 "a steps count is 1 to {MAX_EASING_STEPS}, not {count}"
696 )))
697 }
698}
699
700impl Steps {
701 #[must_use]
703 pub const fn is_valid(self) -> bool {
704 let least = if matches!(self.position, StepPosition::None) {
705 2
706 } else {
707 1
708 };
709 self.count >= least && self.count <= MAX_EASING_STEPS
710 }
711
712 #[must_use]
716 pub const fn index(self, elapsed: i128, length: i128) -> i128 {
717 let last = self.count as i128 - 1;
718 let index = (elapsed * self.count as i128).div_euclid(length);
719 if index < 0 {
720 0
721 } else if index > last {
722 last
723 } else {
724 index
725 }
726 }
727
728 #[must_use]
730 #[expect(clippy::cast_precision_loss, reason = "counts of at most 65,537")]
731 pub const fn amount(self, index: i128) -> f64 {
732 let (rises, of) = self.fraction(index);
733 rises as f64 / of as f64
734 }
735
736 #[must_use]
739 pub const fn fraction(self, index: i128) -> (i128, i128) {
740 let count = self.count as i128;
741 match self.position {
742 StepPosition::End => (index, count),
743 StepPosition::Start => (index + 1, count),
744 StepPosition::None => (index, count - 1),
745 StepPosition::Both => (index + 1, count + 1),
746 }
747 }
748
749 #[must_use]
752 pub fn apply(self, progress: f64) -> f64 {
753 if progress >= 1.0 {
754 return 1.0;
755 }
756 if progress < 0.0 || progress.is_nan() {
757 return 0.0;
758 }
759 #[expect(
760 clippy::cast_possible_truncation,
761 reason = "a progress below 1 times a count of at most 65,536"
762 )]
763 let index = (progress * f64::from(self.count)).floor() as i128;
764 self.amount(index.clamp(0, i128::from(self.count) - 1))
765 }
766}
767
768#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
770#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
771#[serde(deny_unknown_fields)]
772pub struct EasingPoint {
773 pub x: f32,
775 pub y: f32,
777}
778
779#[must_use]
782pub fn easing_points_valid(points: &[EasingPoint]) -> bool {
783 points.len() <= MAX_EASING_POINTS
784 && points
785 .iter()
786 .all(|point| point.x > 0.0 && point.x < 1.0 && point.y.is_finite())
787 && points.windows(2).all(|pair| pair[0].x < pair[1].x)
788}
789
790fn table_piece(points: &[EasingPoint], progress: f64) -> [(f64, f64); 2] {
791 let wide = |point: &EasingPoint| (f64::from(point.x), f64::from(point.y));
792 let next = points.partition_point(|point| f64::from(point.x) <= progress);
793 [
794 next.checked_sub(1)
795 .and_then(|index| points.get(index))
796 .map_or((0.0, 0.0), wide),
797 points.get(next).map_or((1.0, 1.0), wide),
798 ]
799}
800
801#[must_use]
804pub fn easing_points_at(points: &[EasingPoint], progress: f64) -> f64 {
805 if progress <= 0.0 || progress.is_nan() {
806 return 0.0;
807 }
808 if progress >= 1.0 {
809 return 1.0;
810 }
811 let [(xa, ya), (xb, yb)] = table_piece(points, progress);
812 ya + (yb - ya) * ((progress - xa) / (xb - xa))
813}
814
815#[must_use]
818pub fn easing_points_slope(points: &[EasingPoint], progress: f64) -> f64 {
819 let [(xa, ya), (xb, yb)] = table_piece(points, progress.clamp(0.0, 1.0));
820 (yb - ya) / (xb - xa)
821}
822
823#[must_use]
825pub fn easing_points_range(points: &[EasingPoint]) -> [f64; 2] {
826 points.iter().fold([0.0, 1.0], |[low, high], point| {
827 [low.min(f64::from(point.y)), high.max(f64::from(point.y))]
828 })
829}
830
831#[expect(
832 clippy::cast_possible_truncation,
833 reason = "easing points are stored as `f32`"
834)]
835fn rising_points(points: impl Iterator<Item = (f64, f64)>) -> Vec<EasingPoint> {
836 let mut rising: Vec<EasingPoint> = Vec::new();
837 for (x, y) in points {
838 let point = EasingPoint {
839 x: x as f32,
840 y: y.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32,
841 };
842 if point.x > rising.last().map_or(0.0, |last| last.x) && point.x < 1.0 {
843 rising.push(point);
844 }
845 }
846 rising
847}
848
849#[must_use]
852pub fn easing_points_reversed(points: &[EasingPoint]) -> Vec<EasingPoint> {
853 rising_points(
854 points
855 .iter()
856 .rev()
857 .map(|point| (1.0 - f64::from(point.x), 1.0 - f64::from(point.y))),
858 )
859}
860
861#[must_use]
865pub fn easing_points_between(
866 points: &[EasingPoint],
867 start: f64,
868 end: f64,
869 output: impl Fn(f64) -> f64,
870) -> Option<Vec<EasingPoint>> {
871 let inside: Vec<(f64, f64)> = points
872 .iter()
873 .map(|point| (f64::from(point.x), output(f64::from(point.y))))
874 .filter(|(x, _)| *x > start && *x < end)
875 .map(|(x, y)| ((x - start) / (end - start), y))
876 .collect();
877 inside
878 .iter()
879 .all(|(_, y)| y.is_finite())
880 .then(|| rising_points(inside.into_iter()))
881}
882
883#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
887#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
888#[serde(tag = "type", rename_all = "snake_case", from = "EasingWire")]
889pub enum Easing {
890 Linear,
892 CubicBezier(CubicBezier),
894 Steps(Steps),
896 Points {
899 points: Vec<EasingPoint>,
902 },
903}
904
905#[derive(Deserialize)]
910#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
911#[cfg_attr(feature = "schema", schemars(rename = "Easing"))]
912#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
913pub(crate) enum EasingWire {
914 Linear {},
916 CubicBezier(CubicBezier),
918 Steps(Steps),
920 Points {
923 #[serde(deserialize_with = "crate::bounded::seq::<_, _, MAX_EASING_POINTS>")]
926 #[cfg_attr(feature = "schema", schemars(length(max = MAX_EASING_POINTS)))]
927 points: Vec<EasingPoint>,
928 },
929}
930
931impl From<EasingWire> for Easing {
932 fn from(wire: EasingWire) -> Self {
933 match wire {
934 EasingWire::Linear {} => Self::Linear,
935 EasingWire::CubicBezier(curve) => Self::CubicBezier(curve),
936 EasingWire::Steps(steps) => Self::Steps(steps),
937 EasingWire::Points { points } => Self::Points { points },
938 }
939 }
940}
941
942impl Easing {
943 #[must_use]
945 pub fn is_valid(&self) -> bool {
946 match self {
947 Self::Linear => true,
948 Self::CubicBezier(curve) => curve.is_valid(),
949 Self::Steps(steps) => steps.is_valid(),
950 Self::Points { points } => easing_points_valid(points),
951 }
952 }
953
954 #[must_use]
956 pub fn apply(&self, progress: f64) -> f64 {
957 match self {
958 Self::Linear => progress.clamp(0.0, 1.0),
959 Self::CubicBezier(curve) => curve.apply(progress),
960 Self::Steps(steps) => steps.apply(progress),
961 Self::Points { points } => easing_points_at(points, progress),
962 }
963 }
964}
965
966#[cfg(test)]
967#[path = "easing_parts_tests.rs"]
968mod parts_tests;
969
970#[cfg(test)]
971#[path = "easing_steps_tests.rs"]
972mod steps_tests;
973
974#[cfg(test)]
975mod tests {
976 use super::{CubicBezier, Easing, ValueBezier, time_handles_valid};
977
978 const EASE: CubicBezier = CubicBezier::new(0.25, 0.1, 0.25, 1.0);
979
980 #[test]
981 fn css_ease_matches_its_reference_value() {
982 assert!((EASE.apply(0.5) - 0.802_403_387_584_857).abs() < 1e-9);
986 assert!((EASE.time().parameter_at(0.5) - 0.699_572_438_706_385_6).abs() < 1e-9);
987 let ease_in_out = CubicBezier::new(0.42, 0.0, 0.58, 1.0);
988 assert!((ease_in_out.apply(0.5) - 0.5).abs() < 1e-7);
990 for x in [0.1, 0.25, 0.4] {
991 let mirrored = 1.0 - ease_in_out.apply(1.0 - x);
992 assert!((ease_in_out.apply(x) - mirrored).abs() < 1e-7);
993 }
994 }
995
996 #[test]
997 fn ends_are_exact_and_input_is_clamped() {
998 for curve in [EASE, CubicBezier::new(0.0, -2.0, 1.0, 3.0)] {
999 assert_eq!(curve.apply(0.0).to_bits(), 0.0_f64.to_bits());
1000 assert_eq!(curve.apply(1.0).to_bits(), 1.0_f64.to_bits());
1001 assert_eq!(curve.apply(-4.0).to_bits(), 0.0_f64.to_bits());
1002 assert_eq!(curve.apply(9.0).to_bits(), 1.0_f64.to_bits());
1003 }
1004 }
1005
1006 #[test]
1007 fn the_linear_curve_is_the_identity() {
1008 let linear = CubicBezier::new(0.0, 0.0, 1.0, 1.0);
1009 for index in 0..=64 {
1010 let x = f64::from(index) / 64.0;
1011 assert!((linear.apply(x) - x).abs() < 1e-12, "{x}");
1012 assert!((Easing::Linear.apply(x) - x).abs() < f64::EPSILON);
1013 }
1014 }
1015
1016 #[test]
1017 fn flat_curves_fall_back_to_bisection_and_stay_accurate() {
1018 let cases = [
1021 (CubicBezier::new(0.0, 0.0, 0.0, 0.0), 0.001, 0.1),
1022 (CubicBezier::new(1.0, 1.0, 1.0, 1.0), 0.999, 0.9),
1023 ];
1024 for (curve, x, parameter) in cases {
1025 assert_eq!(
1026 curve.time().newton(x),
1027 None,
1028 "Newton must give up on {curve:?}"
1029 );
1030 let found = curve.time().parameter_at(x);
1031 assert!((found - parameter).abs() < 1e-9, "{curve:?}: {found}");
1032 let x_back = super::component(found, f64::from(curve.x1), f64::from(curve.x2));
1033 assert!((x_back - x).abs() < 1e-12);
1034 }
1035 }
1036
1037 #[test]
1038 fn a_part_of_a_curve_rescaled_shows_the_same_output() {
1039 let curves = [
1040 EASE,
1041 CubicBezier::new(0.42, 0.0, 0.58, 1.0),
1042 CubicBezier::new(0.3, -0.5, 0.7, 1.5),
1043 CubicBezier::new(0.0, 0.0, 1.0, 1.0),
1044 ];
1045 for curve in curves {
1046 for (from, to) in [
1047 (0.0, 0.37),
1048 (0.37, 1.0),
1049 (0.1, 0.9),
1050 (0.5, 0.55),
1051 (0.0, 1.0),
1052 ] {
1053 let part = curve.between(from, to).expect("a curve that moves");
1054 assert!(part.is_valid(), "{curve:?} {from} {to}");
1055 let (low, high) = (curve.apply(from), curve.apply(to));
1056 for step in 0..=1000 {
1057 let x = from + (to - from) * f64::from(step) / 1000.0;
1058 let local = (x - from) / (to - from);
1059 let shown = low + (high - low) * part.apply(local);
1060 assert!(
1062 (shown - curve.apply(x)).abs() < 1e-6,
1063 "{curve:?} {from}..{to} at {x}: {shown} {}",
1064 curve.apply(x)
1065 );
1066 }
1067 }
1068 }
1069 }
1070
1071 #[test]
1072 fn an_empty_part_has_no_curve() {
1073 assert_eq!(EASE.between(0.4, 0.4), None);
1074 }
1075
1076 #[test]
1077 fn overshooting_curves_leave_the_unit_interval_between_the_ends() {
1078 let back = CubicBezier::new(0.34, 1.56, 0.64, 1.0);
1079 let peak = (1..100)
1080 .map(|index| back.apply(f64::from(index) / 100.0))
1081 .fold(f64::MIN, f64::max);
1082 assert!(peak > 1.05, "ease-out-back overshoots: {peak}");
1083 assert!((Easing::CubicBezier(back).apply(1.0) - 1.0).abs() < f64::EPSILON);
1084 }
1085
1086 #[test]
1087 fn only_time_coordinates_that_run_backwards_are_rejected() {
1088 assert!(CubicBezier::new(0.0, -5.0, 1.0, 5.0).is_valid());
1089 assert!(CubicBezier::new(1.136, 0.0, 0.909, 1.0).is_valid());
1090 assert!(!CubicBezier::new(-0.1, 0.0, 1.0, 1.0).is_valid());
1091 assert!(!CubicBezier::new(0.0, 0.0, 1.1, 1.0).is_valid());
1092 assert!(!CubicBezier::new(1.2, 0.0, 0.2, 1.0).is_valid());
1093 assert!(!CubicBezier::new(0.0, f32::NAN, 1.0, 1.0).is_valid());
1094 assert!(!CubicBezier::new(f32::NAN, 0.0, 1.0, 1.0).is_valid());
1095 assert!(!CubicBezier::new(0.0, 0.0, f32::INFINITY, 1.0).is_valid());
1096 assert!(!Easing::CubicBezier(CubicBezier::new(0.0, 0.0, 2.0, 1.0)).is_valid());
1097 }
1098
1099 fn least_time_speed(x1: f32, x2: f32) -> f64 {
1100 let (first, last) = (f64::from(x1), 1.0 - f64::from(x2));
1101 let middle = f64::from(x2) - f64::from(x1);
1102 (0..=4096)
1103 .map(|step| {
1104 let u = f64::from(step) / 4096.0;
1105 let rest = 1.0 - u;
1106 rest * rest * first + 2.0 * rest * u * middle + u * u * last
1107 })
1108 .fold(f64::INFINITY, f64::min)
1109 }
1110
1111 #[test]
1112 fn time_handles_are_valid_exactly_where_time_never_runs_backwards() {
1113 let coordinate = |index: u16| f32::from(index) / 64.0 - 0.5;
1114 let mut valid = 0;
1115 for x1 in (0..=128).map(coordinate) {
1116 for x2 in (0..=128).map(coordinate) {
1117 let least = least_time_speed(x1, x2);
1118 let verdict = time_handles_valid(x1, x2);
1119 valid += u32::from(verdict);
1120 assert!(
1121 verdict == (least >= -1e-12) || least.abs() < 1e-6,
1122 "({x1}, {x2}): {verdict}, least speed {least}"
1123 );
1124 }
1125 }
1126 assert!(valid > 65 * 65, "more than the CSS box: {valid}");
1127 assert!(!time_handles_valid(f32::NAN, 0.5));
1128 assert!(!time_handles_valid(0.5, f32::INFINITY));
1129 }
1130
1131 #[test]
1132 fn the_css_box_is_inside_the_valid_time_handles() {
1133 let coordinate = |index: u16| f32::from(index) / 64.0;
1134 for x1 in (0..=64).map(coordinate) {
1135 for x2 in (0..=64).map(coordinate) {
1136 assert!(time_handles_valid(x1, x2), "({x1}, {x2})");
1137 }
1138 }
1139 }
1140
1141 #[test]
1142 fn the_widest_valid_handles_are_near_four_thirds_and_minus_one_third() {
1143 assert!(time_handles_valid(1.333, 2.0 / 3.0));
1144 assert!(time_handles_valid(1.0 / 3.0, -0.333));
1145 let partners = || (0..=2048_u16).map(|index| f32::from(index) / 1024.0 - 0.5);
1146 for partner in partners() {
1147 assert!(!time_handles_valid(1.34, partner), "x2 = {partner}");
1148 assert!(!time_handles_valid(partner, -0.34), "x1 = {partner}");
1149 }
1150 }
1151
1152 #[test]
1153 fn a_curve_outside_the_css_box_still_reaches_every_progress() {
1154 let curve = CubicBezier::new(1.136, 0.0, 0.909, 1.0);
1155 let mut previous = 0.0;
1156 for step in 1..1000 {
1157 let x = f64::from(step) / 1000.0;
1158 let parameter = curve.time().parameter_at(x);
1159 let back = super::component(parameter, f64::from(curve.x1), f64::from(curve.x2));
1160 assert!((back - x).abs() < 1e-9, "{x}: {back}");
1161 assert!(parameter >= previous, "{x}: {parameter} after {previous}");
1162 previous = parameter;
1163 }
1164 }
1165
1166 #[test]
1167 fn an_unweighted_value_curve_has_its_control_points_at_the_thirds() {
1168 let curve = ValueBezier::unweighted(0.75, -0.25);
1169 let thirds = ValueBezier::weighted(1.0 / 3.0, 0.75, 2.0 / 3.0, -0.25);
1170 assert_eq!(curve.weights(), None);
1171 assert_eq!(thirds.weights(), Some((1.0 / 3.0, 2.0 / 3.0)));
1172 for step in 0..=64 {
1173 let progress = f64::from(step) / 64.0;
1174 let (plain, solved) = (
1175 curve.value(-1.0, 2.5, progress),
1176 thirds.value(-1.0, 2.5, progress),
1177 );
1178 assert!(
1179 (plain - solved).abs() < 1e-6,
1180 "{progress}: {plain} {solved}"
1181 );
1182 }
1183 }
1184
1185 #[test]
1186 fn the_ends_of_a_value_curve_are_its_two_values_exactly() {
1187 for curve in [
1188 ValueBezier::unweighted(3.0, -7.0),
1189 ValueBezier::weighted(0.0, 5.0, 1.0, 5.0),
1190 ValueBezier::weighted(1.136, -2.0, 0.909, 0.5),
1191 ] {
1192 for progress in [-4.0, 0.0] {
1193 assert_eq!(
1194 curve.value(0.1, 0.7, progress).to_bits(),
1195 f64::from(0.1_f32).to_bits()
1196 );
1197 }
1198 for progress in [1.0, 9.0] {
1199 assert_eq!(
1200 curve.value(0.1, 0.7, progress).to_bits(),
1201 f64::from(0.7_f32).to_bits()
1202 );
1203 }
1204 }
1205 }
1206
1207 #[test]
1208 fn a_value_curves_slope_is_its_rise_over_its_run() {
1209 let straight = ValueBezier::unweighted(1.0, -1.0);
1210 for progress in [0.0, 0.3, 1.0] {
1211 assert!((straight.slope(2.0, 5.0, progress) - 3.0).abs() < 1e-12);
1212 }
1213 let weighted = ValueBezier::weighted(0.25, 0.5, 0.5, -1.0);
1214 assert!((weighted.slope(0.0, 1.0, 0.0) - 0.5 / 0.25).abs() < 1e-9);
1215 assert!((weighted.slope(0.0, 1.0, 1.0) - 1.0 / 0.5).abs() < 1e-9);
1216 for step in 1..64 {
1217 let progress = f64::from(step) / 64.0;
1218 let numeric = (weighted.value(0.0, 1.0, progress + 1e-6)
1219 - weighted.value(0.0, 1.0, progress - 1e-6))
1220 / 2e-6;
1221 let slope = weighted.slope(0.0, 1.0, progress);
1222 assert!(
1223 (slope - numeric).abs() < 1e-4,
1224 "{progress}: {slope} {numeric}"
1225 );
1226 }
1227 let vertical = ValueBezier::weighted(0.0, 0.5, 1.0, 0.5);
1228 assert_eq!(vertical.slope(0.0, 1.0, 0.0).to_bits(), f64::MAX.to_bits());
1229 assert_eq!(
1230 vertical.slope(0.0, 1.0, 1.0).to_bits(),
1231 (-f64::MAX).to_bits()
1232 );
1233 let level = ValueBezier::weighted(0.0, 0.0, 1.0, 0.0);
1234 assert_eq!(level.slope(1.0, 1.0, 0.0).to_bits(), 0.0_f64.to_bits());
1235 }
1236
1237 #[test]
1238 fn a_value_curves_range_holds_every_value_and_is_reached() {
1239 let curves = [
1240 ValueBezier::unweighted(0.6, 0.6),
1241 ValueBezier::unweighted(-2.0, 3.0),
1242 ValueBezier::weighted(0.1, 4.0, 0.2, -3.0),
1243 ValueBezier::weighted(1.136, 0.0, 0.909, 0.0),
1244 ValueBezier::unweighted(0.0, 0.0),
1245 ];
1246 for curve in curves {
1247 for (from, to) in [(1.0, 1.0), (0.0, 1.0), (2.25, -3.5)] {
1248 let [low, high] = curve.range(from, to);
1249 let (mut least, mut greatest) = (f64::INFINITY, f64::NEG_INFINITY);
1250 for step in 0..=4096 {
1251 let value = curve.value(from, to, f64::from(step) / 4096.0);
1252 least = least.min(value);
1253 greatest = greatest.max(value);
1254 }
1255 assert!(low <= least + 1e-9 && greatest <= high + 1e-9, "{curve:?}");
1256 assert!(
1257 (low - least).abs() < 1e-5 && (high - greatest).abs() < 1e-5,
1258 "{curve:?} {from}..{to}: {low}..{high} sampled {least}..{greatest}"
1259 );
1260 }
1261 }
1262 }
1263
1264 #[test]
1265 fn an_end_slope_is_the_first_control_leg_with_a_time_extent() {
1266 let near = |slope: f64, expected: f64| (slope - expected).abs() < 1e-12;
1267 let timing = CubicBezier::new(0.25, 0.5, 0.5, 0.75);
1268 assert!(near(timing.end_slope(false), 2.0));
1269 assert!(near(timing.end_slope(true), 0.5));
1270 let upright = CubicBezier::new(0.0, 0.5, 1.0, 0.25);
1271 assert!(near(upright.end_slope(false), 0.25));
1272 assert!(near(upright.end_slope(true), 0.5));
1273 assert!(near(
1274 CubicBezier::new(0.0, 0.5, 0.0, 0.25).end_slope(false),
1275 1.0
1276 ));
1277 assert!(near(
1278 CubicBezier::new(1.0, 0.5, 1.0, 0.25).end_slope(true),
1279 1.0
1280 ));
1281 assert!(near(
1282 CubicBezier::new(0.0, 0.0, 1.0, 1.0).end_slope(false),
1283 1.0
1284 ));
1285
1286 let value = ValueBezier::weighted(0.25, 1.5, 0.5, -3.0);
1287 assert!(near(value.end_slope(1.0, 3.0, false), 6.0));
1288 assert!(near(value.end_slope(1.0, 3.0, true), 6.0));
1289 let thirds = ValueBezier::unweighted(1.5, -3.0);
1290 assert!((thirds.end_slope(1.0, 3.0, false) - 4.5).abs() < 1e-9);
1291 assert!((thirds.end_slope(1.0, 3.0, true) - 9.0).abs() < 1e-9);
1292 assert!((thirds.end_slope(1.0, 3.0, false) - thirds.slope(1.0, 3.0, 0.0)).abs() < 1e-9);
1293 assert!((thirds.end_slope(1.0, 3.0, true) - thirds.slope(1.0, 3.0, 1.0)).abs() < 1e-9);
1294 let upright = ValueBezier::weighted(0.0, 1.5, 1.0, -3.0);
1295 assert!(near(upright.end_slope(1.0, 3.0, false), 2.0 - 3.0));
1296 assert!(near(upright.end_slope(1.0, 3.0, true), 2.0 - 1.5));
1297 let chord = ValueBezier::weighted(0.0, 1.5, 0.0, -3.0);
1298 assert!(near(chord.end_slope(1.0, 3.0, false), 2.0));
1299 assert!(near(
1300 ValueBezier::weighted(1.0, 1.5, 1.0, -3.0).end_slope(1.0, 3.0, true),
1301 2.0
1302 ));
1303 }
1304
1305 #[test]
1306 fn a_value_curve_needs_finite_offsets_and_both_time_coordinates() {
1307 assert!(ValueBezier::unweighted(1e30, -1e30).is_valid());
1308 assert!(ValueBezier::weighted(1.2, 0.0, 0.9, 0.0).is_valid());
1309 assert!(!ValueBezier::unweighted(f32::NAN, 0.0).is_valid());
1310 assert!(!ValueBezier::unweighted(0.0, f32::INFINITY).is_valid());
1311 assert!(!ValueBezier::weighted(1.2, 0.0, 0.2, 0.0).is_valid());
1312 let half = ValueBezier {
1313 x1: Some(0.5),
1314 ..ValueBezier::unweighted(0.0, 0.0)
1315 };
1316 assert!(!half.is_valid());
1317 }
1318
1319 #[test]
1320 fn the_wire_form_is_a_tagged_object() {
1321 let easing: Easing =
1322 serde_json::from_str(r#"{"type":"cubic_bezier","x1":0.42,"y1":0,"x2":0.58,"y2":1}"#)
1323 .expect("cubic bezier easing");
1324 assert_eq!(
1325 easing,
1326 Easing::CubicBezier(CubicBezier::new(0.42, 0.0, 0.58, 1.0))
1327 );
1328 let linear: Easing = serde_json::from_str(r#"{"type":"linear"}"#).expect("linear");
1329 assert_eq!(linear, Easing::Linear);
1330 assert!(serde_json::from_str::<Easing>(r#""linear""#).is_err());
1331 assert!(serde_json::from_str::<Easing>(r#"{"type":"linear","x1":0}"#).is_err());
1332 }
1333}