ferravex_play/camera/
mod.rs

1//! Allocation-free presentation cameras. World Y is up. Shooter yaw zero faces
2//! -Z; orbit eye offsets and vehicle-local chase forward use +Z. No simulation
3//! or input state is changed by damping, obstruction recovery or shake.
4//!
5//! [`Follow2`] and [`Rig3`] initialize on their first successful update. Use
6//! `snap` when the new spawn/teleport target is available, `reset` when restarting
7//! before that target exists, or `cut` to defer a snap until the next update while
8//! retaining the last pose. Honor the returned `cut` flag when interpolating
9//! rendered frames. Reset simulation interpolation at the teleport too: provide
10//! the new target directly so the camera does not follow a stale blended target.
11//!
12//! Smoothing half-lives are in seconds: after one half-life a stationary goal's
13//! error is halved. Existing tuning is retained by resets and snaps. Update time
14//! must be finite and in `0..=0.25`; larger gaps are rejected without mutation.
15//! A host can deliberately snap on resume or bound only its presentation time.
16//!
17//! This chase-camera integration uses Dune Skimmer's position/target damping.
18//! Call it after sampling the vehicle pose, then copy the returned pose into the
19//! renderer's camera. A recovery flag must be raised even for a short teleport
20//! below the automatic distance threshold.
21//!
22//! ```
23//! use ferravex_math::Vec3;
24//! use ferravex_play::camera::{
25//!     CameraError, CollisionQuery, Frame3, Input3, Mode3, NoObstructions,
26//!     Rig3, Settings3, Target3,
27//! };
28//!
29//! fn vehicle_view(
30//!     camera: &mut Rig3,
31//!     vehicle: Target3,
32//!     elapsed: f32,
33//!     recovered: bool,
34//!     blockers: &(impl CollisionQuery + ?Sized),
35//! ) -> Result<Frame3, CameraError> {
36//!     if !elapsed.is_finite() || elapsed < 0. {
37//!         return Err(CameraError::InvalidInput);
38//!     }
39//!     let input = Input3 {
40//!         target: vehicle,
41//!         mode: Mode3::Chase {
42//!             distance: 8., height: 3., look_ahead: 4., look_height: 1.,
43//!             speed_distance: 0.05, speed_height: 0., prediction: 0.1,
44//!             level: true,
45//!         },
46//!         fov_y: 1.,
47//!     };
48//!     if recovered || elapsed > 0.25 {
49//!         camera.snap(input, blockers)
50//!     } else {
51//!         camera.update(elapsed, input, blockers)
52//!     }
53//! }
54//!
55//! let mut camera = Rig3::new(Settings3 {
56//!     position_half_life: std::f32::consts::LN_2 / 5.5,
57//!     target_half_life: std::f32::consts::LN_2 / 8.,
58//!     ..Default::default()
59//! })?;
60//! let spawn = Target3::at(Vec3::new(100., 1., 20.));
61//! let frame = vehicle_view(&mut camera, spawn, 1. / 60., true, &NoObstructions)?;
62//! assert!(frame.cut);
63//! assert_eq!(camera.pose(), Some(frame.pose));
64//! # Ok::<(), CameraError>(())
65//! ```
66mod collision;
67mod composition;
68pub use composition::{
69    CameraComposer, CameraZone, FramingBounds, FramingError, FramingLimit, FramingResult,
70    FramingSettings, MAX_FRAMING_SUBJECTS,
71};
72mod follow;
73pub mod rail;
74mod shake;
75#[cfg(test)]
76mod tests;
77pub mod transition;
78pub use collision::{Blocker, CollisionQuery, MAX_BLOCKERS, NoObstructions, Sweep, SweepOutcome};
79use ferravex_math::{Quat, Vec3};
80pub use follow::{Follow2, Follow2Settings, Frame2, Limits2};
81pub use shake::{CameraShake, ShakeEnvelope, ShakeImpulse, ShakeSample};
82
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub enum CameraError {
85    InvalidInput,
86    InvalidSettings,
87    InvalidObstacle,
88    InvalidQuery,
89    QueryBudget,
90    ShakeCapacity,
91}
92impl std::fmt::Display for CameraError {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        write!(f, "camera: {self:?}")
95    }
96}
97impl std::error::Error for CameraError {}
98fn bounded(v: Vec3) -> bool {
99    v.is_finite() && v.abs().max_element() <= 1e6
100}
101fn nonnegative(v: f32, max: f32) -> bool {
102    v.is_finite() && (0. ..=max).contains(&v)
103}
104fn valid_dt(dt: f32) -> bool {
105    nonnegative(dt, 0.25)
106}
107/// Exact exponential response to a stationary goal. Zero half-life snaps on a
108/// positive timestep; zero time contributes no damping.
109fn weight(dt: f32, half_life: f32) -> f32 {
110    if dt == 0. {
111        0.
112    } else if half_life == 0. {
113        1.
114    } else {
115        -(-std::f32::consts::LN_2 * dt / half_life).exp_m1()
116    }
117}
118fn direction(yaw: f32, pitch: f32) -> Vec3 {
119    let (sy, cy) = yaw.sin_cos();
120    let (sp, cp) = pitch.sin_cos();
121    Vec3::new(sy * cp, sp, -cy * cp)
122}
123fn basis(forward: Vec3, up: Vec3) -> (Vec3, Vec3) {
124    let right = forward
125        .cross(up)
126        .try_normalize()
127        .unwrap_or_else(|| forward.any_orthonormal_vector());
128    (right, right.cross(forward).normalize())
129}
130#[derive(Clone, Copy, Debug, PartialEq)]
131pub struct Target3 {
132    pub position: Vec3,
133    pub rotation: Quat,
134    pub velocity: Vec3,
135}
136impl Target3 {
137    pub fn at(position: Vec3) -> Self {
138        Self {
139            position,
140            rotation: Quat::IDENTITY,
141            velocity: Vec3::ZERO,
142        }
143    }
144}
145#[derive(Clone, Copy, Debug, PartialEq)]
146pub enum Mode3 {
147    /// Offsets remain in world axes; useful for an isometric or overhead view.
148    Follow { eye_offset: Vec3, look_offset: Vec3 },
149    /// Eye offset is spherical around a target-local pivot. Positive pitch is up.
150    Orbit {
151        yaw: f32,
152        pitch: f32,
153        distance: f32,
154        pivot: Vec3,
155    },
156    /// Immediate world-space look, yaw zero -Z, positive pitch up. No aim damping.
157    FirstPerson {
158        eye_offset: Vec3,
159        yaw: f32,
160        pitch: f32,
161    },
162    /// Vehicle-local +Z forward, optionally flattened to the world XZ plane.
163    Chase {
164        distance: f32,
165        height: f32,
166        look_ahead: f32,
167        look_height: f32,
168        speed_distance: f32,
169        speed_height: f32,
170        prediction: f32,
171        level: bool,
172    },
173}
174impl Mode3 {
175    fn tag(self) -> u8 {
176        match self {
177            Self::Follow { .. } => 0,
178            Self::Orbit { .. } => 1,
179            Self::FirstPerson { .. } => 2,
180            Self::Chase { .. } => 3,
181        }
182    }
183    fn desired(self, t: Target3) -> Result<(Vec3, Vec3, Vec3), CameraError> {
184        let angle = |v: f32| v.is_finite() && v.abs() <= 1e6;
185        let pitch_valid = |v: f32| v.is_finite() && v.abs() <= std::f32::consts::FRAC_PI_2 - 0.001;
186        let result = match self {
187            Self::Follow {
188                eye_offset,
189                look_offset,
190            } if bounded(eye_offset)
191                && bounded(look_offset)
192                && eye_offset.distance_squared(look_offset) > 1e-6 =>
193            {
194                (
195                    t.position + eye_offset,
196                    t.position + look_offset,
197                    t.position,
198                )
199            }
200            Self::Orbit {
201                yaw,
202                pitch,
203                distance,
204                pivot,
205            } if angle(yaw)
206                && pitch_valid(pitch)
207                && distance.is_finite()
208                && (0.01..=1e5).contains(&distance)
209                && bounded(pivot) =>
210            {
211                let origin = t.position + t.rotation * pivot;
212                let (s, c) = yaw.sin_cos();
213                let (sp, cp) = pitch.sin_cos();
214                (
215                    origin + Vec3::new(s * cp, sp, c * cp) * distance,
216                    origin,
217                    origin,
218                )
219            }
220            Self::FirstPerson {
221                eye_offset,
222                yaw,
223                pitch,
224            } if bounded(eye_offset) && angle(yaw) && pitch_valid(pitch) => {
225                let eye = t.position + t.rotation * eye_offset;
226                (eye, eye + direction(yaw, pitch), eye)
227            }
228            Self::Chase {
229                distance,
230                height,
231                look_ahead,
232                look_height,
233                speed_distance,
234                speed_height,
235                prediction,
236                level,
237            } if distance.is_finite()
238                && (0.01..=1e5).contains(&distance)
239                && [height, look_ahead, look_height]
240                    .into_iter()
241                    .all(|v| v.is_finite() && v.abs() <= 1e5)
242                && nonnegative(speed_distance, 100.)
243                && nonnegative(speed_height, 100.)
244                && nonnegative(prediction, 1.) =>
245            {
246                let mut forward = t.rotation * Vec3::Z;
247                if level {
248                    forward.y = 0.;
249                    forward = forward.try_normalize().ok_or(CameraError::InvalidInput)?;
250                }
251                let speed = t.velocity.length();
252                let center = t.position + t.velocity * prediction;
253                (
254                    center - forward * (distance + speed * speed_distance)
255                        + Vec3::Y * (height + speed * speed_height),
256                    center + forward * look_ahead + Vec3::Y * look_height,
257                    t.position + Vec3::Y * look_height,
258                )
259            }
260            _ => return Err(CameraError::InvalidInput),
261        };
262        if [result.0, result.1, result.2].into_iter().all(bounded) {
263            Ok(result)
264        } else {
265            Err(CameraError::InvalidInput)
266        }
267    }
268}
269#[derive(Clone, Copy, Debug, PartialEq)]
270pub struct Input3 {
271    pub target: Target3,
272    pub mode: Mode3,
273    pub fov_y: f32,
274}
275#[derive(Clone, Copy, Debug, PartialEq)]
276pub struct ObstructionSettings {
277    pub radius: f32,
278    pub padding: f32,
279    /// Retract immediately, ease back out after an obstacle clears.
280    pub release_half_life: f32,
281    pub sweep_motion: bool,
282}
283impl Default for ObstructionSettings {
284    fn default() -> Self {
285        Self {
286            radius: 0.25,
287            padding: 0.02,
288            release_half_life: 0.15,
289            sweep_motion: true,
290        }
291    }
292}
293#[derive(Clone, Copy, Debug, PartialEq)]
294pub struct Settings3 {
295    /// Position error half-life in seconds, in `0..=10`; zero disables damping
296    /// on positive timesteps. Orbit uses this for yaw, pitch and distance too.
297    pub position_half_life: f32,
298    /// Look-target error half-life in seconds. First-person aim is always immediate.
299    pub target_half_life: f32,
300    /// Vertical field-of-view error half-life in seconds.
301    pub fov_half_life: f32,
302    /// Cut when subject motion between successful updates exceeds this distance.
303    /// `None` disables automatic teleport detection; explicit snaps still work.
304    pub teleport_distance: Option<f32>,
305    pub obstruction: Option<ObstructionSettings>,
306    /// Set to zero for reduced-motion presentation.
307    pub shake_strength: f32,
308}
309impl Default for Settings3 {
310    fn default() -> Self {
311        Self {
312            position_half_life: 0.12,
313            target_half_life: 0.08,
314            fov_half_life: 0.14,
315            teleport_distance: Some(20.),
316            obstruction: None,
317            shake_strength: 1.,
318        }
319    }
320}
321impl Settings3 {
322    fn valid(self) -> bool {
323        [
324            self.position_half_life,
325            self.target_half_life,
326            self.fov_half_life,
327        ]
328        .into_iter()
329        .all(|v| nonnegative(v, 10.))
330            && self
331                .teleport_distance
332                .is_none_or(|v| v.is_finite() && (0.001..=1e6).contains(&v))
333            && nonnegative(self.shake_strength, 1.)
334            && self.obstruction.is_none_or(|o| {
335                o.radius.is_finite()
336                    && (0.001..=1000.).contains(&o.radius)
337                    && nonnegative(o.padding, 10.)
338                    && nonnegative(o.release_half_life, 10.)
339            })
340    }
341}
342#[derive(Clone, Copy, Debug, PartialEq)]
343pub struct Pose3 {
344    pub position: Vec3,
345    pub target: Vec3,
346    pub up: Vec3,
347    pub fov_y: f32,
348}
349impl Default for Pose3 {
350    fn default() -> Self {
351        Self {
352            position: Vec3::ZERO,
353            target: -Vec3::Z,
354            up: Vec3::Y,
355            fov_y: std::f32::consts::FRAC_PI_3,
356        }
357    }
358}
359#[derive(Clone, Copy, Debug, PartialEq)]
360pub struct Frame3 {
361    pub pose: Pose3,
362    /// Discontinuity: discard any renderer interpolation from the previous frame.
363    pub cut: bool,
364    pub obstructed: bool,
365    pub blocked_pivot: bool,
366    pub recovered: bool,
367    pub queries: u8,
368}
369/// Copyable complete presentation state; update errors preserve it unchanged.
370#[derive(Clone, Copy, Debug, PartialEq)]
371pub struct Rig3 {
372    settings: Settings3,
373    initialized: bool,
374    cut_next: bool,
375    last_mode: u8,
376    previous_subject: Vec3,
377    base: Pose3,
378    rendered: Pose3,
379    boom_length: f32,
380    orbit: Vec3,
381    pub shake: CameraShake,
382}
383impl Default for Rig3 {
384    fn default() -> Self {
385        Self::new(Settings3::default()).unwrap()
386    }
387}
388impl Rig3 {
389    pub fn new(settings: Settings3) -> Result<Self, CameraError> {
390        if !settings.valid() {
391            return Err(CameraError::InvalidSettings);
392        }
393        Ok(Self {
394            settings,
395            initialized: false,
396            cut_next: false,
397            last_mode: 0,
398            previous_subject: Vec3::ZERO,
399            base: Pose3::default(),
400            rendered: Pose3::default(),
401            boom_length: 0.,
402            orbit: Vec3::ZERO,
403            shake: CameraShake::new(0x4645525241564558),
404        })
405    }
406    pub fn settings(&self) -> Settings3 {
407        self.settings
408    }
409    pub fn set_settings(&mut self, settings: Settings3) -> Result<(), CameraError> {
410        if !settings.valid() {
411            return Err(CameraError::InvalidSettings);
412        }
413        self.settings = settings;
414        Ok(())
415    }
416    /// Last successful pose, or `None` before initialization or after [`Self::reset`].
417    pub fn pose(&self) -> Option<Pose3> {
418        self.initialized.then_some(self.rendered)
419    }
420    /// Forget the pose, damping, orbit and obstruction history, retaining settings.
421    ///
422    /// Clears active shake without replacing its configured seed or sequence.
423    /// The next valid update initializes directly, even with zero elapsed time.
424    /// Shake queued after resetting belongs to the new scene and is retained.
425    ///
426    /// ```
427    /// use ferravex_play::camera::Rig3;
428    /// let mut camera = Rig3::default();
429    /// let tuning = camera.settings();
430    /// camera.reset(); // The restarted scene has not supplied its spawn yet.
431    /// assert_eq!(camera.pose(), None);
432    /// assert_eq!(camera.settings(), tuning);
433    /// ```
434    pub fn reset(&mut self) {
435        self.initialized = false;
436        self.cut_next = true;
437        self.last_mode = 0;
438        self.previous_subject = Vec3::ZERO;
439        self.base = Pose3::default();
440        self.rendered = Pose3::default();
441        self.boom_length = 0.;
442        self.orbit = Vec3::ZERO;
443        self.shake.clear();
444    }
445    /// Cut on the next valid update and discard current presentation shake.
446    /// The last pose remains available; shake queued after this call is retained.
447    pub fn cut(&mut self) {
448        self.cut_next = true;
449        self.shake.clear();
450    }
451    /// Immediately initialize or relocate the camera, clearing current shake.
452    ///
453    /// Position, look target, FOV and orbit state snap to `input`; obstruction
454    /// still constrains the boom, without sweeping from the old scene's pose.
455    /// Subsequent updates smooth from the new state with the same settings.
456    /// Input or collision errors preserve the complete previous camera state,
457    /// including shake and pending cuts. Queue new-scene shake after this call.
458    ///
459    /// ```
460    /// use ferravex_math::Vec3;
461    /// use ferravex_play::camera::{Input3, Mode3, NoObstructions, Rig3, Target3};
462    /// let mut camera = Rig3::default();
463    /// let frame = camera.snap(Input3 {
464    ///     target: Target3::at(Vec3::X * 100.),
465    ///     mode: Mode3::Follow {
466    ///         eye_offset: Vec3::Z * 10., look_offset: Vec3::ZERO,
467    ///     },
468    ///     fov_y: 1.,
469    /// }, &NoObstructions)?;
470    /// assert!(frame.cut);
471    /// assert_eq!(frame.pose.position, Vec3::new(100., 0., 10.));
472    /// # Ok::<(), ferravex_play::camera::CameraError>(())
473    /// ```
474    pub fn snap(
475        &mut self,
476        input: Input3,
477        collision: &(impl CollisionQuery + ?Sized),
478    ) -> Result<Frame3, CameraError> {
479        let mut next = *self;
480        next.cut();
481        let frame = next.update(0., input, collision)?;
482        *self = next;
483        Ok(frame)
484    }
485    /// Advance presentation with elapsed seconds in `0..=0.25`.
486    ///
487    /// Invalid or larger timesteps return [`CameraError::InvalidInput`] and leave
488    /// all state unchanged. Use [`Self::snap`] after a long host suspension if an
489    /// immediate view of the current target is desired. Zero time freezes damping
490    /// and shake time; initialization, cuts, first-person aim and collision still
491    /// apply. Automatic teleports and mode changes cut and clear old shake.
492    pub fn update(
493        &mut self,
494        dt: f32,
495        input: Input3,
496        collision: &(impl CollisionQuery + ?Sized),
497    ) -> Result<Frame3, CameraError> {
498        if !valid_dt(dt)
499            || !bounded(input.target.position)
500            || !bounded(input.target.velocity)
501            || !input.target.rotation.is_finite()
502            || (input.target.rotation.length_squared() - 1.).abs() > 0.001
503            || !input.fov_y.is_finite()
504            || !(0.05..=3.1).contains(&input.fov_y)
505        {
506            return Err(CameraError::InvalidInput);
507        }
508        let (eye, look, origin) = input.mode.desired(input.target)?;
509        let mut next = *self;
510        let cut = !self.initialized
511            || self.cut_next
512            || self.last_mode != input.mode.tag()
513            || self.settings.teleport_distance.is_some_and(|v| {
514                input
515                    .target
516                    .position
517                    .distance_squared(self.previous_subject)
518                    > v * v
519            });
520        if cut {
521            // Explicit cuts already clear old impulses. Preserve feedback that
522            // the caller queued afterwards for the new scene/impact.
523            if !self.cut_next {
524                next.shake.clear();
525            }
526            next.base = Pose3 {
527                position: eye,
528                target: look,
529                up: Vec3::Y,
530                fov_y: input.fov_y,
531            };
532        } else {
533            next.base.position = self
534                .base
535                .position
536                .lerp(eye, weight(dt, self.settings.position_half_life));
537            next.base.target = self
538                .base
539                .target
540                .lerp(look, weight(dt, self.settings.target_half_life));
541            next.base.fov_y = self.base.fov_y
542                + (input.fov_y - self.base.fov_y) * weight(dt, self.settings.fov_half_life);
543        }
544        if let Mode3::Orbit {
545            yaw,
546            pitch,
547            distance,
548            pivot,
549        } = input.mode
550        {
551            if cut {
552                next.orbit = Vec3::new(yaw, pitch, distance);
553            } else {
554                let alpha = weight(dt, self.settings.position_half_life);
555                let change = (yaw - self.orbit.x + std::f32::consts::PI)
556                    .rem_euclid(std::f32::consts::TAU)
557                    - std::f32::consts::PI;
558                next.orbit = Vec3::new(
559                    self.orbit.x + change * alpha,
560                    self.orbit.y + (pitch - self.orbit.y) * alpha,
561                    self.orbit.z + (distance - self.orbit.z) * alpha,
562                );
563                let (eye, look, _) = Mode3::Orbit {
564                    yaw: next.orbit.x,
565                    pitch: next.orbit.y,
566                    distance: next.orbit.z,
567                    pivot,
568                }
569                .desired(input.target)?;
570                next.base.position = next.base.target + (eye - look);
571            }
572        }
573        // First-person orientation always follows the sampled aim exactly, even
574        // when optional position damping follows a corrected/stepped eye.
575        if let Mode3::FirstPerson { yaw, pitch, .. } = input.mode {
576            next.base.target = next.base.position + direction(yaw, pitch);
577        }
578        let forward = (next.base.target - next.base.position)
579            .try_normalize()
580            .unwrap_or(-Vec3::Z);
581        let (right, up) = basis(forward, Vec3::Y);
582        let shake = next.shake.advance(dt)?;
583        let translation = (right * shake.translation.x
584            + up * shake.translation.y
585            + forward * shake.translation.z)
586            * self.settings.shake_strength;
587        let rotation = Quat::from_scaled_axis(
588            (right * shake.rotation.x + up * shake.rotation.y + forward * shake.rotation.z)
589                * self.settings.shake_strength,
590        );
591        let mut pose = Pose3 {
592            position: next.base.position + translation,
593            target: next.base.position
594                + translation
595                + rotation * forward * (next.base.target - next.base.position).length().max(0.01),
596            up: rotation * up,
597            fov_y: next.base.fov_y,
598        };
599        let mut frame = Frame3 {
600            pose,
601            cut,
602            obstructed: false,
603            blocked_pivot: false,
604            recovered: false,
605            queries: 0,
606        };
607        if let Some(settings) = self.settings.obstruction {
608            let boom = pose.position - origin;
609            let length = boom.length();
610            if length > 1e-6 {
611                let allowed = limit(collision, origin, pose.position, settings, &mut frame)?;
612                frame.blocked_pivot = allowed == 0.;
613                next.boom_length = if cut || allowed < self.boom_length {
614                    allowed
615                } else {
616                    self.boom_length
617                        + (allowed - self.boom_length) * weight(dt, settings.release_half_life)
618                };
619                pose.position = origin + boom / length * next.boom_length.min(allowed);
620            } else {
621                next.boom_length = 0.;
622            }
623            if !cut
624                && settings.sweep_motion
625                && pose.position.distance_squared(self.rendered.position) > 1e-12
626            {
627                let length = pose.position.distance(self.rendered.position);
628                let allowed = limit(
629                    collision,
630                    self.rendered.position,
631                    pose.position,
632                    settings,
633                    &mut frame,
634                )?;
635                if allowed == 0. {
636                    // A moving obstacle may now contain the previous camera.
637                    // Use the already checked boom as a recovery cut.
638                    frame.recovered = true;
639                    frame.cut = true;
640                } else if allowed < length {
641                    pose.position = self.rendered.position
642                        + (pose.position - self.rendered.position) * (allowed / length);
643                    let length = pose.position.distance(origin);
644                    if length > 1e-6 {
645                        let safe = limit(collision, origin, pose.position, settings, &mut frame)?;
646                        if safe < length {
647                            frame.recovered = true;
648                            frame.cut = true;
649                        }
650                        pose.position = origin + (pose.position - origin) * (safe / length);
651                    }
652                }
653            }
654        }
655        if self.settings.obstruction.is_some() {
656            next.boom_length = pose.position.distance(origin);
657        }
658        let forward = (pose.target - pose.position)
659            .try_normalize()
660            .unwrap_or(forward);
661        let (_, up) = basis(forward, pose.up);
662        pose.up = up;
663        if pose.target.distance_squared(pose.position) < 1e-6 {
664            pose.target = pose.position + forward;
665        }
666        if !bounded(pose.position) || !bounded(pose.target) || !pose.up.is_finite() {
667            return Err(CameraError::InvalidInput);
668        }
669        frame.pose = pose;
670        next.rendered = pose;
671        next.previous_subject = input.target.position;
672        next.last_mode = input.mode.tag();
673        next.initialized = true;
674        next.cut_next = false;
675        *self = next;
676        Ok(frame)
677    }
678}
679fn limit(
680    query: &(impl CollisionQuery + ?Sized),
681    start: Vec3,
682    end: Vec3,
683    settings: ObstructionSettings,
684    frame: &mut Frame3,
685) -> Result<f32, CameraError> {
686    frame.queries += 1;
687    let length = start.distance(end);
688    let hit = query.sweep(Sweep {
689        start,
690        end,
691        radius: settings.radius,
692    })?;
693    match hit {
694        Some(t) if t.is_finite() && (0. ..=1.).contains(&t) => {
695            frame.obstructed = true;
696            Ok((t * length - settings.padding).max(0.))
697        }
698        None => Ok(length),
699        _ => Err(CameraError::InvalidQuery),
700    }
701}