sciart_core/timeline.rs
1//! Looping scripted narratives and easing curves (SPEC-001 CORE-R38, CORE-R39).
2//!
3//! A scene such as a moon landing is a fixed script — descent, hover, touchdown, … —
4//! replayed forever. [`Timeline`] turns the scene's accumulated sim time into "which
5//! phase, and how far through it", and [`ease`] shapes that progress into motion.
6
7/// One non-empty phase, with its start offset precomputed so queries never re-sum.
8#[derive(Debug, Clone, Copy, PartialEq)]
9struct Phase {
10 /// Offset of this phase from the start of the cycle, in seconds.
11 start: f64,
12 duration: f64,
13 label: &'static str,
14 /// Position in the list given to [`Timeline::new`] (zero-length phases included).
15 index: usize,
16}
17
18/// Where a point in time falls inside a [`Timeline`] (CORE-R38).
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub struct Beat {
21 /// Index of the phase in the list passed to [`Timeline::new`] — skipped
22 /// zero-length phases keep their slot, so scenes can match on their own constants.
23 pub index: usize,
24 pub label: &'static str,
25 /// Seconds since the phase started, in `[0, duration)`.
26 pub local: f64,
27 /// `local / duration`, in `[0, 1)`.
28 pub progress: f64,
29}
30
31/// A looping sequence of labelled phases (CORE-R38).
32///
33/// Storage is one `Box<[Phase]>` built in [`Timeline::new`] — the only allocation.
34/// Taking `&'static` slices instead would forbid durations computed at runtime (from
35/// the canvas size or `ctx.rng`), and precomputing start offsets means a query is a
36/// `rem_euclid` plus an O(log n) binary search, with no summing and no allocation.
37#[derive(Debug, Clone, PartialEq)]
38pub struct Timeline {
39 /// Only phases with a finite, positive duration, in order.
40 phases: Box<[Phase]>,
41 total: f64,
42 /// Label reported by an empty timeline: the first phase's, if any.
43 fallback_label: &'static str,
44}
45
46impl Timeline {
47 /// Build a timeline from `(label, seconds)` pairs (CORE-R38).
48 ///
49 /// Phases whose duration is not a finite positive number (zero, negative, NaN, ∞)
50 /// are zero-length and never reported by [`Timeline::at`]. An infinite phase would
51 /// make the loop never wrap, which a scene can express by simply not using a
52 /// timeline, so it is treated as invalid rather than special-cased.
53 pub fn new(phases: &[(&'static str, f64)]) -> Self {
54 let mut total = 0.0;
55 let kept: Box<[Phase]> = phases
56 .iter()
57 .enumerate()
58 .filter(|(_, (_, d))| d.is_finite() && *d > 0.0)
59 .map(|(index, &(label, duration))| {
60 let start = total;
61 total += duration;
62 Phase {
63 start,
64 duration,
65 label,
66 index,
67 }
68 })
69 .collect();
70 // Sums of finite values can still overflow; such a timeline is unusable.
71 let (phases_kept, total) = if total.is_finite() {
72 (kept, total)
73 } else {
74 (Box::default(), 0.0)
75 };
76 Self {
77 phases: phases_kept,
78 total,
79 fallback_label: phases.first().map_or("", |p| p.0),
80 }
81 }
82
83 /// Length of one cycle in seconds; 0 for an empty or all-zero timeline (CORE-R38).
84 #[inline]
85 pub fn total(&self) -> f64 {
86 self.total
87 }
88
89 /// `true` when no phase has positive length, so every query reports phase 0.
90 #[inline]
91 pub fn is_empty(&self) -> bool {
92 self.phases.is_empty()
93 }
94
95 /// Split `t` into (completed cycles, offset in `[0, total)`), or `None` when the
96 /// timeline is empty. Non-finite `t` is treated as 0.
97 fn wrap(&self, t: f64) -> Option<(f64, f64)> {
98 if self.phases.is_empty() {
99 return None;
100 }
101 let t = if t.is_finite() { t } else { 0.0 };
102 let mut cycles = t.div_euclid(self.total);
103 let mut u = t.rem_euclid(self.total);
104 // For tiny negative `t`, `t + total` rounds to exactly `total`: that instant is
105 // (to within one ulp) the start of the next cycle.
106 if u >= self.total {
107 u = 0.0;
108 cycles += 1.0;
109 }
110 Some((cycles, u))
111 }
112
113 /// The phase active at sim time `t`, looping every [`Timeline::total`] seconds
114 /// (CORE-R38).
115 ///
116 /// Any finite `t`, including negative, maps into the cycle; non-finite `t` behaves
117 /// like `t = 0`. An empty timeline yields index 0 (labelled with the first phase
118 /// given, or `""`) with `local = progress = 0`.
119 pub fn at(&self, t: f64) -> Beat {
120 let Some((_, u)) = self.wrap(t) else {
121 return Beat {
122 index: 0,
123 label: self.fallback_label,
124 local: 0.0,
125 progress: 0.0,
126 };
127 };
128 // Last phase starting at or before `u`; phase 0 starts at 0 so this is >= 1.
129 let i = self
130 .phases
131 .partition_point(|p| p.start <= u)
132 .saturating_sub(1);
133 let p = &self.phases[i];
134 // `u < start + duration` in exact terms, but the subtraction can round up to
135 // `duration`; keep both outputs strictly inside their half-open ranges.
136 let local = (u - p.start).clamp(0.0, p.duration.next_down());
137 let progress = (local / p.duration).min(1.0f64.next_down());
138 Beat {
139 index: p.index,
140 label: p.label,
141 local,
142 progress,
143 }
144 }
145
146 /// Number of completed cycles at time `t`: `floor(t / total)`, so negative for
147 /// `t < 0`; saturates at the `i64` range and is 0 when empty or `t` is not finite
148 /// (CORE-R38).
149 pub fn cycle(&self, t: f64) -> i64 {
150 // Float-to-int `as` saturates, which is exactly the behaviour documented above.
151 self.wrap(t).map_or(0, |(cycles, _)| cycles as i64)
152 }
153}
154
155/// Easing curves mapping `[0, 1] → [0, 1]` monotonically with `f(0) = 0`, `f(1) = 1`
156/// (CORE-R39).
157///
158/// Inputs outside `[0, 1]` are clamped and NaN maps to 0, so a curve can be fed a raw
159/// [`Beat::progress`]-style value, or garbage, without producing garbage.
160pub mod ease {
161 /// Clamp to `[0, 1]`, NaN ⇒ 0 (`f64::clamp` would propagate NaN).
162 #[inline]
163 fn unit(x: f64) -> f64 {
164 if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) }
165 }
166
167 /// Hermite smoothstep `3x² − 2x³`: zero slope at both ends (CORE-R39).
168 #[inline]
169 pub fn smoothstep(x: f64) -> f64 {
170 let x = unit(x);
171 x * x * (3.0 - 2.0 * x)
172 }
173
174 /// Cubic ease-in-out: `4x³` then mirrored; passes through (½, ½) (CORE-R39).
175 #[inline]
176 pub fn in_out_cubic(x: f64) -> f64 {
177 let x = unit(x);
178 if x < 0.5 {
179 4.0 * x * x * x
180 } else {
181 let r = 2.0 - 2.0 * x;
182 1.0 - 0.5 * r * r * r
183 }
184 }
185
186 /// Quadratic ease-out `1 − (1 − x)²`: fast start, gentle landing (CORE-R39).
187 #[inline]
188 pub fn out_quad(x: f64) -> f64 {
189 let r = 1.0 - unit(x);
190 1.0 - r * r
191 }
192
193 /// Linear interpolation from `a` (at `t = 0`) to `b` (at `t = 1`) (CORE-R39).
194 ///
195 /// `t` is **not** clamped, so it extrapolates; compose with a curve above to stay
196 /// in range. Interpolating from the nearer endpoint makes the result exact at
197 /// `t = 0` and `t = 1` and exactly `a` when `a == b`; plain `a + (b − a)·t` can
198 /// miss `b` at `t = 1` by an ulp.
199 #[inline]
200 pub fn lerp(a: f64, b: f64, t: f64) -> f64 {
201 let d = b - a;
202 if t < 0.5 {
203 a + d * t
204 } else {
205 b - d * (1.0 - t)
206 }
207 }
208}