ferravex_play/camera/rail.rs
1//! Optional presentation-only intro/result rails, sampled at caller-owned seconds.
2//!
3//! Cubics use polynomial **parameter** time, not arc length. Routes use their
4//! measured polyline arc length (including a closed route's seam). Convert a
5//! curve with [`tessellate_route_into`] for approximate constant-distance travel;
6//! an incomplete tessellation never replaces the last good route. Neither path
7//! aims the camera along its tangent: orientation, roll, view distance and FOV
8//! come from authored [`RailKey3`] poses through the existing [`Transition3`].
9//! Segments prepare one normalized transition at construction. Each query samples
10//! a copy once; it never retargets a live transition or steps hidden simulation.
11//!
12//! Time is finite, nonnegative f64 seconds since this rail's start. Seeking is
13//! allowed, including backward and across many loops. Boundaries are right
14//! continuous: all zero-duration cuts at a boundary apply before the following
15//! segment starts. Once mode clamps at the exact final key; loop mode wraps at
16//! the exact duration, reporting an absolute cycle number. These are observations,
17//! not queued events or evidence of gameplay completion. Reduced motion always
18//! returns the exact final key as a finished cut, even for loops and held players.
19//!
20//! A raw sample reports cuts at start, exact authored cut boundaries and loop
21//! seams. [`RailPlayer3`] additionally marks backward seeks, crossed cuts/loops,
22//! initialization and reset as discontinuities. Hold retains the displayed sample;
23//! the host must freeze/rebase its own playhead before resume (no automatic clock
24//! offset). Reset forgets the pose/hold; the next query initializes at supplied
25//! time. Renderer interpolation/history must honor cuts. Subject history,
26//! collisions, accepted teleports, lens matrices and look-input tuning stay host
27//! owned. Local menus must continue authoritative network/replay progression.
28//!
29//! Storage/work: at most 64 borrowed segments, 1024 batch samples, 4096 route
30//! points and 8191 tessellation work nodes. Queries allocate nothing. Orientation
31//! fraction rounds to f32 (as in Transition3); position uses f64 path progress.
32//! Pose/lens bounds and shortest-arc half-turn ties are Transition3's conventions.
33//! Intermediate target rounding can still fail; errors preserve player state and
34//! the entire batch destination. A valid endpoint pair is not a guarantee of all
35//! interior samples. Loop counts >= 2^53 are rejected rather than cast/saturated;
36//! f64 time's existing loss of fractional precision cannot be recovered. Loop
37//! phase uses remainder of the supplied binary seconds, without epsilon snapping
38//! to decimal boundaries (for example, 1 second is just under ten stored 0.1s
39//! durations). Cycle counting follows that same remainder convention.
40//!
41//! # Executable optional intro/result recipe
42//!
43//! The host chooses this optional view without changing game defaults or ticks.
44//! This headless recipe exercises real authoring, sampling, hold, restart and an
45//! accepted Rig3 teleport handoff. No wall clock, renderer or subject mutation.
46//!
47//! ```rust
48//! use ferravex_math::{Vec3, curves::{CubicBezier3, TessellationOptions}, projection::NdcDepth};
49//! use ferravex_play::{navigation::Route3, camera::{Pose3, Rig3, Input3, Mode3,
50//! Target3, NoObstructions, transition::{Perspective3, Transition3, ViewHandedness}, rail::*}};
51//!
52//! fn main() -> Result<(), Box<dyn std::error::Error>> {
53//! let lens = Perspective3 { aspect: 16./9., near: 0.1, far: 1000.,
54//! handedness: ViewHandedness::Right, depth: NdcDepth::ZeroToOne };
55//! let key = |x| RailKey3 { pose: Pose3 { position: Vec3::X*x,
56//! target: Vec3::X*x - Vec3::Z*4., ..Pose3::default() }, projection: lens };
57//! let curve = CubicBezier3::new([Vec3::ZERO, Vec3::Y, Vec3::X*4.+Vec3::Y, Vec3::X*4.])?;
58//! let mut route = Route3::new(128).map_err(RailError::Route)?;
59//! let mut scratch = [Vec3::ZERO; 128];
60//! tessellate_route_into(curve, &mut route, &mut scratch, TessellationOptions {
61//! tolerance: 0.01, max_depth: 16, max_work: 1023 })?;
62//! let segments = [RailSegment3::new(RailPath3::Route(&route), key(0.), key(4.), 2.)?];
63//! let rail = Rail3::new(&segments, RailMode::Once)?;
64//! let mut intro = RailPlayer3::new(rail);
65//! assert!(intro.sample_at(0., false)?.cut);
66//! let visible = intro.sample_at(0.5, false)?;
67//! intro.hold();
68//! assert_eq!(intro.sample_at(90., false)?, visible);
69//! intro.resume(); // The host discarded paused time, retaining playhead 0.5.
70//! assert_eq!(intro.sample_at(0.5, false)?.pose, visible.pose);
71//! assert!(intro.sample_at(2., false)?.finished);
72//! intro.reset(); // Restart also resets host simulation/subject history.
73//! assert_eq!(intro.displayed(), None);
74//! assert!(intro.sample_at(0., false)?.cut);
75//! intro.hold();
76//! let result = intro.sample_at(0.2, true)?; // Motion preference overrides hold.
77//! assert!(result.cut && result.finished);
78//! assert_eq!(result.pose, key(4.).pose);
79//!
80//! // The host has accepted a teleport and reset its subject history first.
81//! let mut rig = Rig3::default();
82//! let accepted = rig.snap(Input3 { target: Target3::at(Vec3::X*100.),
83//! mode: Mode3::Follow { eye_offset: Vec3::Z*5., look_offset: Vec3::ZERO },
84//! fov_y: 1. }, &NoObstructions)?;
85//! let mut live = Transition3::new();
86//! live.cut(result.pose, result.projection)?;
87//! live.retarget_frame(&accepted, lens, 1.)?;
88//! assert_eq!(live.pose(), Some(accepted.pose));
89//! Ok(())
90//! }
91//! ```
92
93use super::{
94 Pose3,
95 transition::{Perspective3, Transition3, TransitionError},
96};
97use crate::navigation::{MAX_ROUTE_POINTS, NavigationError, Route3};
98use ferravex_math::{
99 Vec3,
100 curves::{CubicBezier3, CurveError, Tessellation, TessellationOptions, TessellationStatus},
101};
102
103/// Maximum authored segments, including zero-duration cuts. See module recipe.
104pub const MAX_RAIL_SEGMENTS: usize = 64;
105/// Maximum times accepted by one atomic batch. See [`Rail3::sample_into`].
106pub const MAX_RAIL_SAMPLES: usize = 1024;
107/// Maximum curve subdivision work accepted by [`tessellate_route_into`].
108pub const MAX_RAIL_TESSELLATION_WORK: usize = 8191;
109
110/// Authored world-space look pose and explicit host projection intent.
111/// See module recipe. Existing public camera literals/defaults are unchanged.
112#[derive(Clone, Copy, Debug, PartialEq)]
113pub struct RailKey3 {
114 pub pose: Pose3,
115 pub projection: Perspective3,
116}
117
118/// Position source; orientation is independent. See [`RailSegment3::new`].
119#[derive(Clone, Copy)]
120pub enum RailPath3<'a> {
121 /// An explicit zero-duration discontinuity; permits projection changes.
122 Cut,
123 /// Full cubic, uniformly in polynomial parameter, without tessellation.
124 Cubic(CubicBezier3),
125 /// Full immutable route, uniformly in measured polyline arc distance.
126 /// A closed route ends at its first point; zero-length nonempty routes work.
127 Route(&'a Route3),
128}
129
130/// Playback topology. Loop seams are explicit cuts, even if poses happen to match.
131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
132pub enum RailMode {
133 Once,
134 Loop,
135}
136
137/// Rejected authoring/query; no partial player or batch output is committed.
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139#[non_exhaustive]
140pub enum RailError {
141 /// Empty/oversized rail, batch, scratch or tessellation work budget.
142 Capacity,
143 /// Nonfinite/negative time or duration; durations exceed 3600 seconds.
144 InvalidTime,
145 /// Positive-duration cut or zero-duration moving segment.
146 InvalidCut,
147 /// Empty route or position source does not meet both authored eyes.
148 InvalidPath,
149 /// Adjacent end/start keys differ. Insert an explicit cut instead.
150 Disconnected,
151 /// A loop has no positive duration, or adding a duration lost its boundary.
152 InvalidTimeline,
153 /// Loop count or rounded interior pose is not representable.
154 NumericalLimit,
155 Transition(TransitionError),
156 Curve(CurveError),
157 Route(NavigationError),
158 /// Scratch contains only a prefix; the destination route is unchanged.
159 IncompleteCurve(TessellationStatus),
160}
161impl std::fmt::Display for RailError {
162 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163 write!(f, "camera rail: {self:?}")
164 }
165}
166impl std::error::Error for RailError {}
167impl From<TransitionError> for RailError {
168 fn from(e: TransitionError) -> Self {
169 match e {
170 TransitionError::NumericalLimit => Self::NumericalLimit,
171 other => Self::Transition(other),
172 }
173 }
174}
175
176/// Transactionally replace an open route only after a complete curve tessellation.
177///
178/// Scratch is disposable work space and may change on failure. The previous
179/// route is always retained on error, including its topology and capacity. Work
180/// above 8191 or scratch above 4096 points is rejected before tessellation. A
181/// plain `RailPath3::Route` trusts the supplied route's authored provenance;
182/// use this adapter instead of installing an unchecked tessellation prefix.
183/// See the executable module recipe.
184pub fn tessellate_route_into(
185 curve: CubicBezier3,
186 route: &mut Route3,
187 scratch: &mut [Vec3],
188 options: TessellationOptions,
189) -> Result<Tessellation, RailError> {
190 if scratch.len() > MAX_ROUTE_POINTS || options.max_work > MAX_RAIL_TESSELLATION_WORK {
191 return Err(RailError::Capacity);
192 }
193 let result = curve
194 .tessellate_into(scratch, options)
195 .map_err(RailError::Curve)?;
196 if result.status != TessellationStatus::Complete || result.covered_until != 1. {
197 return Err(RailError::IncompleteCurve(result.status));
198 }
199 route
200 .set(&scratch[..result.written])
201 .map_err(RailError::Route)?;
202 Ok(result)
203}
204
205/// Immutable prepared segment. Borrowed routes cannot change during playback.
206/// See module recipe; construction allocates nothing, as do subsequent samples.
207#[derive(Clone, Copy)]
208pub struct RailSegment3<'a> {
209 path: RailPath3<'a>,
210 start: RailKey3,
211 end: RailKey3,
212 duration: f64,
213 orientation: Transition3,
214}
215impl<'a> RailSegment3<'a> {
216 /// Prepare shortest-arc orientation, distance and FOV once via Transition3.
217 /// Positive durations are finite `0 < seconds <= 3600` and require identical
218 /// projection descriptors. Full path endpoints must exactly equal key eyes.
219 /// Cuts require zero seconds, validate both keys and allow a different lens.
220 /// All route vertices/cubic controls must lie within the transition eye bound
221 /// (abs component <= 1e6); degenerate look poses are rejected, stationary
222 /// paths are allowed. See module recipe for a checked construction.
223 pub fn new(
224 path: RailPath3<'a>,
225 start: RailKey3,
226 end: RailKey3,
227 seconds: f64,
228 ) -> Result<Self, RailError> {
229 if !seconds.is_finite() || !(0. ..=3600.).contains(&seconds) {
230 return Err(RailError::InvalidTime);
231 }
232 if matches!(path, RailPath3::Cut) != (seconds == 0.) {
233 return Err(RailError::InvalidCut);
234 }
235 let mut orientation = Transition3::new();
236 orientation.cut(start.pose, start.projection)?;
237 let mut validate = Transition3::new();
238 validate.cut(end.pose, end.projection)?;
239 if seconds > 0. {
240 orientation.retarget(end.pose, end.projection, 0.25)?;
241 let valid_eye = |v: &Vec3| v.is_finite() && v.abs().max_element() <= 1e6;
242 let (first, last) = match path {
243 RailPath3::Cut => unreachable!(),
244 RailPath3::Cubic(curve) => {
245 let controls = curve.control_points();
246 if !controls.iter().all(valid_eye) {
247 return Err(RailError::InvalidPath);
248 }
249 (controls[0], controls[3])
250 }
251 RailPath3::Route(route) => {
252 if route.points().is_empty() || !route.points().iter().all(valid_eye) {
253 return Err(RailError::InvalidPath);
254 }
255 (
256 route
257 .sample_progress(0.)
258 .map_err(RailError::Route)?
259 .unwrap()
260 .position,
261 route
262 .sample_progress(1.)
263 .map_err(RailError::Route)?
264 .unwrap()
265 .position,
266 )
267 }
268 };
269 if first != start.pose.position || last != end.pose.position {
270 return Err(RailError::InvalidPath);
271 }
272 }
273 Ok(Self {
274 path,
275 start,
276 end,
277 duration: seconds,
278 orientation,
279 })
280 }
281
282 fn key_at(&self, fraction: f64) -> Result<RailKey3, RailError> {
283 if fraction == 0. {
284 return Ok(self.start);
285 }
286 if fraction == 1. {
287 return Ok(self.end);
288 }
289 let position = match self.path {
290 RailPath3::Cut => return Ok(self.end),
291 RailPath3::Cubic(curve) => curve.position(fraction).map_err(RailError::Curve)?,
292 RailPath3::Route(route) => {
293 route
294 .sample_progress(fraction)
295 .map_err(RailError::Route)?
296 .unwrap()
297 .position
298 }
299 };
300 let mut orientation = self.orientation;
301 // One normalized sample of an already prepared segment, no time stepping.
302 let delta = ((fraction * 0.25) as f32).min(0.25_f32.next_down());
303 let base = orientation.advance(delta)?.unwrap();
304 let pose = Pose3 {
305 position,
306 target: Vec3::from_array(std::array::from_fn(|i| {
307 (f64::from(position[i]) + f64::from(base.target[i]) - f64::from(base.position[i]))
308 as f32
309 })),
310 ..base
311 };
312 let mut validate = Transition3::new();
313 validate
314 .cut(pose, self.start.projection)
315 .map_err(|_| RailError::NumericalLimit)?;
316 Ok(RailKey3 {
317 pose,
318 projection: self.start.projection,
319 })
320 }
321}
322
323/// A presentation observation; never an obstruction-tested camera frame.
324/// `cycle` is an absolute loop count, not a count of events since the last call.
325/// `looped` denotes an exact loop seam for raw queries, or any crossed loop for
326/// a player. `cut` requests renderer history discard. See module time semantics.
327#[derive(Clone, Copy, Debug, PartialEq)]
328pub struct RailSample3 {
329 pub pose: Pose3,
330 pub projection: Perspective3,
331 pub segment: usize,
332 pub cycle: u64,
333 pub looped: bool,
334 pub cut: bool,
335 pub finished: bool,
336}
337
338/// Bounded immutable timeline over caller-owned prepared segments.
339#[derive(Clone, Copy)]
340pub struct Rail3<'a> {
341 segments: &'a [RailSegment3<'a>],
342 mode: RailMode,
343 duration: f64,
344}
345impl<'a> Rail3<'a> {
346 /// Validate capacity, exact adjacent-key continuity and representable timing.
347 /// Loops require positive total duration; a Once rail may contain only cuts.
348 /// No allocation or root registration is needed beyond `camera::rail`.
349 /// See module recipe.
350 pub fn new(segments: &'a [RailSegment3<'a>], mode: RailMode) -> Result<Self, RailError> {
351 if segments.is_empty() || segments.len() > MAX_RAIL_SEGMENTS {
352 return Err(RailError::Capacity);
353 }
354 let mut duration = 0.;
355 for (index, segment) in segments.iter().enumerate() {
356 if index > 0 && segments[index - 1].end != segment.start {
357 return Err(RailError::Disconnected);
358 }
359 let next = duration + segment.duration;
360 if segment.duration > 0. && next <= duration {
361 return Err(RailError::InvalidTimeline);
362 }
363 duration = next;
364 }
365 if mode == RailMode::Loop && duration == 0. {
366 return Err(RailError::InvalidTimeline);
367 }
368 Ok(Self {
369 segments,
370 mode,
371 duration,
372 })
373 }
374 /// Total authored seconds, before wrapping. See module recipe.
375 pub fn duration(&self) -> f64 {
376 self.duration
377 }
378
379 /// Stateless absolute-time query. Seeking/backward sampling retains no state.
380 /// Reduced motion selects the final key immediately, ignoring loop topology.
381 /// Finite nonnegative time is required even in reduced-motion mode.
382 /// See module recipe and [`RailPlayer3`] for crossed-boundary detection.
383 pub fn sample_at(&self, seconds: f64, reduced_motion: bool) -> Result<RailSample3, RailError> {
384 check_time(seconds)?;
385 let last = self.segments.len() - 1;
386 let make = |key: RailKey3, segment, cycle, looped, cut, finished| RailSample3 {
387 pose: key.pose,
388 projection: key.projection,
389 segment,
390 cycle,
391 looped,
392 cut,
393 finished,
394 };
395 if reduced_motion {
396 return Ok(make(self.segments[last].end, last, 0, false, true, true));
397 }
398 let (time, cycle) = if self.mode == RailMode::Loop {
399 let mut cycles = (seconds / self.duration).floor();
400 if cycles >= 9007199254740992. {
401 return Err(RailError::NumericalLimit);
402 }
403 // Division can round a quotient just below an integer up to it.
404 // Fused residual testing keeps the cycle consistent with remainder,
405 // including 1.0 % 0.1, without losing the retained phase.
406 if cycles.mul_add(self.duration, -seconds) > 0. {
407 cycles -= 1.;
408 }
409 (seconds % self.duration, cycles as u64)
410 } else {
411 (seconds.min(self.duration), 0)
412 };
413 let looped = cycle > 0 && time == 0.;
414 let mut cut = time == 0.;
415 let mut start = 0.;
416 for (index, segment) in self.segments.iter().enumerate() {
417 let end = start + segment.duration;
418 if segment.duration == 0. {
419 cut |= time == start;
420 } else if time < end {
421 let key = segment.key_at(((time - start) / segment.duration).clamp(0., 1.))?;
422 return Ok(make(key, index, cycle, looped, cut, false));
423 }
424 start = end;
425 }
426 Ok(make(
427 self.segments[last].end,
428 last,
429 cycle,
430 looped,
431 cut,
432 true,
433 ))
434 }
435
436 /// Sample up to 1024 supplied times into a caller slice. Entire destination
437 /// (including unused tail) is unchanged on any error, including a late numeric
438 /// failure. Success writes exactly `times.len()` entries. Empty input succeeds.
439 /// Validates in one pass, then writes in a second: bounded O(times * segments).
440 /// No allocation; immutable paths guarantee repeatability within the call.
441 ///
442 /// ```
443 /// use ferravex_math::{Vec3, projection::NdcDepth};
444 /// use ferravex_play::camera::{Pose3, transition::*, rail::*};
445 /// let key = RailKey3 { pose: Pose3::default(), projection: Perspective3 {
446 /// aspect: 1., near: 0.1, far: 100., handedness: ViewHandedness::Right,
447 /// depth: NdcDepth::ZeroToOne } };
448 /// let segments = [RailSegment3::new(RailPath3::Cut, key, key, 0.)?];
449 /// let rail = Rail3::new(&segments, RailMode::Once)?;
450 /// let sentinel = rail.sample_at(0., false)?;
451 /// let mut out = [sentinel; 3];
452 /// assert!(rail.sample_into(&[0., f64::NAN], false, &mut out).is_err());
453 /// assert_eq!(out, [sentinel; 3]);
454 /// assert_eq!(rail.sample_into(&[0., 2.], false, &mut out)?, 2);
455 /// assert_eq!(out[2], sentinel);
456 /// # Ok::<(), RailError>(())
457 /// ```
458 pub fn sample_into(
459 &self,
460 times: &[f64],
461 reduced_motion: bool,
462 output: &mut [RailSample3],
463 ) -> Result<usize, RailError> {
464 if times.len() > MAX_RAIL_SAMPLES || output.len() < times.len() {
465 return Err(RailError::Capacity);
466 }
467 for &time in times {
468 self.sample_at(time, reduced_motion)?;
469 }
470 for (&time, slot) in times.iter().zip(output.iter_mut()) {
471 *slot = self.sample_at(time, reduced_motion)?;
472 }
473 Ok(times.len())
474 }
475
476 fn crosses_cut(&self, from: f64, to: f64) -> bool {
477 let mut boundary = 0.;
478 self.segments.iter().any(|segment| {
479 let crossed = segment.duration == 0. && from < boundary && boundary <= to;
480 boundary += segment.duration;
481 crossed
482 })
483 }
484}
485fn check_time(seconds: f64) -> Result<(), RailError> {
486 if seconds.is_finite() && seconds >= 0. {
487 Ok(())
488 } else {
489 Err(RailError::InvalidTime)
490 }
491}
492
493/// Optional retained display/hold/discontinuity adapter over a fixed rail.
494/// No clock, accumulator or simulation ownership. See executable module recipe.
495#[derive(Clone, Copy)]
496pub struct RailPlayer3<'a> {
497 rail: Rail3<'a>,
498 displayed: Option<RailSample3>,
499 time: f64,
500 held: bool,
501 generation: u64,
502}
503impl<'a> RailPlayer3<'a> {
504 /// Empty player, generation zero; the first successful sample is a cut.
505 pub fn new(rail: Rail3<'a>) -> Self {
506 Self {
507 rail,
508 displayed: None,
509 time: 0.,
510 held: false,
511 generation: 0,
512 }
513 }
514 /// Last displayed observation, including its original outcome flags.
515 pub fn displayed(&self) -> Option<RailSample3> {
516 self.displayed
517 }
518 /// Local wrapping discontinuity counter; not a tick ID or global identity.
519 pub fn generation(&self) -> u64 {
520 self.generation
521 }
522 /// Whether ordinary valid samples retain the displayed pose/time.
523 pub fn is_held(&self) -> bool {
524 self.held
525 }
526 /// Hold current display; empty holds initialize on the next query.
527 pub fn hold(&mut self) -> bool {
528 let changed = !self.held;
529 self.held = true;
530 changed
531 }
532 /// Release hold; host must resume from its frozen/rebased playhead.
533 pub fn resume(&mut self) -> bool {
534 let changed = self.held;
535 self.held = false;
536 changed
537 }
538 /// Forget display/time, release hold, increment generation. See module recipe.
539 pub fn reset(&mut self) {
540 self.displayed = None;
541 self.time = 0.;
542 self.held = false;
543 self.generation = self.generation.wrapping_add(1);
544 }
545 /// Atomic supplied-time query. Hold discards valid supplied time; reduced
546 /// motion overrides hold and cuts to final. Invalid time still errors while
547 /// held. Backward seeks and crossed cuts/loops discard renderer history.
548 /// Repeated identical time/policy does not increment generation again.
549 /// Resuming after reduced motion cuts, preventing stale interpolation.
550 /// See module recipe.
551 pub fn sample_at(
552 &mut self,
553 seconds: f64,
554 reduced_motion: bool,
555 ) -> Result<RailSample3, RailError> {
556 check_time(seconds)?;
557 if self.held
558 && !reduced_motion
559 && let Some(displayed) = self.displayed
560 {
561 return Ok(displayed);
562 }
563 let mut sample = self.rail.sample_at(seconds, reduced_motion)?;
564 if let Some(previous) = self.displayed {
565 let changed_cycle = sample.cycle != previous.cycle;
566 sample.looped |= changed_cycle;
567 let (from, to) = if self.rail.mode == RailMode::Loop {
568 (self.time % self.rail.duration, seconds % self.rail.duration)
569 } else {
570 (self.time, seconds)
571 };
572 sample.cut |= seconds < self.time
573 || changed_cycle
574 || self.rail.crosses_cut(from, to)
575 || (previous.finished && self.rail.mode == RailMode::Loop)
576 || (previous.finished && !sample.finished);
577 if sample.cut
578 && (seconds != self.time
579 || sample.pose != previous.pose
580 || sample.projection != previous.projection
581 || sample.finished != previous.finished)
582 {
583 self.generation = self.generation.wrapping_add(1);
584 }
585 } else {
586 sample.cut = true;
587 self.generation = self.generation.wrapping_add(1);
588 }
589 self.displayed = Some(sample);
590 self.time = seconds;
591 if reduced_motion {
592 self.held = false;
593 }
594 Ok(sample)
595 }
596}