1use super::ReplayError;
7use ferravex_math::{Quat, Vec3};
8pub const MAX_SAMPLES: usize = 120_000;
9#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct Sample {
12 pub tick: u64,
13 pub position: Vec3,
14 pub rotation: Quat,
15 pub teleport: bool,
19}
20
21#[derive(Clone, Copy, Debug, PartialEq)]
29pub enum SampleState {
30 Empty,
32 BeforeStart {
34 first: Sample,
36 },
37 AfterEnd {
39 last: Sample,
41 },
42 Exact(Sample),
44 Interpolated {
46 sample: Sample,
48 from_tick: u64,
50 to_tick: u64,
52 },
53 Held {
56 sample: Sample,
58 from_tick: u64,
60 teleport_tick: u64,
62 },
63}
64
65impl SampleState {
66 pub fn sample(self) -> Option<Sample> {
81 match self {
82 Self::Exact(sample) | Self::Interpolated { sample, .. } | Self::Held { sample, .. } => {
83 Some(sample)
84 }
85 Self::Empty | Self::BeforeStart { .. } | Self::AfterEnd { .. } => None,
86 }
87 }
88}
89
90#[derive(Clone, Debug)]
91pub struct GhostTrack {
92 context: u64,
93 tick_hz: u16,
94 samples: Vec<Sample>,
95 capacity: usize,
96}
97impl GhostTrack {
98 pub fn new(context: u64, tick_hz: u16, capacity: usize) -> Result<Self, ReplayError> {
99 if !(1..=1000).contains(&tick_hz) || capacity > MAX_SAMPLES {
100 return Err(ReplayError::InvalidLimits);
101 }
102 Ok(Self {
103 context,
104 tick_hz,
105 samples: Vec::with_capacity(capacity),
106 capacity,
107 })
108 }
109 pub fn context(&self) -> u64 {
110 self.context
111 }
112 pub fn tick_hz(&self) -> u16 {
113 self.tick_hz
114 }
115 pub fn samples(&self) -> &[Sample] {
116 &self.samples
117 }
118 pub fn push(&mut self, mut sample: Sample) -> Result<(), ReplayError> {
139 if self.samples.len() == self.capacity {
140 return Err(ReplayError::Capacity);
141 }
142 if self.samples.last().is_some_and(|s| s.tick >= sample.tick) {
143 return Err(ReplayError::TickOrder);
144 }
145 if !sample.position.is_finite()
146 || sample.position.abs().max_element() > 1e6
147 || !sample.rotation.is_finite()
148 || sample.rotation.length_squared() < 1e-8
149 {
150 return Err(ReplayError::InvalidData);
151 }
152 sample.rotation = sample.rotation.normalize();
153 self.samples.push(sample);
154 Ok(())
155 }
156 pub fn sample(&self, tick: u64, alpha: f32) -> Option<Sample> {
162 if !alpha.is_finite() || !(0.0..1.0).contains(&alpha) {
163 return None;
164 }
165 let first = self.samples.first()?;
166 let last = self.samples.last()?;
167 if tick < first.tick || tick > last.tick || (tick == last.tick && alpha > 0.) {
168 return None;
169 }
170 let i = self.samples.partition_point(|s| s.tick <= tick) - 1;
171 let a = self.samples[i];
172 let Some(b) = self.samples.get(i + 1).copied() else {
173 return Some(a);
174 };
175 if b.teleport {
176 return Some(Sample { tick, ..a });
177 }
178 Some(interpolate(a, b, tick, alpha))
179 }
180
181 pub fn sample_checked(&self, tick: u64, alpha: f32) -> Result<SampleState, ReplayError> {
225 if !alpha.is_finite() || !(0.0..1.0).contains(&alpha) {
226 return Err(ReplayError::InvalidData);
227 }
228 let Some(&first) = self.samples.first() else {
229 return Ok(SampleState::Empty);
230 };
231 if tick < first.tick {
232 return Ok(SampleState::BeforeStart { first });
233 }
234 let last = self.samples[self.samples.len() - 1];
235 if tick > last.tick || (tick == last.tick && alpha > 0.) {
236 return Ok(SampleState::AfterEnd { last });
237 }
238 let i = self.samples.partition_point(|s| s.tick <= tick) - 1;
239 let a = self.samples[i];
240 if tick == a.tick && alpha == 0. {
241 return Ok(SampleState::Exact(a));
242 }
243 let b = self.samples[i + 1];
245 if b.teleport {
246 return Ok(SampleState::Held {
247 sample: Sample {
248 tick,
249 teleport: false,
250 ..a
251 },
252 from_tick: a.tick,
253 teleport_tick: b.tick,
254 });
255 }
256 Ok(SampleState::Interpolated {
257 sample: interpolate(a, b, tick, alpha),
258 from_tick: a.tick,
259 to_tick: b.tick,
260 })
261 }
262}
263
264fn interpolate(a: Sample, b: Sample, tick: u64, alpha: f32) -> Sample {
265 let t = ((tick - a.tick) as f64 + f64::from(alpha)) / (b.tick - a.tick) as f64;
266 Sample {
267 tick,
268 position: a.position.lerp(b.position, t as f32),
269 rotation: a.rotation.slerp(b.rotation, t as f32),
270 teleport: false,
271 }
272}
273#[cfg(test)]
274mod tests {
275 use super::*;
276
277 fn pose(tick: u64, x: f32, teleport: bool) -> Sample {
278 Sample {
279 tick,
280 position: Vec3::X * x,
281 rotation: Quat::IDENTITY,
282 teleport,
283 }
284 }
285
286 #[test]
287 fn checked_empty_and_invalid_fractions_are_distinct() {
288 let mut empty = GhostTrack::new(4, 64, 0).unwrap();
289 let mut populated = GhostTrack::new(4, 64, 1).unwrap();
290 populated.push(pose(10, 1., false)).unwrap();
291 assert_eq!(empty.push(pose(10, 1., false)), Err(ReplayError::Capacity));
292 for track in [&empty, &populated] {
293 for tick in [0, 10, u64::MAX] {
294 for alpha in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.1, 1., 2.] {
295 assert_eq!(
296 track.sample_checked(tick, alpha),
297 Err(ReplayError::InvalidData)
298 );
299 assert_eq!(track.sample(tick, alpha), None);
300 }
301 }
302 }
303 for tick in [0, 10, u64::MAX] {
304 for alpha in [0., -0., 0.5] {
305 assert_eq!(empty.sample_checked(tick, alpha), Ok(SampleState::Empty));
306 }
307 }
308 assert_eq!(SampleState::Empty.sample(), None);
309 assert!(empty.samples().is_empty());
310 }
311
312 #[test]
313 fn checked_single_key_has_inclusive_exact_and_exclusive_fractional_end() {
314 for tick in [0, 10, u64::MAX] {
315 let mut track = GhostTrack::new(4, 64, 1).unwrap();
316 track.push(pose(tick, 7., true)).unwrap();
317 let key = track.samples()[0];
318 for alpha in [0., -0.] {
319 let state = track.sample_checked(tick, alpha).unwrap();
320 assert_eq!(state, SampleState::Exact(key));
321 assert_eq!(state.sample(), Some(key));
322 }
323 for alpha in [
324 f32::from_bits(1),
325 0.5,
326 f32::from_bits(1.0_f32.to_bits() - 1),
327 ] {
328 let state = track.sample_checked(tick, alpha).unwrap();
329 assert_eq!(state, SampleState::AfterEnd { last: key });
330 assert_eq!(state.sample(), None);
331 }
332 if let Some(before) = tick.checked_sub(1) {
333 let state = track.sample_checked(before, 0.999).unwrap();
334 assert_eq!(state, SampleState::BeforeStart { first: key });
335 assert_eq!(state.sample(), None);
336 }
337 if let Some(after) = tick.checked_add(1) {
338 assert_eq!(
339 track.sample_checked(after, 0.),
340 Ok(SampleState::AfterEnd { last: key })
341 );
342 }
343 }
344 }
345
346 #[test]
347 fn checked_exact_keys_preserve_quaternion_sign_and_teleport_flag() {
348 let mut track = GhostTrack::new(4, 64, 3).unwrap();
349 for tick in [10, 20, 30] {
350 track
351 .push(Sample {
352 rotation: if tick == 20 {
353 -Quat::IDENTITY
354 } else {
355 Quat::IDENTITY
356 },
357 ..pose(tick, tick as f32, tick != 30)
358 })
359 .unwrap();
360 }
361 for &key in track.samples() {
362 assert_eq!(
363 track.sample_checked(key.tick, 0.),
364 Ok(SampleState::Exact(key))
365 );
366 }
367 assert!(!track.sample(20, 0.).unwrap().teleport);
369 assert!(
370 track
371 .sample_checked(20, 0.)
372 .unwrap()
373 .sample()
374 .unwrap()
375 .teleport
376 );
377 assert!(track.sample(15, 0.).unwrap().teleport);
378 assert!(
379 !track
380 .sample_checked(15, 0.)
381 .unwrap()
382 .sample()
383 .unwrap()
384 .teleport
385 );
386 assert_eq!(
387 track.sample_checked(9, 0.5),
388 Ok(SampleState::BeforeStart {
389 first: track.samples()[0]
390 })
391 );
392 assert_eq!(
393 track.sample_checked(30, 0.5),
394 Ok(SampleState::AfterEnd {
395 last: track.samples()[2]
396 })
397 );
398 }
399
400 #[test]
401 fn checked_teleports_hold_both_components_then_resume_continuous_motion() {
402 let mut track = GhostTrack::new(4, 64, 4).unwrap();
403 let turn = Quat::from_rotation_y(std::f32::consts::FRAC_PI_2);
404 for key in [
405 pose(10, 0., false),
406 Sample {
407 rotation: turn,
408 ..pose(20, 100., true)
409 },
410 pose(21, -100., true),
411 pose(25, -92., false),
412 ] {
413 track.push(key).unwrap();
414 }
415 let original = track.samples().to_vec();
416 for (tick, alpha, from, to) in [
418 (20, 0.5, 1, 2),
419 (19, 0.999, 0, 1),
420 (10, 0.5, 0, 1),
421 (15, 0., 0, 1),
422 (20, 0.5, 1, 2),
423 ] {
424 let expected = Sample {
425 tick,
426 teleport: false,
427 ..original[from]
428 };
429 let state = track.sample_checked(tick, alpha).unwrap();
430 assert_eq!(
431 state,
432 SampleState::Held {
433 sample: expected,
434 from_tick: original[from].tick,
435 teleport_tick: original[to].tick,
436 }
437 );
438 assert_eq!(state.sample(), Some(expected));
439 }
440 for index in [1, 2] {
441 assert_eq!(
442 track.sample_checked(original[index].tick, 0.),
443 Ok(SampleState::Exact(original[index]))
444 );
445 }
446 assert_eq!(
447 track.sample_checked(21, 0.5),
448 Ok(SampleState::Interpolated {
449 sample: pose(21, -99., false),
450 from_tick: 21,
451 to_tick: 25,
452 })
453 );
454 assert_eq!(track.samples(), original);
455 }
456
457 #[test]
458 fn checked_sparse_interpolation_uses_tick_gap_and_shortest_rotation() {
459 let mut track = GhostTrack::new(4, 64, 3).unwrap();
460 let start = u64::MAX - 20;
461 track.push(pose(start, 0., false)).unwrap();
462 track
463 .push(Sample {
464 rotation: -Quat::from_rotation_y(std::f32::consts::FRAC_PI_2),
465 ..pose(start + 10, 10., false)
466 })
467 .unwrap();
468 track.push(pose(u64::MAX, 50., true)).unwrap();
469 let state = track.sample_checked(start + 5, 0.5).unwrap();
470 assert!(
471 matches!(state, SampleState::Interpolated { from_tick, to_tick, .. }
472 if from_tick == start && to_tick == start + 10)
473 );
474 let sample = state.sample().unwrap();
475 assert_eq!(sample.position.x, 5.5);
476 assert_eq!(sample.tick, start + 5);
477 assert!(!sample.teleport);
478 assert!((sample.rotation.length_squared() - 1.).abs() < 1e-6);
479 let expected = Quat::from_rotation_y(std::f32::consts::FRAC_PI_2 * 0.55) * Vec3::X;
480 assert!((sample.rotation * Vec3::X - expected).length() < 1e-6);
481 assert_eq!(track.sample(start + 5, 0.5), Some(sample));
482 assert!(matches!(
483 track.sample_checked(u64::MAX - 1, 0.999).unwrap(),
484 SampleState::Held {
485 teleport_tick: u64::MAX,
486 ..
487 }
488 ));
489 assert_eq!(
490 track.sample_checked(u64::MAX, 0.),
491 Ok(SampleState::Exact(track.samples()[2]))
492 );
493 }
494
495 #[test]
496 fn checked_full_tick_span_never_wraps_or_extrapolates() {
497 let mut track = GhostTrack::new(4, 64, 2).unwrap();
498 track.push(pose(0, -1e6, false)).unwrap();
499 track.push(pose(u64::MAX, 1e6, false)).unwrap();
500 for tick in [0, 1, u64::MAX / 2, u64::MAX - 1] {
501 let state = track.sample_checked(tick, 0.5).unwrap();
502 assert!(matches!(
503 state,
504 SampleState::Interpolated {
505 from_tick: 0,
506 to_tick: u64::MAX,
507 ..
508 }
509 ));
510 let sample = state.sample().unwrap();
511 assert!(sample.position.is_finite());
512 assert!(sample.position.x.abs() <= 1e6);
513 assert!(sample.rotation.is_finite());
514 }
515 assert_eq!(
516 track.sample_checked(u64::MAX, 0.5),
517 Ok(SampleState::AfterEnd {
518 last: track.samples()[1]
519 })
520 );
521 }
522
523 #[test]
524 fn rejected_duplicate_decreasing_and_wrapped_ticks_preserve_history() {
525 let mut track = GhostTrack::new(4, 64, 3).unwrap();
526 track.push(pose(10, 0., false)).unwrap();
527 track.push(pose(20, 10., false)).unwrap();
528 let original = track.samples().to_vec();
529 let before = track.sample_checked(15, 0.5).unwrap();
530 for tick in [20, 19, 10, 0] {
531 assert_eq!(
532 track.push(pose(tick, 99., true)),
533 Err(ReplayError::TickOrder)
534 );
535 assert_eq!(track.samples(), original);
536 assert_eq!(track.sample_checked(15, 0.5), Ok(before));
537 }
538 track.push(pose(30, 20., false)).unwrap();
539 for tick in [30, 31] {
541 assert_eq!(
542 track.push(pose(tick, 99., true)),
543 Err(ReplayError::Capacity)
544 );
545 }
546 assert_eq!(track.samples().len(), 3);
547 let mut wrapping = GhostTrack::new(4, 64, 2).unwrap();
548 wrapping.push(pose(u64::MAX, 0., false)).unwrap();
549 assert_eq!(
550 wrapping.push(pose(0, 99., true)),
551 Err(ReplayError::TickOrder)
552 );
553 assert_eq!(wrapping.samples(), &[pose(u64::MAX, 0., false)]);
554 }
555
556 #[test]
557 fn rejected_invalid_poses_do_not_create_discontinuities() {
558 let mut track = GhostTrack::new(4, 64, 2).unwrap();
559 track.push(pose(10, 0., false)).unwrap();
560 let valid = pose(20, 10., true);
561 for invalid in [
562 Sample {
563 position: Vec3::NAN,
564 ..valid
565 },
566 Sample {
567 position: Vec3::X * 1_000_001.,
568 ..valid
569 },
570 Sample {
571 rotation: Quat::NAN,
572 ..valid
573 },
574 Sample {
575 rotation: Quat::from_xyzw(0., 0., 0., 0.),
576 ..valid
577 },
578 ] {
579 assert_eq!(track.push(invalid), Err(ReplayError::InvalidData));
580 assert_eq!(track.samples(), &[pose(10, 0., false)]);
581 }
582 track
583 .push(Sample {
584 rotation: Quat::IDENTITY * 2.,
585 ..valid
586 })
587 .unwrap();
588 assert_eq!(track.samples()[1], valid);
589 assert!(matches!(
590 track.sample_checked(15, 0.).unwrap(),
591 SampleState::Held {
592 teleport_tick: 20,
593 ..
594 }
595 ));
596 }
597
598 #[test]
599 fn sparse_interpolation_and_discontinuities() {
600 let mut g = GhostTrack::new(4, 64, 3).unwrap();
601 for (tick, x, teleport) in [
602 (u64::MAX - 20, 0., false),
603 (u64::MAX - 10, 10., false),
604 (u64::MAX, 50., true),
605 ] {
606 g.push(Sample {
607 tick,
608 position: Vec3::X * x,
609 rotation: Quat::IDENTITY,
610 teleport,
611 })
612 .unwrap();
613 }
614 assert_eq!(g.sample(u64::MAX - 15, 0.5).unwrap().position.x, 5.5);
615 assert_eq!(g.sample(u64::MAX - 5, 0.).unwrap().position.x, 10.);
616 assert!(g.sample(u64::MAX, 0.5).is_none());
617 assert!(g.sample(u64::MAX - 21, 0.).is_none());
618 }
619}