crcbl_phys/system/clearance.rs
1//! [`PhysicsSystem::farthest_clear_point`]: how far a sphere gets along a
2//! path before it would touch something.
3
4use glam::DVec3;
5
6use super::PhysicsSystem;
7use crate::{QueryFilter, Segment};
8
9impl PhysicsSystem {
10 /// The farthest point from `from` towards `to` a sphere of `radius` can
11 /// stand, `skin` metres short of the first collider it would touch.
12 ///
13 /// This is what a camera boom, a held weapon's muzzle or a spring arm
14 /// asks: sweep from a point known to be clear — the head, the pivot —
15 /// towards where the eye wants to be, and stop just in front of the wall.
16 /// The skin keeps the near plane off the surface it stopped at. `to` comes
17 /// back when nothing is in the way and when the path has no length; `from`
18 /// when the sweep starts touching something or the skin is longer than the
19 /// way to the hit. The skin is measured along the path, not along the
20 /// surface's normal.
21 ///
22 /// `filter` leaves colliders out — the character the camera follows, at
23 /// least — on [`QueryFilter`]'s terms. Triggers never stop it.
24 #[must_use]
25 pub fn farthest_clear_point(
26 &mut self,
27 from: DVec3,
28 to: DVec3,
29 radius: f64,
30 skin: f64,
31 filter: QueryFilter,
32 ) -> DVec3 {
33 let length = from.distance(to);
34 if length == 0.0 {
35 return to;
36 }
37 let Some((_, hit)) = self.sweep_sphere_filtered(&Segment::new(from, to), radius, filter)
38 else {
39 return to;
40 };
41 let fraction = (hit.t - skin / length).clamp(0.0, 1.0);
42 from.lerp(to, fraction)
43 }
44}