1use crate::{SampleContext, sample_scalar};
5use alpha2_model::{
6 Animated, AnimatedPoint, CubicBezier, Extrapolation, Interpolation, Keyframe, MAX_KEYFRAMES,
7 PointKeyframe, ValueBezier, Vec2,
8};
9use alpha2_time::{MediaTime, TICKS_PER_SECOND, TimeRange};
10
11mod materialize;
12mod motion;
13mod tangents;
14mod wide;
15mod within;
16
17pub use materialize::materialize;
18pub use motion::path_to_keys;
19pub(crate) use tangents::tangents_of;
20pub use tangents::{
21 AutoTangent, auto_tangents, contain, from_handle_points, from_slopes, from_speed_influence,
22};
23pub(crate) use wide::{WideKey, as_value_curve, part_keys, split_at, stepped};
24pub(crate) use within::keys_within;
25
26#[derive(Copy, Clone, Debug, Eq, PartialEq)]
28pub enum CurveError {
29 Empty,
31 NotKeyed,
33 OutsideKeys,
35 OnAKey,
37 LevelSegment,
40 TooManyKeys,
42 OffThePath,
45}
46
47impl std::fmt::Display for CurveError {
48 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 formatter.write_str(match self {
50 Self::Empty => "the value has no keyframes",
51 Self::NotKeyed => "the value is not keyframed",
52 Self::OutsideKeys => "the time lies outside the keyframes",
53 Self::OnAKey => "a keyframe already lies at the time",
54 Self::LevelSegment => "a part of the segment has no timing curve",
55 Self::TooManyKeys => "the result would hold too many keyframes",
56 Self::OffThePath => "the value is off the path between the keyframes at the time",
57 })
58 }
59}
60
61impl std::error::Error for CurveError {}
62
63#[derive(Copy, Clone, Debug, Eq, PartialEq)]
65pub enum SegmentKind {
66 Hold,
68 Linear,
70 Timing,
72 Value,
74 Steps,
76 Points,
78}
79
80#[derive(Copy, Clone, Debug, PartialEq)]
82pub struct ControlSegment {
83 pub start: (i64, f64),
85 pub end: (i64, f64),
87 pub controls: Option<[(f64, f64); 2]>,
90 pub kind: SegmentKind,
92}
93
94#[derive(Copy, Clone, Debug, PartialEq)]
96pub struct CurveSample {
97 pub value: f32,
99 pub velocity: f64,
102}
103
104#[expect(clippy::cast_precision_loss, reason = "a span of ticks as a length")]
105fn span(left: MediaTime, right: MediaTime) -> f64 {
106 (i128::from(right.ticks()) - i128::from(left.ticks())) as f64
107}
108
109#[expect(clippy::cast_precision_loss, reason = "a tick as a coordinate")]
110const fn coordinate(time: MediaTime) -> f64 {
111 time.ticks() as f64
112}
113
114#[expect(
115 clippy::cast_possible_truncation,
116 reason = "clamped to the range of f32"
117)]
118pub(crate) fn narrow(value: f64) -> f32 {
119 if value.is_nan() {
120 0.0
121 } else {
122 value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32
123 }
124}
125
126struct Cubic {
127 x1: f64,
128 x2: f64,
129 from: f64,
130 leave: f64,
131 arrive: f64,
132 to: f64,
133}
134
135impl Cubic {
136 fn of(left: &Keyframe<f32>, right: &Keyframe<f32>) -> Option<Self> {
137 let (from, to) = (f64::from(left.value), f64::from(right.value));
138 match left.interpolation {
139 Interpolation::Hold
140 | Interpolation::Linear
141 | Interpolation::Steps(_)
142 | Interpolation::Points { .. } => None,
143 Interpolation::CubicBezier(curve) => Some(Self {
144 x1: f64::from(curve.x1),
145 x2: f64::from(curve.x2),
146 from,
147 leave: f64::from(curve.y1) * (to - from),
148 arrive: (f64::from(curve.y2) - 1.0) * (to - from),
149 to,
150 }),
151 Interpolation::ValueBezier(curve) => {
152 let (x1, x2) = curve.weights().map_or((1.0 / 3.0, 2.0 / 3.0), |(x1, x2)| {
153 (f64::from(x1), f64::from(x2))
154 });
155 Some(Self {
156 x1,
157 x2,
158 from,
159 leave: f64::from(curve.leave),
160 arrive: f64::from(curve.arrive),
161 to,
162 })
163 }
164 }
165 }
166
167 fn progress_at(&self, u: f64) -> f64 {
168 let c = 3.0 * self.x1;
169 let b = 3.0 * (self.x2 - self.x1) - c;
170 let a = 1.0 - c - b;
171 ((a * u + b) * u + c) * u
172 }
173
174 fn polynomial(&self) -> [f64; 3] {
175 let change = self.to - self.from;
176 let c = 3.0 * self.leave;
177 let b = 3.0 * (change + self.arrive - self.leave) - c;
178 [change - c - b, b, c]
179 }
180
181 fn value_at(&self, u: f64) -> f64 {
182 let [a, b, c] = self.polynomial();
183 self.from + ((a * u + b) * u + c) * u
184 }
185
186 fn turns(&self) -> impl Iterator<Item = f64> {
187 let [a, b, c] = self.polynomial();
188 let (qa, qb, qc) = (3.0 * a, 2.0 * b, c);
189 let mut roots = [None, None];
190 if qa.abs() <= f64::EPSILON {
191 if qb.abs() > f64::EPSILON {
192 roots[0] = Some(-qc / qb);
193 }
194 } else {
195 let discriminant = qb * qb - 4.0 * qa * qc;
196 if discriminant >= 0.0 {
197 let root = discriminant.sqrt();
198 roots = [
199 Some((-qb + root) / (2.0 * qa)),
200 Some((-qb - root) / (2.0 * qa)),
201 ];
202 }
203 }
204 roots.into_iter().flatten().filter(|u| *u > 0.0 && *u < 1.0)
205 }
206}
207
208#[must_use]
211pub fn segments(animation: &Animated<f32>) -> Vec<ControlSegment> {
212 let Animated::Keyframes { keyframes, .. } = animation else {
213 return Vec::new();
214 };
215 keyframes
216 .windows(2)
217 .map(|pair| {
218 let (left, right) = (&pair[0], &pair[1]);
219 let length = span(left.time, right.time);
220 let controls = Cubic::of(left, right).map(|cubic| {
221 [
222 (
223 coordinate(left.time) + cubic.x1 * length,
224 cubic.from + cubic.leave,
225 ),
226 (
227 coordinate(left.time) + cubic.x2 * length,
228 cubic.to + cubic.arrive,
229 ),
230 ]
231 });
232 ControlSegment {
233 start: (left.time.ticks(), f64::from(left.value)),
234 end: (right.time.ticks(), f64::from(right.value)),
235 controls,
236 kind: match left.interpolation {
237 Interpolation::Hold => SegmentKind::Hold,
238 Interpolation::Linear => SegmentKind::Linear,
239 Interpolation::CubicBezier(_) => SegmentKind::Timing,
240 Interpolation::ValueBezier(_) => SegmentKind::Value,
241 Interpolation::Steps(_) => SegmentKind::Steps,
242 Interpolation::Points { .. } => SegmentKind::Points,
243 },
244 }
245 })
246 .collect()
247}
248
249#[must_use]
253pub fn sample(animation: &Animated<f32>, times: &[MediaTime]) -> Vec<CurveSample> {
254 times
255 .iter()
256 .map(|time| CurveSample {
257 value: sample_scalar(animation, *time, &SampleContext::NONE),
258 velocity: match animation {
259 Animated::Keyframes {
260 keyframes,
261 before,
262 after,
263 } => velocity(keyframes, *before, *after, *time),
264 _ => 0.0,
265 },
266 })
267 .collect()
268}
269
270fn per_second(slope: f64, left: &Keyframe<f32>, right: &Keyframe<f32>) -> f64 {
271 let seconds = span(left.time, right.time) / span(MediaTime(0), MediaTime(TICKS_PER_SECOND));
272 let velocity = slope / seconds;
273 if velocity.is_nan() {
274 0.0
275 } else {
276 velocity.clamp(-f64::MAX, f64::MAX)
277 }
278}
279
280fn slope_at(left: &Keyframe<f32>, right: &Keyframe<f32>, progress: f64) -> f64 {
281 let change = f64::from(right.value) - f64::from(left.value);
282 let slope = match left.interpolation {
283 Interpolation::Hold | Interpolation::Steps(_) => 0.0,
284 Interpolation::Points { ref points } => {
285 alpha2_model::easing_points_slope(points, progress) * change
286 }
287 Interpolation::Linear => change,
288 Interpolation::CubicBezier(curve) => {
289 let slope = curve.slope(progress) * change;
290 if slope.is_nan() { 0.0 } else { slope }
291 }
292 Interpolation::ValueBezier(curve) => curve.slope(left.value, right.value, progress),
293 };
294 per_second(slope, left, right)
295}
296
297fn continued_slope(left: &Keyframe<f32>, right: &Keyframe<f32>, at_end: bool) -> f64 {
298 let change = f64::from(right.value) - f64::from(left.value);
299 let slope = match left.interpolation {
300 Interpolation::ValueBezier(curve) => curve.end_slope(left.value, right.value, at_end),
301 ref timing => timing.end_slope(at_end).unwrap_or(0.0) * change,
302 };
303 per_second(slope, left, right)
304}
305
306fn slope_before(keyframes: &[Keyframe<f32>], at: i128) -> f64 {
307 let right = keyframes.partition_point(|keyframe| i128::from(keyframe.time.ticks()) < at);
308 slope_in(&keyframes[right - 1], &keyframes[right], at)
309}
310
311fn slope_after(keyframes: &[Keyframe<f32>], at: i128) -> f64 {
312 let right = keyframes.partition_point(|keyframe| i128::from(keyframe.time.ticks()) <= at);
313 slope_in(&keyframes[right - 1], &keyframes[right], at)
314}
315
316#[expect(
317 clippy::cast_precision_loss,
318 reason = "ticks as a fraction of a segment"
319)]
320fn slope_in(left: &Keyframe<f32>, right: &Keyframe<f32>, at: i128) -> f64 {
321 let start = i128::from(left.time.ticks());
322 let progress = (at - start) as f64 / (i128::from(right.time.ticks()) - start) as f64;
323 slope_at(left, right, progress)
324}
325
326fn velocity(
327 keyframes: &[Keyframe<f32>],
328 before: Extrapolation,
329 after: Extrapolation,
330 time: MediaTime,
331) -> f64 {
332 let [first, .., last] = keyframes else {
333 return 0.0;
334 };
335 let (start, end, at) = (
336 i128::from(first.time.ticks()),
337 i128::from(last.time.ticks()),
338 i128::from(time.ticks()),
339 );
340 let period = end - start;
341 let side = if at <= start {
342 before
343 } else if at > end {
344 after
345 } else {
346 return slope_before(keyframes, at);
347 };
348 match side {
349 Extrapolation::Hold => 0.0,
350 Extrapolation::Linear if at > end => {
351 continued_slope(&keyframes[keyframes.len() - 2], last, true)
352 }
353 Extrapolation::Linear => continued_slope(first, &keyframes[1], false),
354 Extrapolation::Repeat | Extrapolation::RepeatOffset => {
355 let offset = (at - start).rem_euclid(period);
356 slope_before(keyframes, start + if offset == 0 { period } else { offset })
357 }
358 Extrapolation::PingPong => {
359 let offset = (at - start).rem_euclid(2 * period);
360 if offset == 0 {
361 0.0 - slope_after(keyframes, start)
362 } else if offset <= period {
363 slope_before(keyframes, start + offset)
364 } else {
365 0.0 - slope_after(keyframes, start + 2 * period - offset)
366 }
367 }
368 }
369}
370
371struct Bounds([f64; 2]);
372
373impl Bounds {
374 fn add(&mut self, value: f64) {
375 self.0 = [self.0[0].min(value), self.0[1].max(value)];
376 }
377}
378
379fn keyed_bounds(keyframes: &[Keyframe<f32>], from: i64, to: i64, bounds: &mut Bounds) {
380 for (index, left) in keyframes.iter().enumerate() {
381 let start = left.time.ticks();
382 if start > to {
383 break;
384 }
385 let Some(right) = keyframes.get(index + 1) else {
386 if start >= from {
387 bounds.add(f64::from(left.value));
388 }
389 break;
390 };
391 let end = right.time.ticks();
392 if end < from {
393 continue;
394 }
395 let held = matches!(left.interpolation, Interpolation::Hold);
396 if start >= from || (held && end > from) {
397 bounds.add(f64::from(left.value));
398 }
399 let length = span(left.time, right.time);
400 #[expect(clippy::cast_precision_loss, reason = "ticks as coordinates")]
401 let (low, high) = (from as f64, to as f64);
402 if let Interpolation::Points { points } = &left.interpolation {
403 let change = f64::from(right.value) - f64::from(left.value);
404 for point in points {
405 let time = coordinate(left.time) + f64::from(point.x) * length;
406 if time >= low && time <= high {
407 bounds.add(f64::from(left.value) + change * f64::from(point.y));
408 }
409 }
410 }
411 let Some(cubic) = Cubic::of(left, right) else {
412 continue;
413 };
414 for u in cubic.turns() {
415 let time = coordinate(left.time) + cubic.progress_at(u) * length;
416 if time >= low && time <= high {
417 bounds.add(cubic.value_at(u));
418 }
419 }
420 }
421}
422
423#[must_use]
429pub fn range(animation: &Animated<f32>, range: TimeRange) -> [f64; 2] {
430 let from = range.start().ticks();
431 let to = range.end().ticks().saturating_sub(1).max(from);
432 let value = |tick: i64| {
433 f64::from(sample_scalar(
434 animation,
435 MediaTime(tick),
436 &SampleContext::NONE,
437 ))
438 };
439 let mut bounds = Bounds([value(from); 2]);
440 bounds.add(value(to));
441 let Animated::Keyframes {
442 keyframes,
443 before,
444 after,
445 } = animation
446 else {
447 return bounds.0;
448 };
449 let [first, .., last] = keyframes.as_slice() else {
450 return bounds.0;
451 };
452 let mut spelled = animation.clone();
453 if materialize(&mut spelled, range).is_ok() {
454 if let Animated::Keyframes { keyframes, .. } = &spelled {
455 keyed_bounds(keyframes, from, to, &mut bounds);
456 }
457 return bounds.0;
458 }
459 let (start, end) = (first.time.ticks(), last.time.ticks());
460 if from <= end && to >= start {
461 keyed_bounds(keyframes, from.max(start), to.min(end), &mut bounds);
462 }
463 let mut whole = Bounds([f64::from(first.value); 2]);
464 keyed_bounds(keyframes, start, end, &mut whole);
465 let travel = f64::from(last.value) - f64::from(first.value);
466 let period = i128::from(end) - i128::from(start);
467 let pass = |tick: i64| (i128::from(tick) - i128::from(start)).div_euclid(period);
468 for (reached, side, passes) in [
469 (from < start, *before, [pass(from), -1]),
470 (to >= end, *after, [1, pass(to)]),
471 ] {
472 if !reached {
473 continue;
474 }
475 match side {
476 Extrapolation::Hold | Extrapolation::Linear => {}
477 Extrapolation::Repeat | Extrapolation::PingPong => {
478 bounds.add(whole.0[0]);
479 bounds.add(whole.0[1]);
480 }
481 Extrapolation::RepeatOffset => {
482 for pass in passes {
483 #[expect(clippy::cast_precision_loss, reason = "a count of passes")]
484 let offset = pass as f64 * travel;
485 bounds.add(whole.0[0] + offset);
486 bounds.add(whole.0[1] + offset);
487 }
488 }
489 }
490 }
491 bounds.0
492}
493
494pub(crate) fn segment_value(left: &Keyframe<f32>, right: &Keyframe<f32>, tick: i64) -> f32 {
495 narrow(wide::curve_value(left, right, tick))
496}
497
498pub(crate) fn between_keys(
499 times: impl ExactSizeIterator<Item = MediaTime> + Clone,
500 time: MediaTime,
501) -> Result<(usize, f64), CurveError> {
502 let count = times.len();
503 let (Some(first), Some(last)) = (times.clone().next(), times.clone().last()) else {
504 return Err(CurveError::Empty);
505 };
506 if time < first || time > last {
507 return Err(CurveError::OutsideKeys);
508 }
509 if count >= MAX_KEYFRAMES {
510 return Err(CurveError::TooManyKeys);
511 }
512 let mut left = 0;
513 let mut bounds = (first, last);
514 for (index, key) in times.enumerate() {
515 if key == time {
516 return Err(CurveError::OnAKey);
517 }
518 if key < time {
519 left = index;
520 bounds.0 = key;
521 } else {
522 bounds.1 = key;
523 break;
524 }
525 }
526 Ok((left, span(bounds.0, time) / span(bounds.0, bounds.1)))
527}
528
529pub fn insert_key(animation: &mut Animated<f32>, time: MediaTime) -> Result<(), CurveError> {
540 let Animated::Keyframes { keyframes, .. } = animation else {
541 return Err(CurveError::NotKeyed);
542 };
543 let (index, _) = between_keys(keyframes.iter().map(|key| key.time), time)?;
544 wide::split_at(keyframes, index, time)
545}
546
547fn timing_parts(
548 interpolation: &Interpolation,
549 progress: f64,
550) -> Result<(Interpolation, Interpolation), CurveError> {
551 match interpolation {
552 Interpolation::Hold => Ok((Interpolation::Hold, Interpolation::Hold)),
553 Interpolation::Linear => Ok((Interpolation::Linear, Interpolation::Linear)),
554 Interpolation::CubicBezier(curve) => curve
555 .between(0.0, progress)
556 .zip(curve.between(progress, 1.0))
557 .map(|(leading, trailing)| {
558 (
559 Interpolation::CubicBezier(leading),
560 Interpolation::CubicBezier(trailing),
561 )
562 })
563 .ok_or(CurveError::LevelSegment),
564 Interpolation::Points { points } => {
565 let cut = alpha2_model::easing_points_at(points, progress);
566 let part = |start: f64, end: f64, low: f64, high: f64| {
567 let rise = high - low;
568 (rise != 0.0)
569 .then(|| {
570 alpha2_model::easing_points_between(points, start, end, |y| {
571 (y - low) / rise
572 })
573 })
574 .flatten()
575 .map(|points| Interpolation::Points { points })
576 };
577 part(0.0, progress, 0.0, cut)
578 .zip(part(progress, 1.0, cut, 1.0))
579 .ok_or(CurveError::LevelSegment)
580 }
581 Interpolation::ValueBezier(_) | Interpolation::Steps(_) => Err(CurveError::LevelSegment),
582 }
583}
584
585pub fn insert_eased_key<T>(
594 animation: &mut Animated<T>,
595 time: MediaTime,
596 value: T,
597) -> Result<(), CurveError> {
598 let Animated::Keyframes { keyframes, .. } = animation else {
599 return Err(CurveError::NotKeyed);
600 };
601 let (index, progress) = between_keys(keyframes.iter().map(|key| key.time), time)?;
602 let (leading, trailing) = timing_parts(&keyframes[index].interpolation, progress)?;
603 keyframes[index].interpolation = leading;
604 keyframes.insert(
605 index + 1,
606 Keyframe {
607 time,
608 value,
609 interpolation: trailing,
610 },
611 );
612 Ok(())
613}
614
615pub fn insert_point_key(
624 animation: &mut AnimatedPoint,
625 time: MediaTime,
626 aspect: f64,
627) -> Result<(), CurveError> {
628 let AnimatedPoint::Keyframes { keyframes, .. } = animation else {
629 return Err(CurveError::NotKeyed);
630 };
631 let (index, progress) = between_keys(keyframes.iter().map(|key| key.time), time)?;
632 let (left, right) = (&keyframes[index], &keyframes[index + 1]);
633 let amount = match left.interpolation {
634 Interpolation::Hold => {
635 let held = PointKeyframe {
636 time,
637 value: left.value,
638 interpolation: Interpolation::Hold,
639 out_tangent: Vec2::default(),
640 in_tangent: Vec2::default(),
641 };
642 keyframes.insert(index + 1, held);
643 return Ok(());
644 }
645 Interpolation::Linear => progress,
646 Interpolation::CubicBezier(curve) => curve.apply(progress),
647 Interpolation::Points { ref points } => alpha2_model::easing_points_at(points, progress),
648 Interpolation::ValueBezier(_) | Interpolation::Steps(_) => {
649 return Err(CurveError::LevelSegment);
650 }
651 };
652 if !(0.0..=1.0).contains(&amount) {
653 return Err(CurveError::OffThePath);
654 }
655 let (leading, trailing) = timing_parts(&left.interpolation, progress)?;
656 let straight = left.out_tangent.is_zero() && right.in_tangent.is_zero();
657 let aspect = if aspect.is_finite() && aspect > 0.0 {
658 aspect
659 } else {
660 1.0
661 };
662 let point = |value: Vec2| {
663 alpha2_geometry::kurbo::Point::new(f64::from(value.x) * aspect, f64::from(value.y))
664 };
665 let vector = |value: Vec2| {
666 alpha2_geometry::kurbo::Vec2::new(f64::from(value.x) * aspect, f64::from(value.y))
667 };
668 let cut = alpha2_geometry::spatial::cut_along(
669 point(left.value),
670 vector(left.out_tangent),
671 vector(right.in_tangent),
672 point(right.value),
673 amount,
674 );
675 let back = |x: f64, y: f64| Vec2::new(narrow(x / aspect), narrow(y));
676 let tangent = |tangent: alpha2_geometry::kurbo::Vec2| {
677 if straight {
678 Vec2::default()
679 } else {
680 back(tangent.x, tangent.y)
681 }
682 };
683 let added = PointKeyframe {
684 time,
685 value: back(cut.point.x, cut.point.y),
686 interpolation: trailing,
687 out_tangent: tangent(cut.cut_out),
688 in_tangent: tangent(cut.cut_in),
689 };
690 keyframes[index].interpolation = leading;
691 keyframes[index].out_tangent = tangent(cut.from_out);
692 keyframes[index + 1].in_tangent = tangent(cut.to_in);
693 keyframes.insert(index + 1, added);
694 Ok(())
695}
696
697pub fn to_value_curves(animation: &mut Animated<f32>) {
700 let Animated::Keyframes { keyframes, .. } = animation else {
701 return;
702 };
703 for index in 0..keyframes.len().saturating_sub(1) {
704 let (from, to) = (
705 f64::from(keyframes[index].value),
706 f64::from(keyframes[index + 1].value),
707 );
708 if let Some(curve) = as_value_curve(&keyframes[index].interpolation, from, to) {
709 keyframes[index].interpolation = Interpolation::ValueBezier(curve);
710 }
711 }
712}
713
714pub fn to_timing_curves(animation: &mut Animated<f32>) -> Result<(), CurveError> {
721 let Animated::Keyframes { keyframes, .. } = animation else {
722 return Ok(());
723 };
724 let mut rewritten = Vec::new();
725 for (index, pair) in keyframes.windows(2).enumerate() {
726 let Interpolation::ValueBezier(curve) = pair[0].interpolation else {
727 continue;
728 };
729 let change = f64::from(pair[1].value) - f64::from(pair[0].value);
730 let timing = timing_curve(curve, change).ok_or(CurveError::LevelSegment)?;
731 rewritten.push((index, Interpolation::CubicBezier(timing)));
732 }
733 for (index, interpolation) in rewritten {
734 keyframes[index].interpolation = interpolation;
735 }
736 Ok(())
737}
738
739fn timing_curve(curve: ValueBezier, change: f64) -> Option<CubicBezier> {
740 if change == 0.0 {
741 return None;
742 }
743 let (x1, x2) = curve.weights().unwrap_or((1.0 / 3.0, 2.0 / 3.0));
744 Some(CubicBezier::new(
745 x1,
746 narrow(f64::from(curve.leave) / change),
747 x2,
748 narrow(1.0 + f64::from(curve.arrive) / change),
749 ))
750}
751
752#[cfg(test)]
753#[path = "curves_tests.rs"]
754mod tests;