Skip to main content

crcbl_phys/
character.rs

1//! Capsule character controller: sweep-based movement against the world.
2//!
3//! [`CharacterController`] moves a Y-aligned capsule through a
4//! [`PhysicsWorld`], sliding along what it hits, walking up slopes it is
5//! allowed to and over steps it can reach, staying attached to the ground it
6//! walks off the edge of, and pushing itself out of anything it wakes up
7//! inside. It is kinematic: nothing integrates it, and it moves exactly as far
8//! as the caller asks minus what the world takes away.
9//!
10//! A prone body is the same controller moving a [`LyingCapsule`] whose head is
11//! its position instead: [`CharacterController::move_lying`] sweeps the whole
12//! body with the same slide and lays it along the ground, and
13//! [`CharacterController::turn_lying`] turns it about its head as far as it
14//! fits.
15//!
16//! # It does not know which camera is watching
17//!
18//! [`CharacterController::move_and_slide`] takes a **world-space
19//! displacement** and nothing else. It holds no camera, no view basis and no
20//! yaw, and it never derives a direction from one. Turning a stick vector into
21//! a world direction is the caller's job, because that is the only step that
22//! genuinely differs between a first-person rig (intent is relative to the
23//! view) and a third-person one (intent is relative to the camera while the
24//! body turns toward it over time).
25//!
26//! **Facing is not here either.** There is no orientation on this type. A
27//! first-person game pins the character's facing to its view; a third-person
28//! game turns the body toward the direction it is moving, over time, and reads
29//! that direction from [`MoveOutcome::motion`]. A controller that stored one
30//! yaw and used it for both could not do the second without fighting the first,
31//! which is where the two styles usually get forked into two controllers.
32//!
33//! Camera collision, follow logic and spring arms are the camera's, and
34//! `docs/plan/30-player-kit.md` puts those on the client as presentation while
35//! movement runs as a server system.
36//!
37//! Jump buffering, coyote time, sprint multipliers, acceleration curves and
38//! input mapping are not here either. They are a layer above this one, and they
39//! reach it through the displacement they ask for.
40//!
41//! # The approach, and where it comes from
42//!
43//! The move is a **collect-and-slide loop over a plane set**, which is the
44//! shape every engine converges on:
45//!
46//! * Quake's `SV_FlyMove` / `PM_SlideMove` sweeps, records each blocking
47//!   plane, and clips the velocity against the *set* rather than the last one —
48//!   picking the plane whose clipped result does not drive into any other, and
49//!   falling back to the crease (the cross product of two planes) when no
50//!   single plane frees it. It stops dead when the clipped velocity opposes the
51//!   original, which is what keeps a sloping corner from oscillating. That
52//!   loop, its bump count ([`CharacterConfig::max_slides`]) and its plane
53//!   budget ([`MAX_PLANES`]) are reproduced here.
54//! * Godot's `CharacterBody3D::move_and_slide` contributes the iteration cap as
55//!   a tunable, the walkable-floor angle as the one thing that decides what
56//!   ground is, and `floor_snap_length` — staying attached to a surface that
57//!   drops away under you.
58//! * Unreal's `UCharacterMovementComponent` contributes the two pieces Quake
59//!   has no equivalent of: `StepUp`'s rise / advance / drop with a *validated*
60//!   landing, and `ComputeGroundMovementDelta`'s rule that a grounded move
61//!   keeps its horizontal length and takes its rise from the ramp — so walking
62//!   up a slope is not slower than walking on the flat.
63//!
64//! One deliberate difference from the Quake lineage: its `ClipVelocity` takes
65//! an `overbounce` factor, which Quake III passes slightly above one to nudge
66//! off the plane it just clipped against. This backs the capsule off by
67//! [`CharacterConfig::skin_width`] instead. The gap is then a distance the
68//! reader can name, and the next sweep starts outside the surface rather than
69//! exactly on it.
70//!
71//! # Failure modes
72//!
73//! Handled, each with the mechanism that handles it:
74//!
75//! * **A crease between two planes sliding you into geometry.** Clipping
76//!   against the plane *set* and falling back to the crease direction, from
77//!   `SV_FlyMove`. A third simultaneous plane is a corner and stops the
78//!   character rather than squeezing it through.
79//! * **Oscillating in a sloping corner.** The clipped displacement is dropped
80//!   when it opposes the one the move started with.
81//! * **Creeping down a slope while standing still.** A grounded move takes its
82//!   rise from the ramp and *discards* the vertical it was asked for rather
83//!   than clipping it against the slope, so a request with no horizontal part
84//!   becomes no movement at all. Godot spends `floor_stop_on_slope` on the same
85//!   problem. The ground probe is what holds the character on.
86//! * **Climbing a wall by facing into a corner.** Three things refuse it: the
87//!   step-up needs the advance after rising to make real progress, it needs the
88//!   drop afterwards to land on walkable ground, and it may happen at most once
89//!   per call so a character cannot ratchet up a wall within one tick. The
90//!   ground probe is a fourth — it pulls the capsule back down onto whatever it
91//!   is actually standing on.
92//! * **Tunnelling at speed.** Every probe is a swept capsule, never a
93//!   teleport-and-test.
94//! * **Waking up inside geometry.** [`Penetration`] depths, resolved deepest
95//!   first before the move.
96//!
97//! Not handled, and known:
98//!
99//! * **A step-up that clips the wall it stepped over.** The advance is swept at
100//!   the raised height and the drop is swept straight down, but the corner
101//!   between them is not. A capsule that lands touching the riser is pushed out
102//!   by the next call's depenetration rather than being placed clear by this
103//!   one.
104//! * **Moving geometry.** Nothing here reads a collider's velocity, so a
105//!   character standing on a platform does not ride it and a platform closing
106//!   on a character resolves as a penetration rather than as a push.
107//! * **Ceilings while stepping up.** The rise stops under an overhead
108//!   obstruction, so a low ceiling shortens the step rather than cancelling it;
109//!   whether the shortened step then lands is left to the same landing check as
110//!   any other.
111//! * **More than two simultaneous planes.** Stopping dead is Quake's answer and
112//!   it is this one; Quake III tries the remaining pairs before giving up.
113
114use glam::DVec3;
115
116use crate::broadphase::{Ray, Segment};
117use crate::collider::{Capsule, LyingCapsule};
118use crate::query::{Penetration, ShapeHit};
119use crate::world::{
120    ALL_LAYERS, ColliderId, OverlapQueries, PhysicsWorld, QueryFilter, QueryScratch,
121};
122
123mod lying;
124mod preview;
125mod skin;
126mod slide_contact;
127
128pub use lying::{LyingMoveOutcome, LyingTurnOutcome};
129pub use preview::UprightPreview;
130pub use slide_contact::SlideContact;
131
132/// The world's up axis. `crcbl` is right-handed with `+Y` up, and
133/// [`Capsule`] is Y-aligned, so a character controller has exactly one.
134const UP: DVec3 = DVec3::Y;
135
136/// A displacement shorter than this is not worth a sweep: the capsule is
137/// already where it was going, and sweeping it would only cost a broadphase
138/// traversal to be told so.
139///
140/// For the same reason an advance no longer than this has not covered ground,
141/// and the slide keeps the planes it has already collected across it.
142const MIN_MOVE: f64 = 1e-9;
143
144/// How many blocking planes one move may collect before the character is
145/// declared stuck and stopped.
146///
147/// Quake's `MAX_CLIP_PLANES`, and reaching it is its "this shouldn't really
148/// happen": a character that has found this many distinct surfaces without
149/// covering any ground is wedged rather than on a path. It is a different limit
150/// from the one `clip_to_planes` enforces, which is that only two planes have a
151/// crease to run along.
152pub const MAX_PLANES: usize = 5;
153
154/// How many [`CharacterConfig::skin_width`]s of slack a downward probe carries
155/// beyond the distance it is actually asking about.
156///
157/// A settled capsule sits exactly one skin width of *vertical* travel above its
158/// ground, so a probe with no slack would find that ground only by touching it,
159/// and a sweep that ends exactly at contact is a knife edge. Two skin widths is
160/// the shortest slack that clears it. Unreal spends its `MAX_FLOOR_DIST` the
161/// same way.
162const GROUND_PROBE_SKINS: f64 = 2.0;
163
164// ---------------------------------------------------------------------------
165// Configuration
166// ---------------------------------------------------------------------------
167
168/// The shape of a character and the limits it moves under.
169#[derive(Debug, Clone, Copy, PartialEq)]
170pub struct CharacterConfig {
171    /// Radius of the capsule.
172    pub radius: f64,
173    /// Half the length of the capsule's cylindrical section, as
174    /// [`Capsule::half_height`] means it: the standing height is
175    /// `2 * (half_height + radius)`.
176    pub half_height: f64,
177    /// The smallest `normal · +Y` a surface can have and still be ground the
178    /// character stands and walks on — the **cosine** of the steepest walkable
179    /// slope, not the angle.
180    ///
181    /// A cosine and not an angle because this crate is a determinism-bearing
182    /// one and `cos` is a platform transcendental: see the determinism rule in
183    /// `docs/notes/simulation.md`. Authoring an angle is the caller's job, done
184    /// once, outside the tick. This is the same runtime form Quake's
185    /// `normal[2] > 0.7` and Unreal's `WalkableFloorZ` keep.
186    ///
187    /// Where the behaviour actually flips is measured by
188    /// `tests::the_slope_the_controller_stops_walking_up_is_the_one_it_was_configured_with`.
189    pub min_ground_normal_y: f64,
190    /// The tallest ledge the character walks up without leaving the ground.
191    ///
192    /// Also how far it will drop to stay attached to ground that falls away
193    /// under it, which is Godot's `floor_snap_length` and the reason walking
194    /// down stairs does not become a series of falls.
195    ///
196    /// The rise is taken with a [`skin_width`](Self::skin_width) to spare, so a
197    /// step of exactly this height is climbed and the true cut-off is up to one
198    /// skin width above it. The band is measured by
199    /// `tests::the_step_the_controller_stops_climbing_is_the_offset_it_was_configured_with`.
200    pub step_offset: f64,
201    /// The gap kept between the capsule and every surface it touches.
202    ///
203    /// Every sweep of a move stops this far short of its contact, measured
204    /// along the surface's normal, and one that met a surface already nearer
205    /// than this backs off to it. The next sweep then starts outside the
206    /// surface instead of on it, where a touching start would be reported as
207    /// an overlap and a sweep with a tolerance can meet the surface again for
208    /// motion along it. Unity's `CharacterController`
209    /// calls the same quantity `skinWidth`; Unreal spends it as
210    /// `MAX_FLOOR_DIST`.
211    /// A move whose physical sweep misses also checks the skin envelope, so
212    /// subdividing an approach into sub-skin requests cannot consume the gap.
213    /// The envelope only blocks incoming motion, not parallel or departing moves.
214    pub skin_width: f64,
215    /// How many times one move may be clipped and redirected before it stops.
216    ///
217    /// Quake's `numbumps` and Godot's `max_slides`.
218    pub max_slides: u32,
219    /// How many times the move may push the capsule out of what it overlaps
220    /// before giving up and moving anyway.
221    ///
222    /// One pass resolves one contact completely, so this is the number of
223    /// *distinct* surfaces a character can be dug out of in a single call — a
224    /// corner needs two, a hole in a wall three.
225    pub depenetration_passes: u32,
226}
227
228impl Default for CharacterConfig {
229    /// An adult-sized character: 1.8 m tall, 0.6 m across, 45° slopes.
230    ///
231    /// 45° is expressed as [`std::f64::consts::FRAC_1_SQRT_2`] rather than
232    /// `(PI / 4.0).cos()` so the default costs no transcendental at all — see
233    /// [`min_ground_normal_y`](Self::min_ground_normal_y).
234    fn default() -> Self {
235        Self {
236            radius: 0.3,
237            half_height: 0.6,
238            min_ground_normal_y: std::f64::consts::FRAC_1_SQRT_2,
239            step_offset: 0.4,
240            skin_width: 0.01,
241            max_slides: 4,
242            depenetration_passes: 4,
243        }
244    }
245}
246
247// ---------------------------------------------------------------------------
248// Results
249// ---------------------------------------------------------------------------
250
251/// The ground a character is standing on.
252#[derive(Debug, Clone, Copy, PartialEq)]
253pub struct GroundContact {
254    /// Upward unit normal of the surface.
255    pub normal: DVec3,
256    /// Where the capsule meets it.
257    pub point: DVec3,
258    /// Which collider it is.
259    pub collider: ColliderId,
260}
261
262/// What a downward capsule probe found: the surface, how far below the capsule
263/// it is, and whether the character could stand on it.
264///
265/// Returned by [`CharacterController::probe_ground`] and
266/// [`CharacterController::probe_ground_at`]. The same probe is what ends every
267/// [`CharacterController::move_and_slide`], which keeps only a walkable
268/// result, as its [`GroundContact`].
269#[derive(Debug, Clone, Copy, PartialEq)]
270pub struct GroundProbe {
271    /// The surface hit, in the form [`CharacterController::ground`] reports it.
272    pub contact: GroundContact,
273    /// How far the capsule travelled straight down before touching it. A
274    /// character settled by a move sits one
275    /// [`skin_width`](CharacterConfig::skin_width) above its ground, so this
276    /// reads that gap for a settled character; zero means it is already
277    /// touching or overlapping.
278    pub distance: f64,
279    /// Whether the surface passes [`CharacterController::is_walkable`] under
280    /// this controller's slope limit.
281    pub walkable: bool,
282}
283
284/// What one [`CharacterController::move_and_slide`] did.
285#[derive(Debug, Clone, Copy, PartialEq, Default)]
286pub struct MoveOutcome {
287    /// The displacement actually applied, which is the requested one minus
288    /// whatever the world took away. **This is what a third-person game turns
289    /// the body toward**, and it is world-space for the same reason the
290    /// request is.
291    pub motion: DVec3,
292    /// How far the capsule was pushed out of geometry it started inside,
293    /// before the move. Zero in the ordinary case.
294    pub depenetration: DVec3,
295    /// Whether the character is standing on walkable ground now. Agrees with
296    /// [`CharacterController::is_grounded`].
297    pub grounded: bool,
298    /// Whether the move was blocked by a surface too steep to stand on and not
299    /// steep enough to be a ceiling.
300    pub hit_wall: bool,
301    /// Whether the move was blocked by a surface facing downward.
302    pub hit_ceiling: bool,
303    /// Whether a step was climbed.
304    pub stepped_up: bool,
305    /// How many times the move was blocked and redirected. Zero means it went
306    /// the whole way unobstructed.
307    pub slides: u32,
308}
309
310/// What the slide loop found, before the ground probe has its say.
311#[derive(Debug, Clone, Copy, Default)]
312struct SlideReport {
313    hit_wall: bool,
314    hit_ceiling: bool,
315    stepped_up: bool,
316    slides: u32,
317}
318
319/// The shape a slide sweeps.
320#[derive(Debug, Clone, Copy)]
321enum Body {
322    /// The controller's own upright capsule, centred on its position.
323    Upright,
324    /// A body lying back from the controller's position, which is its head;
325    /// the capsule's own `head` is not read.
326    Lying(LyingCapsule),
327}
328
329/// The world as a move reads it: a shared view of its colliders, and the
330/// buffers that view's queries work in.
331///
332/// Every phase of a move queries through this and never through
333/// `&mut PhysicsWorld`, so the solve has no way to write the world. The one
334/// write a move makes, synchronizing its
335/// [self collider](CharacterController::with_self_collider), comes after the
336/// solve and outside it — which is what lets
337/// [`CharacterController::preview_upright`] run the same solve and stop there.
338struct WorldReader<'w, 's> {
339    view: OverlapQueries<'w>,
340    scratch: &'s mut QueryScratch,
341}
342
343impl<'w> WorldReader<'w, 'w> {
344    /// Read `world` through the view and buffers it keeps for itself.
345    fn of(world: &'w mut PhysicsWorld) -> Self {
346        let (view, scratch) = world.overlap_queries_with_scratch();
347        Self { view, scratch }
348    }
349}
350
351/// A step-up that survived all three of its checks.
352#[derive(Debug, Clone, Copy)]
353struct StepUp {
354    /// Where the capsule ends up.
355    position: DVec3,
356    /// The horizontal displacement the advance consumed.
357    advance: DVec3,
358}
359
360// ---------------------------------------------------------------------------
361// Controller
362// ---------------------------------------------------------------------------
363
364/// A capsule that walks.
365///
366/// Drive it one displacement at a time, at the fixed server timestep:
367///
368/// ```
369/// use crcbl_phys::{BoxCollider, CharacterConfig, CharacterController, PhysicsWorld};
370/// use glam::DVec3;
371///
372/// let mut world = PhysicsWorld::new();
373/// world.add_box(BoxCollider::new(
374///     DVec3::new(0.0, -1.0, 0.0),
375///     DVec3::new(50.0, 1.0, 50.0),
376/// ));
377///
378/// let config = CharacterConfig::default();
379/// // Feet on the floor: the capsule centre is a radius plus a half-height up.
380/// let feet = config.radius + config.half_height;
381/// let mut character = CharacterController::new(config, DVec3::new(0.0, feet, 0.0));
382///
383/// let dt = 1.0 / 60.0;
384/// // The caller owns the camera, so the caller owns this direction.
385/// let intent = DVec3::new(1.0, 0.0, 0.0);
386/// let gravity = DVec3::new(0.0, -9.81 * dt * dt, 0.0);
387///
388/// for _ in 0..30 {
389///     let outcome = character.move_and_slide(&mut world, intent * 4.0 * dt + gravity);
390///     assert!(outcome.grounded);
391/// }
392/// assert!(character.position().x > 1.0);
393/// ```
394#[derive(Debug, Clone)]
395pub struct CharacterController {
396    config: CharacterConfig,
397    position: DVec3,
398    ground: Option<GroundContact>,
399    self_collider: Option<ColliderId>,
400    /// The layers every world query of this controller looks at.
401    query_mask: u32,
402    /// Kept across calls so depenetration allocates nothing per tick.
403    contacts: Vec<(ColliderId, Penetration)>,
404}
405
406impl CharacterController {
407    /// Place a character at `position`, which is the **centre** of its capsule
408    /// — a character whose feet are on `y = 0` starts at
409    /// `radius + half_height`.
410    ///
411    /// It starts ungrounded whatever is beneath it; the first
412    /// [`move_and_slide`](Self::move_and_slide), even with a zero
413    /// displacement, is what finds the floor.
414    #[must_use]
415    pub fn new(config: CharacterConfig, position: DVec3) -> Self {
416        Self {
417            config,
418            position,
419            ground: None,
420            self_collider: None,
421            query_mask: ALL_LAYERS,
422            contacts: Vec::new(),
423        }
424    }
425
426    /// Tell the controller which collider in the world is its own body, so its
427    /// sweeps do not find it.
428    ///
429    /// A character that other things have to collide with is registered in the
430    /// world like anything else, and then sits on the start of every segment it
431    /// sweeps — see [`PhysicsWorld::sweep_capsule_excluding`]. Given this, each
432    /// move also writes the capsule's new position back to that collider, so
433    /// the world's copy is never a tick behind.
434    ///
435    /// A character nothing else collides with does not need it.
436    #[must_use]
437    pub fn with_self_collider(mut self, collider: ColliderId) -> Self {
438        self.set_self_collider(Some(collider));
439        self
440    }
441
442    /// Change the world-collider binding without changing movement or ground state.
443    pub fn set_self_collider(&mut self, collider: Option<ColliderId>) {
444        self.self_collider = collider;
445    }
446
447    /// Look only at the world's colliders on a layer in `mask`: see
448    /// [`PhysicsWorld::set_layers`].
449    ///
450    /// Every query the controller makes — the move's sweeps, the step-up, the
451    /// ground probe that ends a move, [`probe_ground_at`](Self::probe_ground_at)
452    /// and depenetration — applies it together with the
453    /// [self collider](Self::with_self_collider) exclusion, so a collider
454    /// masked out is one the character walks through, stands on nothing of,
455    /// and is never pushed out of. The default is
456    /// [`ALL_LAYERS`]: every collider is solid.
457    #[must_use]
458    pub fn with_query_mask(mut self, mask: u32) -> Self {
459        self.set_query_mask(mask);
460        self
461    }
462
463    /// Change the query mask without changing movement or ground state: see
464    /// [`with_query_mask`](Self::with_query_mask).
465    pub fn set_query_mask(&mut self, mask: u32) {
466        self.query_mask = mask;
467    }
468
469    /// The layers this controller's queries look at.
470    #[inline]
471    #[must_use]
472    pub fn query_mask(&self) -> u32 {
473        self.query_mask
474    }
475
476    /// The centre of the capsule.
477    #[inline]
478    #[must_use]
479    pub fn position(&self) -> DVec3 {
480        self.position
481    }
482
483    /// Teleport. Discards the ground, because the ground under the old position
484    /// says nothing about the new one; the next move finds it again.
485    pub fn set_position(&mut self, position: DVec3) {
486        self.position = position;
487        self.ground = None;
488    }
489
490    /// The capsule as the world sees it.
491    #[inline]
492    #[must_use]
493    pub fn capsule(&self) -> Capsule {
494        Capsule::new(self.position, self.config.radius, self.config.half_height)
495    }
496
497    /// The limits this character moves under.
498    #[inline]
499    #[must_use]
500    pub fn config(&self) -> &CharacterConfig {
501        &self.config
502    }
503
504    /// The ground the character is standing on, if it is standing on any.
505    #[inline]
506    #[must_use]
507    pub fn ground(&self) -> Option<&GroundContact> {
508        self.ground.as_ref()
509    }
510
511    /// Whether the character is standing on walkable ground.
512    #[inline]
513    #[must_use]
514    pub fn is_grounded(&self) -> bool {
515        self.ground.is_some()
516    }
517
518    /// Ask the world, now, what is under the capsule where it stands.
519    ///
520    /// [`probe_ground_at`](Self::probe_ground_at) at the current
521    /// [`position`](Self::position); see there.
522    #[must_use]
523    pub fn probe_ground(&self, world: &mut PhysicsWorld, distance: f64) -> Option<GroundProbe> {
524        self.probe_ground_at(world, self.position, distance)
525    }
526
527    /// Ask the world, now, what is under this controller's capsule if it were
528    /// centred at `position`, looking at most `distance` straight down.
529    ///
530    /// Nothing moves and nothing is recorded: the controller keeps its
531    /// position and its [`ground`](Self::ground), and the world is only read.
532    /// The sweep is the one [`move_and_slide`](Self::move_and_slide) ends
533    /// with — the same capsule, the same [self collider](Self::with_self_collider)
534    /// left out of it, the same [query mask](Self::with_query_mask), the same
535    /// [`is_walkable`](Self::is_walkable) verdict —
536    /// but it reports a surface too steep to stand on as well, with
537    /// [`GroundProbe::walkable`] false, where a move treats that as no ground.
538    ///
539    /// **This is not [`ground`](Self::ground).** That is what the last move
540    /// found and keeps saying so until the next one, however the world changed
541    /// in between: remove the floor and `ground()` still names it. This sweeps
542    /// the world as it is at the call, which is what an action that must start
543    /// from real support — a revive, a vault, a mantle — should ask.
544    ///
545    /// `distance` is how far below the capsule to look. A move leaves a
546    /// grounded character one [`skin_width`](CharacterConfig::skin_width)
547    /// above its floor, so a probe for "standing on something" needs more than
548    /// that; twice the skin width is the slack the move's own probe carries.
549    /// The capsule's shape is this controller's [`config`](Self::config), so a
550    /// caller that swaps configurations for a crouch probes the crouched shape.
551    ///
552    /// # Panics
553    ///
554    /// If `distance` is negative or not finite. A negative distance would
555    /// sweep upward and answer a different question.
556    #[must_use]
557    pub fn probe_ground_at(
558        &self,
559        world: &mut PhysicsWorld,
560        position: DVec3,
561        distance: f64,
562    ) -> Option<GroundProbe> {
563        assert!(
564            distance.is_finite() && distance >= 0.0,
565            "a ground probe looks a finite, non-negative distance down, not {distance}",
566        );
567        self.probe_below(&mut WorldReader::of(world), position, distance)
568    }
569
570    /// A solid collider a body lying as `capsule` would be inside, or `None`
571    /// if it fits there: [`PhysicsWorld::lying_capsule_blocker`] under this
572    /// controller's [self collider](Self::with_self_collider) exclusion and
573    /// [query mask](Self::with_query_mask), so it sees exactly what the
574    /// controller's own moves see.
575    ///
576    /// Like [`probe_ground_at`](Self::probe_ground_at) it moves nothing and
577    /// records nothing. The shape is the caller's and not this controller's
578    /// [`config`](Self::config): a prone body is a different shape from the
579    /// one the controller walks with, and this is the check to make before
580    /// letting a character lie down; [`turn_lying`](Self::turn_lying) makes it
581    /// along a turn.
582    ///
583    /// A capsule whose [`head`](LyingCapsule::head) is this controller's
584    /// settled [`position`](Self::position) with its radius sits a
585    /// [`skin_width`](CharacterConfig::skin_width) above the floor, and fits;
586    /// only a penetration blocks, never a touch.
587    #[must_use]
588    pub fn lying_blocker(
589        &self,
590        world: &mut PhysicsWorld,
591        capsule: &LyingCapsule,
592    ) -> Option<ColliderId> {
593        world.lying_capsule_blocker(capsule, self.filter())
594    }
595
596    /// Whether a surface with this normal is ground the character can stand on.
597    ///
598    /// Upward-facing is part of the question and not an assumption: a
599    /// [`min_ground_normal_y`](CharacterConfig::min_ground_normal_y) of zero
600    /// would otherwise make a vertical wall walkable, and then the ramp
601    /// adjustment would divide by its zero rise.
602    #[inline]
603    #[must_use]
604    pub fn is_walkable(&self, normal: DVec3) -> bool {
605        let rise = normal.dot(UP);
606        rise > 0.0 && rise >= self.config.min_ground_normal_y
607    }
608
609    /// Whether a surface with this normal faces down enough to be a ceiling.
610    ///
611    /// The mirror of [`is_walkable`](Self::is_walkable) through the horizontal,
612    /// so every normal is ground, ceiling or wall and nothing is two of them.
613    #[inline]
614    #[must_use]
615    pub fn is_ceiling(&self, normal: DVec3) -> bool {
616        let rise = normal.dot(UP);
617        rise < 0.0 && -rise >= self.config.min_ground_normal_y
618    }
619
620    /// Move by a **world-space** displacement, sliding along whatever gets in
621    /// the way.
622    ///
623    /// `motion` is a displacement for this tick and not a velocity: the caller
624    /// has already multiplied by its own timestep, so nothing here reads a
625    /// clock and two callers stepping at different rates get the same answer
626    /// for the same displacement.
627    ///
628    /// # What a grounded move does with the vertical part
629    ///
630    /// While the character is standing on walkable ground and `motion` does not
631    /// point upward, the vertical part of `motion` is **replaced** by the rise
632    /// or fall the ground itself imposes — Unreal's
633    /// `ComputeGroundMovementDelta`. Walking up a ramp therefore covers the
634    /// same horizontal distance as walking on the flat, and the gravity a
635    /// caller keeps applying does not dig the capsule into the slope. What
636    /// holds the character down instead is the ground probe at the end of the
637    /// move.
638    ///
639    /// The moment the ground stops being walkable, or the caller asks to go
640    /// up, `motion` is used as given and gravity does what gravity does.
641    pub fn move_and_slide(&mut self, world: &mut PhysicsWorld, motion: DVec3) -> MoveOutcome {
642        self.move_upright(world, motion, None)
643    }
644
645    /// [`move_and_slide`](Self::move_and_slide), writing every sweep that met
646    /// something into `contacts` (which is cleared first), in the order the
647    /// slide met them.
648    ///
649    /// The move itself is the same one, to the bit: recording reads what the
650    /// slide found and never feeds back into it. See [`SlideContact`] for what
651    /// each entry holds, and why its fraction is a distance along one straight
652    /// sweep rather than a time.
653    ///
654    /// `contacts` is the caller's so a game recording every tick reuses one
655    /// buffer rather than allocating a list per move; the slide never records
656    /// more than [`max_slides`](CharacterConfig::max_slides) of them.
657    pub fn move_and_slide_into(
658        &mut self,
659        world: &mut PhysicsWorld,
660        motion: DVec3,
661        contacts: &mut Vec<SlideContact>,
662    ) -> MoveOutcome {
663        contacts.clear();
664        self.move_upright(world, motion, Some(contacts))
665    }
666
667    /// The one upright move, recording into `contacts` when there are any:
668    /// [`solve_upright`](Self::solve_upright), then the self collider
669    /// synchronized to where it left the capsule.
670    fn move_upright(
671        &mut self,
672        world: &mut PhysicsWorld,
673        motion: DVec3,
674        contacts: Option<&mut Vec<SlideContact>>,
675    ) -> MoveOutcome {
676        let outcome = self.solve_upright(&mut WorldReader::of(world), motion, contacts);
677        if let Some(collider) = self.self_collider {
678            world.set_capsule(collider, self.capsule());
679        }
680        outcome
681    }
682
683    /// Everything an upright move decides — depenetration, the slide, the
684    /// step-up and the ground probe — applied to this controller and to
685    /// nothing else: the world is only read.
686    ///
687    /// [`move_upright`](Self::move_upright) commits the result to the world;
688    /// [`preview_upright`](Self::preview_upright) runs it on a copy and keeps
689    /// what it found. One solve for both is what makes a preview the move's
690    /// answer to the bit rather than a second algorithm's.
691    fn solve_upright(
692        &mut self,
693        world: &mut WorldReader<'_, '_>,
694        motion: DVec3,
695        contacts: Option<&mut Vec<SlideContact>>,
696    ) -> MoveOutcome {
697        let depenetration = self.depenetrate(world);
698        let start = self.position;
699        let was_grounded = self.ground.is_some();
700
701        let adjusted = self.ground_adjusted(motion, was_grounded);
702        let report = self.slide(world, adjusted, was_grounded, Body::Upright, contacts);
703        self.settle_on_ground(world, was_grounded, motion);
704
705        MoveOutcome {
706            motion: self.position - start,
707            depenetration,
708            grounded: self.ground.is_some(),
709            hit_wall: report.hit_wall,
710            hit_ceiling: report.hit_ceiling,
711            stepped_up: report.stepped_up,
712            slides: report.slides,
713        }
714    }
715
716    // ── Phases ─────────────────────────────────────────────────────────
717
718    /// Push the capsule out of everything it overlaps, deepest contact first.
719    ///
720    /// One contact per pass, rather than the sum of all of them: two surfaces
721    /// sharing a normal would double the push, and a corner's two normals
722    /// summed points somewhere neither of them does. Resolving the deepest and
723    /// asking again converges on the corner and never overshoots.
724    fn depenetrate(&mut self, world: &mut WorldReader<'_, '_>) -> DVec3 {
725        let mut total = DVec3::ZERO;
726        for _ in 0..self.config.depenetration_passes {
727            let capsule = self.capsule();
728            let mut contacts = std::mem::take(&mut self.contacts);
729            world.view.capsule_penetrations_filtered_into(
730                &capsule,
731                self.filter(),
732                world.scratch,
733                &mut contacts,
734            );
735            let deepest = contacts
736                .iter()
737                .max_by(|a, b| a.1.depth.total_cmp(&b.1.depth))
738                .map(|&(_, penetration)| penetration);
739            self.contacts = contacts;
740
741            let Some(penetration) = deepest else {
742                break;
743            };
744            let push = penetration.normal * (penetration.depth + self.config.skin_width);
745            self.position += push;
746            total += push;
747        }
748        total
749    }
750
751    /// Turn a requested displacement into the one a grounded character
752    /// actually makes.
753    ///
754    /// While the character is on walkable ground and not asking to leave it,
755    /// the horizontal part of the request keeps its length and takes its rise
756    /// from the ground plane — Unreal's `ComputeGroundMovementDelta` with
757    /// `bMaintainHorizontalGroundVelocity`. The vertical part is **discarded**,
758    /// not projected.
759    ///
760    /// Discarding it is what stops a standing character creeping downhill.
761    /// Clipping gravity against the slope instead, which is what happens the
762    /// moment this does not run, leaves a downhill component behind on every
763    /// tick, and Godot spends `floor_stop_on_slope` on the same problem. It
764    /// also means a request with no horizontal part becomes no movement at all,
765    /// because the ramp form of a zero horizontal is zero.
766    fn ground_adjusted(&self, motion: DVec3, was_grounded: bool) -> DVec3 {
767        if !was_grounded || motion.dot(UP) > 0.0 {
768            return motion;
769        }
770        let Some(ground) = self.ground else {
771            return motion;
772        };
773        let flat = motion - UP * motion.dot(UP);
774        flat - UP * (ground.normal.dot(flat) / ground.normal.dot(UP))
775    }
776
777    /// The collect-and-slide loop, after `SV_FlyMove`, sweeping `body`.
778    ///
779    /// Only an upright body steps up; a grounded lying one meets a wall as
780    /// though the wall were upright.
781    ///
782    /// Each sweep that meets something is pushed onto `contacts`, when given,
783    /// once the slide has decided what to do about it. Nothing read back from
784    /// a contact steers the loop, so recording cannot change the move.
785    fn slide(
786        &mut self,
787        world: &mut WorldReader<'_, '_>,
788        motion: DVec3,
789        was_grounded: bool,
790        body: Body,
791        mut contacts: Option<&mut Vec<SlideContact>>,
792    ) -> SlideReport {
793        let mut record = |contact| {
794            if let Some(contacts) = contacts.as_deref_mut() {
795                contacts.push(contact);
796            }
797        };
798        let mut report = SlideReport::default();
799        let primal = motion;
800        let mut remaining = motion;
801        // Quake's `original_velocity`: what the plane set is asked to clip.
802        // It is only re-read once the capsule has actually covered ground,
803        // because a plane found without moving has to be added to the ones
804        // already there rather than replacing them.
805        let mut clip_from = motion;
806        let mut planes = [DVec3::ZERO; MAX_PLANES];
807        let mut plane_count = 0usize;
808
809        for _ in 0..self.config.max_slides {
810            let distance = remaining.length();
811            if distance <= MIN_MOVE {
812                return report;
813            }
814            let direction = remaining / distance;
815            let target = self.position + remaining;
816
817            let Some(sweep) = self.sweep_body(world, body, remaining) else {
818                self.position = target;
819                return report;
820            };
821            let (collider, hit) = (sweep.collider, sweep.hit);
822            report.slides += 1;
823            let mut contact = SlideContact {
824                collider,
825                normal: hit.normal,
826                requested: remaining,
827                fraction: hit.t,
828                started_inside: hit.started_inside,
829                clearance_only: sweep.clearance.is_some(),
830                applied: DVec3::ZERO,
831                remaining: DVec3::ZERO,
832                stepped_up: false,
833            };
834
835            let wall = !self.is_ceiling(hit.normal) && !self.is_walkable(hit.normal);
836            let mut plane = hit.normal;
837            if wall && was_grounded && matches!(body, Body::Lying(_)) {
838                // Unreal's `SlideAlongSurface`: a grounded body is not pushed
839                // up a wall. A lying body meets the edge of a riser with its
840                // round end, whose normal leans up, and clipping against that,
841                // or backing off along it, lifts it a little every tick until
842                // it is on top; against the wall made upright, it stops. The
843                // upright capsule is not given the rule here: it steps up, and
844                // its sweep meets a box's edge square
845                // (`query::swept_capsule_vs_aabb`), not leaning.
846                let flat = (plane - UP * plane.dot(UP)).normalize_or_zero();
847                if flat != DVec3::ZERO {
848                    plane = flat;
849                }
850            }
851
852            let along = hit.t * distance;
853            let mut back_off = DVec3::ZERO;
854            let travel = if sweep.clearance.is_some() {
855                (!hit.started_inside).then_some(along)
856            } else {
857                self.skin_short(along, direction, plane)
858            };
859            if let Some(travel) = travel {
860                let travel = travel.min(distance);
861                let step = direction * travel;
862                self.position += step;
863                remaining -= step;
864                contact.applied = step;
865                // Only real ground covered makes the planes already found
866                // stale. A sweep that touches within rounding of the skin
867                // width advances by noise, and dropping the set on that
868                // would lose the crease: a capsule falling into a corner
869                // would keep only the second wall, clip against it alone,
870                // and stop dead every tick.
871                if travel > MIN_MOVE {
872                    clip_from = remaining;
873                    plane_count = 0;
874                }
875            } else {
876                // The contact is no further than the skin width, so clipping
877                // alone would leave the next sweep starting that near too,
878                // and a sweep with a tolerance can meet the same surface
879                // again for motion along it: conservative advancement divides
880                // a gap of rounding size by a closing speed of rounding size,
881                // and a capsule hovering 1e-16 off a turned box hung in
882                // mid-air on it. A capsule set down exactly on the floor
883                // arrives here too, started inside, and must still be able to
884                // walk. Back off along the normal to the gap every other
885                // sweep keeps — unless the gap already is that, to within
886                // rounding: a character resting a skin off a wall it keeps
887                // walking into meets it here every tick, and a back-off of
888                // rounding size moved it an ulp along the normal each time
889                // it was asked to stand still.
890                let approach = (along * -direction.dot(plane)).max(0.0);
891                let short = sweep.clearance.unwrap_or(self.config.skin_width - approach);
892                if short > MIN_MOVE {
893                    back_off = plane * short;
894                }
895            }
896
897            if self.is_ceiling(hit.normal) {
898                report.hit_ceiling = true;
899            } else if wall {
900                report.hit_wall = true;
901                if was_grounded
902                    && !report.stepped_up
903                    && matches!(body, Body::Upright)
904                    && let Some(step) = self.try_step_up(world, remaining)
905                {
906                    contact.applied += step.position - self.position;
907                    self.position = step.position;
908                    remaining -= step.advance;
909                    clip_from = remaining;
910                    plane_count = 0;
911                    report.stepped_up = true;
912                    record(SlideContact {
913                        remaining,
914                        stepped_up: true,
915                        ..contact
916                    });
917                    continue;
918                }
919            }
920
921            // A valid step can cross a riser's clearance envelope. Backing
922            // away before trying it would cancel a shorter forward move on
923            // every tick, preventing the capsule from reaching the landing.
924            self.position += back_off;
925            contact.applied += back_off;
926
927            if plane_count == MAX_PLANES {
928                record(contact);
929                return report;
930            }
931            planes[plane_count] = plane;
932            plane_count += 1;
933
934            remaining = clip_to_planes(clip_from, &planes[..plane_count], remaining);
935            if remaining.dot(primal) <= 0.0 {
936                record(contact);
937                return report;
938            }
939            record(SlideContact {
940                remaining,
941                ..contact
942            });
943        }
944        report
945    }
946
947    /// Rise, advance, drop — Unreal's `StepUp`, with its landing check.
948    ///
949    /// The three refusals stop three different things. The **advance** check is
950    /// what makes a corner not a step: after rising, a corner is still a wall
951    /// in both directions and nothing was stepped onto. The **landing** check
952    /// keeps the capsule off thin air when the drop finds nothing under it. The
953    /// **walkable** test keeps it off a surface it is not allowed to stand on
954    /// and would slide straight back off.
955    ///
956    /// They are not the last line: the ground probe that ends every move pulls
957    /// the capsule back down onto whatever it is really standing on, so a step
958    /// that rose without earning it is undone anyway. All four have to be gone
959    /// at once before a character in a corner actually gains height, which is
960    /// what `tests::a_character_pressed_into_a_corner_does_not_climb_it` was
961    /// checked against.
962    fn try_step_up(&self, world: &mut WorldReader<'_, '_>, remaining: DVec3) -> Option<StepUp> {
963        if self.config.step_offset <= 0.0 {
964            return None;
965        }
966        let forward = remaining - UP * remaining.dot(UP);
967        let forward_distance = forward.length();
968        if forward_distance <= MIN_MOVE {
969            return None;
970        }
971        let forward_direction = forward / forward_distance;
972
973        // Rise. A settled capsule is already a skin width off its floor, and
974        // that gap is what lets a step of exactly `step_offset` clear its own
975        // top rather than starting the advance in contact with it. An overhead
976        // obstruction shortens the rise instead of cancelling it.
977        let rise = self.clear_travel(world, self.position, UP * self.config.step_offset);
978        if rise <= MIN_MOVE {
979            return None;
980        }
981        let raised = self.position + UP * rise;
982
983        // Advance. No progress up here means this is a wall and not a step.
984        let advance = self.clear_travel(world, raised, forward);
985        if advance <= MIN_MOVE {
986            return None;
987        }
988        // Drop, far enough to actually reach what it is landing on: the rise
989        // it is undoing plus the gap it started from, or a step of no height at
990        // all comes back as a sweep that ends exactly at contact and is
991        // reported as a miss. Unreal spends the same two floor distances on it.
992        let drop = rise + self.config.skin_width * GROUND_PROBE_SKINS;
993        let land = |world: &mut WorldReader<'_, '_>, advance: f64| {
994            let over = raised + forward_direction * advance;
995            let (_, landing) = world.view.sweep_upright_where(
996                &Capsule::new(over, self.config.radius, self.config.half_height),
997                over - UP * drop,
998                self.filter(),
999                world.scratch,
1000                |hit| hit.normal.dot(UP) > MIN_MOVE,
1001            )?;
1002            (!landing.started_inside).then_some((advance, over, landing))
1003        };
1004        let (advance, over, landing) = land(world, advance)?;
1005        if !self.is_walkable(landing.normal)
1006            && !self.perches_on(world, landing.point, over, forward_direction)
1007        {
1008            return None;
1009        }
1010        // The step is as high as what it lands on, not as high as the capsule
1011        // rose: a round capsule on a rounded edge sits lower than the edge's
1012        // top, and would otherwise climb a step a little higher than the
1013        // offset. `feet` rest a skin above the floor, so this allows the
1014        // offset above the floor and that skin.
1015        let feet = self.position.y - self.config.radius - self.config.half_height;
1016        if landing.point.y - feet > self.config.step_offset {
1017            return None;
1018        }
1019        let fall = (landing.t * drop - self.config.skin_width).clamp(0.0, drop);
1020
1021        Some(StepUp {
1022            position: over - UP * fall,
1023            advance: forward_direction * advance,
1024        })
1025    }
1026
1027    /// Find the ground, and drop onto it if it fell away under the character.
1028    ///
1029    /// The probe is what makes the ground authoritative: a walkable plane the
1030    /// slide loop happened to graze is not standing on it, and a character that
1031    /// walked off a lip is still standing on the floor below. Snapping only
1032    /// happens to a character that was already walking and is not asking to go
1033    /// up, so a jump is not swallowed by the floor it just left.
1034    fn settle_on_ground(
1035        &mut self,
1036        world: &mut WorldReader<'_, '_>,
1037        was_grounded: bool,
1038        motion: DVec3,
1039    ) {
1040        self.ground = None;
1041        // An explicit ascent leaves support even inside the ground probe's
1042        // reach. Use requested motion here: walking uphill also rises, but
1043        // that rise belongs to the ground adjustment and must stay supported.
1044        if motion.dot(UP) > 0.0 {
1045            return;
1046        }
1047        let probe = self.settle_reach(was_grounded, motion);
1048
1049        let Some(mut found) = self.probe_below(world, self.position, probe) else {
1050            return;
1051        };
1052        let ahead = DVec3::new(motion.x, 0.0, motion.z).normalize_or_zero();
1053        let perched = !found.walkable
1054            && was_grounded
1055            && self.perches_on(
1056                world,
1057                found.contact.point,
1058                self.position - UP * found.distance,
1059                ahead,
1060            );
1061        if perched {
1062            // Stood on as a step's corner is, flat: the edge's own normal
1063            // steepens towards horizontal at its rim, and ground-following
1064            // along it would climb without bound. The next move's sweep meets
1065            // the edge ahead and steps on.
1066            found.contact.normal = UP;
1067            found.walkable = true;
1068        }
1069        if !found.walkable {
1070            // A walking character over an edge too steep to stand on, and not
1071            // stepping onto it, slides off it, down its tangent, onto what is
1072            // below within the same reach: a lip walked off lands on the
1073            // floor beneath, while a character that was not walking has only
1074            // the probe's slack to slide and falls.
1075            let Some((landed, below)) = self.slide_off_edge(world, probe, &found) else {
1076                if was_grounded {
1077                    self.position -= UP * self.departure_drop(&found);
1078                }
1079                return;
1080            };
1081            self.position = landed;
1082            found = below;
1083        }
1084        // Signed, and so it corrects in both directions: a capsule that ended
1085        // the move *closer* to the floor than a skin width — set down on it, or
1086        // walked onto it — is lifted back off, which is what keeps the next
1087        // horizontal sweep from starting on the floor's surface and being told
1088        // it is already in contact. Unreal spends `AdjustFloorHeight` on the
1089        // same correction. The lift is capped at the gap it is restoring;
1090        // anything deeper than that is a penetration, and the next move's
1091        // depenetration is what owns it.
1092        let fall = (found.distance - self.config.skin_width).clamp(-self.config.skin_width, probe);
1093        self.position -= UP * fall;
1094        self.ground = Some(found.contact);
1095    }
1096
1097    /// Whether a capsule centred at `centre`, moving horizontally along
1098    /// `ahead`, perches on an edge it touches at `point` that is too steep to
1099    /// stand on: when the edge is ahead of it, so it is stepping onto it, no
1100    /// higher above its feet than the step offset, and **the rim of a walkable
1101    /// top**, which a ray dropped a skin beyond the contact finds within a
1102    /// skin of its height. A steep slope has no top there, only more slope,
1103    /// and is refused: perching on it would climb it a step at a time.
1104    /// Standing still, or moving away, a capsule has nothing ahead, and slides
1105    /// off.
1106    fn perches_on(
1107        &self,
1108        world: &mut WorldReader<'_, '_>,
1109        point: DVec3,
1110        centre: DVec3,
1111        ahead: DVec3,
1112    ) -> bool {
1113        let feet = centre.y - self.config.radius - self.config.half_height;
1114        let toward = DVec3::new(point.x - centre.x, 0.0, point.z - centre.z);
1115        if toward.dot(ahead) <= MIN_MOVE || point.y - feet > self.config.step_offset {
1116            return false;
1117        }
1118        let skin = self.config.skin_width;
1119        let ray = Ray::new(point + ahead * skin + UP * skin, -UP).with_bounds(0.0, 2.0 * skin);
1120        world
1121            .view
1122            .cast_ray_filtered(&ray, self.filter(), world.scratch)
1123            .is_some_and(|(_, top)| !top.started_inside && self.is_walkable(top.normal))
1124    }
1125
1126    /// Where a capsule resting `found.distance` above an edge too steep to
1127    /// stand on comes to rest sliding off it with the rest of `reach`, and
1128    /// the walkable ground it finds there, or `None` if it finds none: the
1129    /// slide follows the edge's surface downward, as far as falls the rest of
1130    /// the reach, and ends a skin short of whatever it meets.
1131    fn slide_off_edge(
1132        &self,
1133        world: &mut WorldReader<'_, '_>,
1134        reach: f64,
1135        found: &GroundProbe,
1136    ) -> Option<(DVec3, GroundProbe)> {
1137        let normal = found.contact.normal;
1138        let down = (-UP + normal * normal.dot(UP)).normalize_or_zero();
1139        let remaining = reach - found.distance;
1140        if down.dot(UP) > -MIN_MOVE || remaining <= MIN_MOVE {
1141            return None;
1142        }
1143        let start = self.position - UP * found.distance;
1144        let length = remaining / -down.dot(UP);
1145        // Only surfaces the slide closes on stop it: the edge it slides along
1146        // is tangent to it and holds nothing back.
1147        let travel = match world.view.sweep_upright_where(
1148            &Capsule::new(start, self.config.radius, self.config.half_height),
1149            start + down * length,
1150            self.filter(),
1151            world.scratch,
1152            |hit| down.dot(hit.normal) < -MIN_MOVE,
1153        ) {
1154            None => length,
1155            Some((_, hit)) => self.skin_short(hit.t * length, down, hit.normal)?,
1156        };
1157        let end = start + down * travel;
1158        let below = self.probe_below(world, end, self.config.skin_width * GROUND_PROBE_SKINS)?;
1159        below.walkable.then_some((end, below))
1160    }
1161
1162    /// How far a character that was standing drops, leaving `found`, an edge
1163    /// too steep to stand on with nothing walkable below it: down to the
1164    /// height at which the edge's rounding meets the slope limit, which is
1165    /// where shorter moves along the same walk would have followed it down to
1166    /// and left it. Without it, where a character starts to fall depends on
1167    /// how its walk was cut into moves: a move ending just past that point
1168    /// left it at the top's height, the rounding's drop above where shorter
1169    /// ones did. Never further than the probe's own contact, so a steep plane
1170    /// is met rather than passed through.
1171    fn departure_drop(&self, found: &GroundProbe) -> f64 {
1172        let skin = self.config.skin_width;
1173        let leaves = found.contact.point.y
1174            + (self.config.radius + skin) * self.config.min_ground_normal_y
1175            + self.config.half_height;
1176        (self.position.y - leaves).clamp(0.0, (found.distance - skin).max(0.0))
1177    }
1178
1179    /// How far below itself a move's closing ground probe looks: the
1180    /// [`step_offset`](CharacterConfig::step_offset) it snaps down by, for a
1181    /// character that was walking and is not asking to go up, and the probe's
1182    /// slack either way.
1183    fn settle_reach(&self, was_grounded: bool, motion: DVec3) -> f64 {
1184        let snap = if was_grounded && motion.dot(UP) <= 0.0 {
1185            self.config.step_offset
1186        } else {
1187            0.0
1188        };
1189        snap + self.config.skin_width * GROUND_PROBE_SKINS
1190    }
1191
1192    /// Sweep the capsule straight down `distance` from `from`, and describe
1193    /// the first surface it touches.
1194    ///
1195    /// The one ground probe: [`settle_on_ground`](Self::settle_on_ground) and
1196    /// the public [`probe_ground_at`](Self::probe_ground_at) both ask it, so
1197    /// the two cannot disagree about what counts as ground.
1198    fn probe_below(
1199        &self,
1200        world: &mut WorldReader<'_, '_>,
1201        from: DVec3,
1202        distance: f64,
1203    ) -> Option<GroundProbe> {
1204        let found = world.view.sweep_upright_where(
1205            &Capsule::new(from, self.config.radius, self.config.half_height),
1206            from - UP * distance,
1207            self.filter(),
1208            world.scratch,
1209            |hit| hit.normal.dot(UP) > MIN_MOVE,
1210        )?;
1211        let probe = self.ground_probe(found, distance);
1212        if probe.walkable {
1213            return Some(probe);
1214        }
1215        Some(self.wedged_footing(world, from - UP * probe.distance, probe))
1216    }
1217
1218    /// `probe`, a surface too steep to stand on alone, as footing when the
1219    /// capsule at `at` is held up by more than one surface whose normals
1220    /// together point up within the slope limit: a capsule wedged in the
1221    /// V-crease of two steep faces stands in it, as EW asked (2026-10-23).
1222    /// The ground it reports is the normals' normalized sum, so slope
1223    /// projection runs along the crease, and a crease too steep along its own
1224    /// length still sums to a normal the limit refuses, and slides.
1225    ///
1226    /// The surfaces are the ones within the probe's slack of the capsule,
1227    /// where the slide loop leaves a resting character a skin off each of
1228    /// them, and only those facing up: a wall beside the capsule holds
1229    /// nothing up. One supporting surface is `probe` itself, refused as it
1230    /// was.
1231    fn wedged_footing(
1232        &self,
1233        world: &mut WorldReader<'_, '_>,
1234        at: DVec3,
1235        probe: GroundProbe,
1236    ) -> GroundProbe {
1237        let reach = Capsule::new(
1238            at,
1239            self.config.radius + self.config.skin_width * GROUND_PROBE_SKINS,
1240            self.config.half_height,
1241        );
1242        let mut normals = Vec::new();
1243        world
1244            .view
1245            .capsule_contact_normals_into(&reach, self.filter(), world.scratch, &mut normals);
1246        let (count, sum) = normals
1247            .iter()
1248            .filter(|normal| normal.dot(UP) > MIN_MOVE)
1249            .fold((0_usize, DVec3::ZERO), |(count, sum), normal| {
1250                (count + 1, sum + *normal)
1251            });
1252        let combined = sum.normalize_or_zero();
1253        if count < 2 || !self.is_walkable(combined) {
1254            return probe;
1255        }
1256        GroundProbe {
1257            contact: GroundContact {
1258                normal: combined,
1259                ..probe.contact
1260            },
1261            walkable: true,
1262            ..probe
1263        }
1264    }
1265
1266    /// A downward sweep of `distance` that met `found`, described as ground.
1267    fn ground_probe(&self, (collider, hit): (ColliderId, ShapeHit), distance: f64) -> GroundProbe {
1268        GroundProbe {
1269            contact: GroundContact {
1270                normal: hit.normal,
1271                point: hit.point,
1272                collider,
1273            },
1274            distance: hit.t * distance,
1275            walkable: self.is_walkable(hit.normal),
1276        }
1277    }
1278
1279    // ── Sweeping ───────────────────────────────────────────────────────
1280
1281    /// How far along `delta` the skin envelope can go. Parallel and departing
1282    /// surfaces do not obstruct the step's rise or forward travel.
1283    fn clear_travel(&self, world: &mut WorldReader<'_, '_>, from: DVec3, delta: DVec3) -> f64 {
1284        let distance = delta.length();
1285        if distance <= MIN_MOVE {
1286            return 0.0;
1287        }
1288        world
1289            .view
1290            .sweep_upright_where(
1291                &Capsule::new(
1292                    from,
1293                    self.config.radius + self.config.skin_width,
1294                    self.config.half_height,
1295                ),
1296                from + delta,
1297                self.filter(),
1298                world.scratch,
1299                |hit| delta.dot(hit.normal) < -MIN_MOVE,
1300            )
1301            .map_or(distance, |(_, hit)| hit.t * distance)
1302    }
1303
1304    /// How far along `direction` the capsule can go toward a contact `along`
1305    /// ahead of it, with surface normal `normal`, and stay a
1306    /// [`skin_width`](CharacterConfig::skin_width) off the surface's plane:
1307    /// `None` when it is already no further than that.
1308    ///
1309    /// The gap is measured along the normal, as a gap is. Measured along the
1310    /// move instead, an oblique approach is left nearer than a skin; the
1311    /// slide backs that off along the normal on its next sweep, and the two
1312    /// then fight — a capsule in a crease bounced between its walls rather
1313    /// than falling down it. The step-up's advance measures it the same way,
1314    /// or a character the slide left a skin off both walls of a corner is
1315    /// offered the diagonal between the two measures as a step.
1316    fn skin_short(&self, along: f64, direction: DVec3, normal: DVec3) -> Option<f64> {
1317        let closing = -direction.dot(normal);
1318        (along * closing > self.config.skin_width).then(|| along - self.config.skin_width / closing)
1319    }
1320
1321    /// The capsule's own sweep, with the character's body and every collider
1322    /// off its query mask left out of it.
1323    fn sweep(
1324        &self,
1325        world: &mut WorldReader<'_, '_>,
1326        from: DVec3,
1327        to: DVec3,
1328    ) -> Option<(ColliderId, ShapeHit)> {
1329        world.view.sweep_capsule_filtered(
1330            &Segment::new(from, to),
1331            self.config.radius,
1332            self.config.half_height,
1333            self.filter(),
1334            world.scratch,
1335        )
1336    }
1337
1338    /// The filter every world query of this controller runs under.
1339    fn filter(&self) -> QueryFilter {
1340        QueryFilter::excluding(self.self_collider).with_mask(self.query_mask)
1341    }
1342}
1343
1344/// Redirect `motion` so it runs along the planes it has collected, after
1345/// `SV_FlyMove`'s plane-set rule.
1346///
1347/// The first plane whose clipped result does not drive into any of the others
1348/// wins. When none does, two planes have a crease to run along — their cross
1349/// product — and anything more is a corner with nowhere to go.
1350///
1351/// `current` is the displacement as the last clip left it, which is what the
1352/// crease is measured against; Quake takes it from the same place.
1353fn clip_to_planes(motion: DVec3, planes: &[DVec3], current: DVec3) -> DVec3 {
1354    for (i, &plane) in planes.iter().enumerate() {
1355        let clipped = motion - plane * motion.dot(plane);
1356        if planes
1357            .iter()
1358            .enumerate()
1359            .all(|(j, &other)| j == i || clipped.dot(other) >= 0.0)
1360        {
1361            return clipped;
1362        }
1363    }
1364    if let [first, second] = planes {
1365        // Normalised, where Quake leaves the cross product at the sine of the
1366        // angle between the planes and quietly shortens the move by it. Quake
1367        // III normalises for the same reason.
1368        let crease = first.cross(*second).normalize_or_zero();
1369        return crease * crease.dot(current);
1370    }
1371    DVec3::ZERO
1372}
1373
1374// ---------------------------------------------------------------------------
1375// Tests
1376// ---------------------------------------------------------------------------
1377
1378#[cfg(test)]
1379mod tests {
1380    use super::*;
1381    use crate::collider::{BoxCollider, Sphere};
1382
1383    /// A ramp big enough that its curvature does not move the slope under the
1384    /// character: over the tenth of a metre these tests walk, the contact angle
1385    /// changes by the travel over this radius.
1386    const DOME_RADIUS: f64 = 1000.0;
1387
1388    /// The centre a capsule needs so its feet are at `feet`.
1389    fn centre_for_feet(config: &CharacterConfig, feet: f64) -> f64 {
1390        feet + config.radius + config.half_height
1391    }
1392
1393    /// A floor whose top is `y = 0`, wide enough that nothing in these tests
1394    /// reaches its edge.
1395    fn flat_world() -> PhysicsWorld {
1396        let mut world = PhysicsWorld::new();
1397        world.add_box(BoxCollider::new(
1398            DVec3::new(0.0, -1.0, 0.0),
1399            DVec3::new(50.0, 1.0, 50.0),
1400        ));
1401        world
1402    }
1403
1404    /// A character standing on `flat_world`'s floor at the origin, already
1405    /// grounded — the zero move is what finds the floor.
1406    fn standing(world: &mut PhysicsWorld, config: CharacterConfig) -> CharacterController {
1407        let mut character =
1408            CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0));
1409        character.move_and_slide(world, DVec3::ZERO);
1410        assert!(character.is_grounded(), "the fixture starts on the floor");
1411        character
1412    }
1413
1414    /// A dome whose summit is `y = 0`, so a character on it stands on a slope
1415    /// of whatever angle `on_dome` places it at.
1416    pub(super) fn dome_world() -> PhysicsWorld {
1417        let mut world = PhysicsWorld::new();
1418        world.add_sphere(Sphere::new(DVec3::new(0.0, -DOME_RADIUS, 0.0), DOME_RADIUS));
1419        world
1420    }
1421
1422    /// The capsule centre that touches the dome exactly where its surface
1423    /// normal is `angle` from vertical, leaning toward `+X`.
1424    ///
1425    /// Exact rather than approximate: a capsule against a sphere is its centre
1426    /// against that sphere grown along Y (see `query`'s swept-capsule note), so
1427    /// the contact normal is the radial direction from the grown shape's top
1428    /// cap, which is what this offsets from.
1429    pub(super) fn on_dome(config: &CharacterConfig, angle: f64) -> DVec3 {
1430        let normal = DVec3::new(
1431            crcbl_core::trig::sin(angle),
1432            crcbl_core::trig::cos(angle),
1433            0.0,
1434        );
1435        DVec3::new(0.0, -DOME_RADIUS + config.half_height, 0.0)
1436            + normal * (DOME_RADIUS + config.radius)
1437    }
1438
1439    /// A floor over `x < 0` whose top is `y = 0`, and a second one over
1440    /// `x > 0` whose top is `y = height`.
1441    pub(super) fn stepped_world(height: f64) -> PhysicsWorld {
1442        let mut world = PhysicsWorld::new();
1443        world.add_box(BoxCollider::new(
1444            DVec3::new(-25.0, -1.0, 0.0),
1445            DVec3::new(25.0, 1.0, 5.0),
1446        ));
1447        world.add_box(BoxCollider::new(
1448            DVec3::new(25.0, (height - 2.0) * 0.5, 0.0),
1449            DVec3::new(25.0, (height + 2.0) * 0.5, 5.0),
1450        ));
1451        world
1452    }
1453
1454    fn feet_of(character: &CharacterController) -> f64 {
1455        character.position().y - character.config().radius - character.config().half_height
1456    }
1457
1458    // ── The unobstructed case ──────────────────────────────────────────
1459
1460    #[test]
1461    fn an_unobstructed_move_covers_the_whole_displacement_and_slides_none() {
1462        let mut world = flat_world();
1463        let mut character = standing(&mut world, CharacterConfig::default());
1464        let outcome = character.move_and_slide(&mut world, DVec3::new(0.2, 0.0, -0.1));
1465
1466        assert_eq!(outcome.slides, 0, "nothing was in the way");
1467        assert!(
1468            (outcome.motion - DVec3::new(0.2, 0.0, -0.1)).length() < 1e-12,
1469            "asked for (0.2, 0, -0.1) and got {:?}",
1470            outcome.motion,
1471        );
1472        assert!(outcome.grounded);
1473        assert!(!outcome.hit_wall && !outcome.hit_ceiling && !outcome.stepped_up);
1474    }
1475
1476    // ── Walls ──────────────────────────────────────────────────────────
1477
1478    /// **Walking into a wall at an angle keeps the speed along it.** Stopping
1479    /// dead against a wall the character is only grazing is the failure this
1480    /// guards; the tangential half of the displacement has to survive intact,
1481    /// not merely mostly.
1482    #[test]
1483    fn walking_into_a_wall_at_an_angle_keeps_the_whole_speed_along_it() {
1484        let mut world = flat_world();
1485        // Its -X face is x = 0, so a capsule centred at x = -0.35 has 0.05 of
1486        // clear approach in front of its flank.
1487        world.add_box(BoxCollider::new(
1488            DVec3::new(4.5, 2.0, 0.0),
1489            DVec3::new(4.5, 3.0, 10.0),
1490        ));
1491        let config = CharacterConfig::default();
1492        let mut character = standing(&mut world, config);
1493        character.set_position(DVec3::new(-0.35, centre_for_feet(&config, 0.0), 0.0));
1494        character.move_and_slide(&mut world, DVec3::ZERO);
1495
1496        let asked = DVec3::new(0.1, 0.0, 0.1);
1497        let outcome = character.move_and_slide(&mut world, asked);
1498
1499        assert!(outcome.hit_wall, "the wall's -X face is 0.05 away");
1500        assert!(
1501            outcome.motion.x < asked.x,
1502            "the wall must have taken something off the approach, and x moved {}",
1503            outcome.motion.x,
1504        );
1505        assert!(
1506            (outcome.motion.z - asked.z).abs() < 1e-12,
1507            "the speed along the wall is {} and was asked to be {}",
1508            outcome.motion.z,
1509            asked.z,
1510        );
1511    }
1512
1513    /// **A move far longer than the obstacle is thick still stops at it.**
1514    /// The whole point of sweeping rather than stepping-and-testing.
1515    #[test]
1516    fn a_move_far_longer_than_the_obstacle_does_not_pass_through_it() {
1517        let mut world = flat_world();
1518        let pane_x = 5.0;
1519        let pane_half_thickness = 0.005;
1520        world.add_box(BoxCollider::new(
1521            DVec3::new(pane_x, 2.0, 0.0),
1522            DVec3::new(pane_half_thickness, 3.0, 10.0),
1523        ));
1524        let config = CharacterConfig::default();
1525        let mut character = standing(&mut world, config);
1526
1527        let outcome = character.move_and_slide(&mut world, DVec3::new(50.0, 0.0, 0.0));
1528
1529        assert!(outcome.hit_wall);
1530        let front = pane_x - pane_half_thickness - config.radius;
1531        assert!(
1532            character.position().x <= front,
1533            "the capsule's flank is at {} and the pane's near face at {front}",
1534            character.position().x + config.radius,
1535        );
1536    }
1537
1538    // ── Slopes ─────────────────────────────────────────────────────────
1539
1540    /// **The slope the controller stops walking is the one it was configured
1541    /// with**, measured rather than assumed.
1542    ///
1543    /// The sweep: place a character on a dome at every tenth of a degree from
1544    /// `0°` to `89.9°`, ground it, then hand it sixty ticks of pure gravity and
1545    /// no horizontal intent at all, and record how far it drifted sideways. On
1546    /// ground it can stand on the answer is exactly zero — that is
1547    /// `ground_adjusted`'s refusal to creep. On ground it cannot, gravity is
1548    /// clipped to the surface and the character slides down it.
1549    ///
1550    /// Measured with [`CharacterConfig::default`]: the drift stays at zero up
1551    /// to the configured limit and is non-zero one step past it, which brackets
1552    /// the limit to within the sweep's own step. The comparison is `>=`, so a
1553    /// slope exactly at the limit is walkable.
1554    ///
1555    /// **The bracket is closed at both ends, and it has to be.** Which of the
1556    /// two adjacent samples the limit lands on is not portable: the dome's
1557    /// surface normal arrives through `sin`/`cos`, those are platform
1558    /// transcendentals, and a last-ulp difference moves a slope that sits
1559    /// exactly on the threshold to either side of it. Linux measures the limit
1560    /// as the last still sample and Windows as the first creeping one, from the
1561    /// same source. Asserting an open end pins the measurement finer than the
1562    /// sweep's step can resolve, which is a claim about a libm rather than
1563    /// about this controller.
1564    #[test]
1565    fn the_slope_the_controller_stops_walking_is_the_one_it_was_configured_with() {
1566        let config = CharacterConfig::default();
1567        let step_degrees = 0.1;
1568        // Big enough to cross the skin gap in one tick: a fall shorter than
1569        // that never touches the ground and the ground never gets a say.
1570        let gravity = DVec3::new(0.0, -0.05, 0.0);
1571
1572        let mut last_still: Option<f64> = None;
1573        let mut first_creep: Option<f64> = None;
1574        for tenth in 0..900 {
1575            let degrees = f64::from(tenth) * step_degrees;
1576            let mut world = dome_world();
1577            let mut character =
1578                CharacterController::new(config, on_dome(&config, degrees.to_radians()));
1579            character.move_and_slide(&mut world, DVec3::ZERO);
1580            let start = character.position();
1581            for _ in 0..60 {
1582                character.move_and_slide(&mut world, gravity);
1583            }
1584            let drift = (character.position() - start).x;
1585            if first_creep.is_none() {
1586                if drift == 0.0 {
1587                    last_still = Some(degrees);
1588                } else {
1589                    first_creep = Some(degrees);
1590                }
1591            }
1592        }
1593
1594        let (Some(last_still), Some(first_creep)) = (last_still, first_creep) else {
1595            panic!(
1596                "the sweep never crossed a boundary: {last_still:?} was the last still \
1597                 slope and {first_creep:?} the first creeping one",
1598            );
1599        };
1600        #[expect(
1601            clippy::disallowed_methods,
1602            reason = "the platform's arccosine is the oracle"
1603        )]
1604        let limit = config.min_ground_normal_y.acos().to_degrees();
1605        assert!(
1606            last_still <= limit && limit <= first_creep,
1607            "the boundary was measured at {last_still}° still / {first_creep}° creeping, \
1608             and the configured limit is {limit}° — the two samples are one \
1609             {step_degrees}° step apart, so the limit has to fall between them",
1610        );
1611    }
1612
1613    /// **A surface exactly at the limit is walkable**, which the sweep above
1614    /// cannot say.
1615    ///
1616    /// That sweep brackets the boundary to a tenth of a degree and no finer,
1617    /// and which of its two adjacent samples the limit lands on moves with the
1618    /// platform's `sin`/`cos` — so flipping `is_walkable`'s comparison from
1619    /// `>=` to `>` shifts it by exactly the amount a different libm does, and
1620    /// the sweep cannot tell the two apart. This can: the normal is built
1621    /// **from** [`CharacterConfig::min_ground_normal_y`] rather than from an
1622    /// angle, so its rise is that number bit for bit on every target, and no
1623    /// transcendental stands between the configuration and the answer.
1624    #[test]
1625    fn a_surface_exactly_at_the_limit_is_walkable() {
1626        let config = CharacterConfig::default();
1627        let character = CharacterController::new(config, DVec3::ZERO);
1628        let rise = config.min_ground_normal_y;
1629        // Unit length, and its Y component is `rise` exactly — the `sqrt` only
1630        // ever touches the horizontal lane.
1631        let exactly = DVec3::new((1.0 - rise * rise).sqrt(), rise, 0.0);
1632
1633        assert_eq!(
1634            exactly.y, rise,
1635            "the test's own normal must carry the configured rise unrounded"
1636        );
1637        assert!(
1638            character.is_walkable(exactly),
1639            "a surface whose rise is exactly {rise} must be walkable, because the \
1640             comparison is `>=` and the limit is the last slope you can stand on"
1641        );
1642    }
1643
1644    /// **Walking up a walkable slope covers the same horizontal ground as
1645    /// walking on the flat**, which is Unreal's
1646    /// `bMaintainHorizontalGroundVelocity` and the reason a ramp does not feel
1647    /// like treacle.
1648    #[test]
1649    #[expect(
1650        clippy::disallowed_methods,
1651        reason = "the platform's tangent is the oracle"
1652    )]
1653    fn a_walkable_slope_is_climbed_without_losing_horizontal_ground() {
1654        let config = CharacterConfig::default();
1655        let angle = 30.0_f64.to_radians();
1656        let mut world = dome_world();
1657        let mut character = CharacterController::new(config, on_dome(&config, angle));
1658        character.move_and_slide(&mut world, DVec3::ZERO);
1659        assert!(character.is_grounded(), "30° is inside the default limit");
1660
1661        // Uphill is -X: the character is on the +X flank of the dome.
1662        let asked = DVec3::new(-0.05, 0.0, 0.0);
1663        let before = character.position();
1664        let outcome = character.move_and_slide(&mut world, asked);
1665        let moved = character.position() - before;
1666
1667        assert!(
1668            (moved.x - asked.x).abs() < 1e-6,
1669            "the horizontal ground covered was {} and the request was {}",
1670            moved.x,
1671            asked.x,
1672        );
1673        assert!(
1674            (moved.y - asked.x.abs() * angle.tan()).abs() < 1e-4,
1675            "climbing 0.05 m of a 30° slope should rise {}, and it rose {}",
1676            asked.x.abs() * angle.tan(),
1677            moved.y,
1678        );
1679        assert!(outcome.grounded);
1680    }
1681
1682    // ── Steps ──────────────────────────────────────────────────────────
1683
1684    /// **The step the controller stops climbing is the offset it was
1685    /// configured with**, measured rather than assumed.
1686    ///
1687    /// The sweep: build a floor and a raised second floor at every millimetre
1688    /// from `0` to `0.6 m`, walk a grounded character into the join for thirty
1689    /// ticks of 0.05 m, and record whether it ended up on top.
1690    ///
1691    /// Measured with [`CharacterConfig::default`]: every step through `0.409 m`
1692    /// is climbed and `0.410 m` is the first that is not. The band above the
1693    /// configured offset is one [`CharacterConfig::skin_width`] wide, because
1694    /// a settled capsule already floats that far off its floor and the rise
1695    /// starts from there.
1696    #[test]
1697    fn the_step_the_controller_stops_climbing_is_the_offset_it_was_configured_with() {
1698        let config = CharacterConfig::default();
1699        let step_metres = 0.001;
1700
1701        let mut last_climbed: Option<f64> = None;
1702        let mut first_blocked: Option<f64> = None;
1703        for milli in 0..=600 {
1704            let height = f64::from(milli) * step_metres;
1705            let mut world = stepped_world(height);
1706            let mut character = CharacterController::new(
1707                config,
1708                DVec3::new(-1.0, centre_for_feet(&config, 0.0), 0.0),
1709            );
1710            character.move_and_slide(&mut world, DVec3::ZERO);
1711            for _ in 0..30 {
1712                character.move_and_slide(&mut world, DVec3::new(0.05, 0.0, 0.0));
1713            }
1714            let climbed =
1715                character.position().x > 0.2 && (feet_of(&character) - height).abs() < 0.02;
1716            if first_blocked.is_none() {
1717                if climbed {
1718                    last_climbed = Some(height);
1719                } else {
1720                    first_blocked = Some(height);
1721                }
1722            }
1723        }
1724
1725        let last_climbed = last_climbed.expect("a zero-height step is walked straight over");
1726        let first_blocked = first_blocked.expect("a 0.6 m step is not a step");
1727        assert!(
1728            last_climbed >= config.step_offset,
1729            "a step of exactly the configured offset must be climbed, and the last \
1730             one climbed was {last_climbed}",
1731        );
1732        assert!(
1733            first_blocked <= config.step_offset + config.skin_width + step_metres,
1734            "the first step refused was {first_blocked}, which is more than one skin \
1735             width above the configured offset of {}",
1736            config.step_offset,
1737        );
1738    }
1739
1740    /// **Walking off a lip inside the step offset keeps the character on the
1741    /// ground**, rather than dropping it into a one-tick fall on every stair.
1742    #[test]
1743    fn walking_off_a_lip_within_the_step_offset_never_leaves_the_ground() {
1744        let config = CharacterConfig::default();
1745        let drop = 0.3;
1746        let mut world = stepped_world(-drop);
1747        let mut character =
1748            CharacterController::new(config, DVec3::new(-1.0, centre_for_feet(&config, 0.0), 0.0));
1749        character.move_and_slide(&mut world, DVec3::ZERO);
1750
1751        for tick in 0..30 {
1752            let outcome = character.move_and_slide(&mut world, DVec3::new(0.05, 0.0, 0.0));
1753            assert!(
1754                outcome.grounded,
1755                "tick {tick} left the ground at x = {}, y = {}",
1756                character.position().x,
1757                character.position().y,
1758            );
1759        }
1760        assert!(character.position().x > 0.2, "it walked past the lip");
1761        assert!(
1762            (feet_of(&character) + drop).abs() < config.skin_width * 2.0,
1763            "it should be standing on the lower floor at {}, and its feet are at {}",
1764            -drop,
1765            feet_of(&character),
1766        );
1767    }
1768
1769    /// The other half of the snap: a drop deeper than the step offset is a
1770    /// fall, and the character has to leave the ground for it.
1771    #[test]
1772    fn walking_off_a_drop_past_the_step_offset_leaves_the_ground() {
1773        let config = CharacterConfig::default();
1774        let mut world = stepped_world(-(config.step_offset * 2.0));
1775        let mut character =
1776            CharacterController::new(config, DVec3::new(-1.0, centre_for_feet(&config, 0.0), 0.0));
1777        character.move_and_slide(&mut world, DVec3::ZERO);
1778
1779        let mut left_the_ground = false;
1780        for _ in 0..30 {
1781            left_the_ground |= !character
1782                .move_and_slide(&mut world, DVec3::new(0.05, 0.0, 0.0))
1783                .grounded;
1784        }
1785        assert!(
1786            left_the_ground,
1787            "the character walked over a {} m drop without ever falling",
1788            config.step_offset * 2.0,
1789        );
1790    }
1791
1792    /// **A character pressed into a corner does not climb it.** The step-up's
1793    /// advance is what refuses: after rising, a corner is still a wall in both
1794    /// directions, so there is nowhere to step onto and the whole step is
1795    /// reverted rather than leaving the capsule up in the air.
1796    #[test]
1797    fn a_character_pressed_into_a_corner_does_not_climb_it() {
1798        let config = CharacterConfig::default();
1799        let mut world = flat_world();
1800        world.add_box(BoxCollider::new(
1801            DVec3::new(5.5, 2.0, 0.0),
1802            DVec3::new(5.0, 3.0, 10.0),
1803        ));
1804        world.add_box(BoxCollider::new(
1805            DVec3::new(0.0, 2.0, 5.5),
1806            DVec3::new(10.0, 3.0, 5.0),
1807        ));
1808        let mut character = standing(&mut world, config);
1809        let resting_feet = feet_of(&character);
1810
1811        let mut planes_at_once = 0;
1812        for _ in 0..60 {
1813            let outcome = character.move_and_slide(&mut world, DVec3::new(0.05, 0.0, 0.05));
1814            planes_at_once = planes_at_once.max(outcome.slides);
1815            assert!(
1816                feet_of(&character) <= resting_feet + config.skin_width,
1817                "the character rose to {} from {resting_feet}",
1818                feet_of(&character),
1819            );
1820            assert!(
1821                !outcome.stepped_up,
1822                "a corner is not a step, and it was climbed at y = {}",
1823                character.position().y,
1824            );
1825        }
1826        assert!(
1827            character.position().x > 0.1 && character.position().z > 0.1,
1828            "the character should have slid along both walls before wedging, and \
1829             stopped at {:?}",
1830            character.position(),
1831        );
1832        assert!(
1833            planes_at_once >= 2,
1834            "the corner never presented two planes in one move, so the clipping \
1835             this is about never ran",
1836        );
1837    }
1838
1839    // ── Depenetration ──────────────────────────────────────────────────
1840
1841    /// **A capsule that wakes up inside a box leaves through the nearest
1842    /// face**, by the depth it is in by, and not by a teleport to somewhere
1843    /// convenient.
1844    #[test]
1845    fn a_capsule_that_starts_inside_a_box_is_pushed_out_of_the_nearest_face() {
1846        let config = CharacterConfig::default();
1847        let mut world = PhysicsWorld::new();
1848        let half = DVec3::new(1.0, 1.0, 1.0);
1849        world.add_box(BoxCollider::new(DVec3::ZERO, half));
1850
1851        // Buried 0.2 m short of the +X face and dead centre on the others, so
1852        // +X is the only shortest way out.
1853        let inside = DVec3::new(half.x - 0.2, 0.0, 0.0);
1854        let mut character = CharacterController::new(config, inside);
1855        let outcome = character.move_and_slide(&mut world, DVec3::ZERO);
1856
1857        let mut still_inside = Vec::new();
1858        world.capsule_penetrations_into(&character.capsule(), None, &mut still_inside);
1859        assert!(
1860            still_inside.is_empty(),
1861            "the capsule is still inside {still_inside:?} after being pushed out",
1862        );
1863        let expected = DVec3::X * (config.radius + 0.2 + config.skin_width);
1864        assert!(
1865            (outcome.depenetration - expected).length() < 1e-12,
1866            "expected a push of {expected:?} and got {:?}",
1867            outcome.depenetration,
1868        );
1869    }
1870
1871    /// The push has to converge: a character standing clear of everything must
1872    /// not be shoved on every tick for ever.
1873    #[test]
1874    fn a_capsule_clear_of_the_world_is_not_pushed_at_all() {
1875        let config = CharacterConfig::default();
1876        let mut world = flat_world();
1877        // Set down at the gap a settled capsule keeps, so it is touching
1878        // nothing — and the move must leave it exactly where it is.
1879        let mut character = CharacterController::new(
1880            config,
1881            DVec3::new(0.0, centre_for_feet(&config, config.skin_width), 0.0),
1882        );
1883
1884        let outcome = character.move_and_slide(&mut world, DVec3::ZERO);
1885
1886        assert_eq!(
1887            outcome.depenetration,
1888            DVec3::ZERO,
1889            "a capsule a skin width clear of its floor is inside nothing",
1890        );
1891        assert!(
1892            outcome.grounded,
1893            "and it is standing on the floor it is clear of"
1894        );
1895    }
1896
1897    // ── Jumping and the ground snap ────────────────────────────────────
1898
1899    /// An upward move is used exactly as it was asked for: the ground
1900    /// adjustment stands aside the moment the character asks to leave the
1901    /// ground, or a jump would be flattened into a walk.
1902    #[test]
1903    fn an_upward_move_covers_its_whole_rise() {
1904        let mut world = flat_world();
1905        let mut character = standing(&mut world, CharacterConfig::default());
1906        let before = character.position().y;
1907
1908        character.move_and_slide(&mut world, DVec3::new(0.0, 0.2, 0.0));
1909
1910        assert!(
1911            (character.position().y - before - 0.2).abs() < 1e-12,
1912            "asked to rise 0.2 and rose {}",
1913            character.position().y - before,
1914        );
1915    }
1916
1917    /// And the ground snap does not reach up after it. The snap is for a
1918    /// character that was walking and stayed down, not for one that jumped.
1919    #[test]
1920    fn an_upward_move_is_not_pulled_back_by_the_ground_snap() {
1921        let config = CharacterConfig::default();
1922        for rise in [config.skin_width * 0.1, 0.2] {
1923            let mut world = flat_world();
1924            let mut character = standing(&mut world, config);
1925            for _ in 0..2 {
1926                let motion = DVec3::new(0.005, rise, 0.0);
1927                let outcome = character.move_and_slide(&mut world, motion);
1928                assert!(
1929                    !outcome.grounded,
1930                    "the floor reached up and took the jump back: rise={rise}"
1931                );
1932                assert!((outcome.motion - motion).length() < 1e-12);
1933            }
1934        }
1935    }
1936
1937    /// **A grounded character asked for nothing but gravity does not move.**
1938    /// On the flat that is trivial; on a slope it is the whole of
1939    /// `floor_stop_on_slope`, because gravity clipped against a 40° face has a
1940    /// downhill component on every single tick.
1941    #[test]
1942    fn gravity_alone_does_not_walk_a_grounded_character_down_a_slope() {
1943        let config = CharacterConfig::default();
1944        let mut world = dome_world();
1945        let mut character =
1946            CharacterController::new(config, on_dome(&config, 40.0_f64.to_radians()));
1947        character.move_and_slide(&mut world, DVec3::ZERO);
1948        assert!(character.is_grounded(), "40° is inside the default limit");
1949
1950        let before = character.position();
1951        for tick in 0..60 {
1952            let outcome = character.move_and_slide(&mut world, DVec3::new(0.0, -0.05, 0.0));
1953            assert_eq!(
1954                (outcome.motion.x, outcome.motion.z),
1955                (0.0, 0.0),
1956                "tick {tick} walked sideways",
1957            );
1958            assert!(outcome.grounded, "tick {tick} left the slope");
1959        }
1960        let drift = character.position() - before;
1961        assert_eq!(
1962            (drift.x, drift.z),
1963            (0.0, 0.0),
1964            "it ended up downhill by {drift:?}"
1965        );
1966        assert!(
1967            drift.y.abs() < config.skin_width,
1968            "it sank {} into the slope, which is more than the gap it settles to",
1969            -drift.y,
1970        );
1971    }
1972
1973    // ── The character's own collider ───────────────────────────────────
1974
1975    #[test]
1976    fn clearing_self_collider_preserves_ground_and_movement_state() {
1977        let config = CharacterConfig::default();
1978        let mut world = flat_world();
1979        let mut character =
1980            CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0));
1981        character.move_and_slide(&mut world, DVec3::ZERO);
1982        assert!(character.is_grounded());
1983        let position = character.position();
1984        let ground = character.ground().cloned();
1985        let body = world.add_capsule(character.capsule());
1986        character.set_self_collider(Some(body));
1987        assert_eq!(character.self_collider, Some(body));
1988        assert_eq!(character.position(), position);
1989        assert_eq!(character.ground(), ground.as_ref());
1990        character.set_self_collider(None);
1991        assert_eq!(character.self_collider, None);
1992        assert_eq!(character.position(), position);
1993        assert_eq!(character.ground(), ground.as_ref());
1994        assert!(world.remove(body));
1995        let moved = character.move_and_slide(&mut world, DVec3::new(0.2, 0.0, 0.0));
1996        assert!((moved.motion.x - 0.2).abs() < 1e-12);
1997        assert!(moved.grounded);
1998    }
1999
2000    #[test]
2001    fn a_character_registered_in_the_world_is_left_out_of_its_own_sweeps() {
2002        let config = CharacterConfig::default();
2003        let mut world = flat_world();
2004        let body = world.add_capsule(Capsule::new(
2005            DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0),
2006            config.radius,
2007            config.half_height,
2008        ));
2009        let mut character =
2010            CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0))
2011                .with_self_collider(body);
2012
2013        character.move_and_slide(&mut world, DVec3::ZERO);
2014
2015        let outcome = character.move_and_slide(&mut world, DVec3::new(0.2, 0.0, 0.0));
2016        assert!(
2017            (outcome.motion.x - 0.2).abs() < 1e-12,
2018            "its own body blocked it: it moved {}",
2019            outcome.motion.x,
2020        );
2021        let aabb = world.aabb_of(body).expect("the body is still registered");
2022        assert!(
2023            (aabb.centre() - character.position()).length() < 1e-12,
2024            "the world's copy is at {:?} and the character at {:?}",
2025            aabb.centre(),
2026            character.position(),
2027        );
2028    }
2029
2030    // ── The public ground probe ────────────────────────────────────────
2031
2032    /// The probe length a caller asks "is it standing on something" with: the
2033    /// move's own slack.
2034    fn standing_probe(config: &CharacterConfig) -> f64 {
2035        config.skin_width * GROUND_PROBE_SKINS
2036    }
2037
2038    #[test]
2039    fn a_probe_under_a_settled_character_finds_its_floor_a_skin_width_down() {
2040        let config = CharacterConfig::default();
2041        let mut world = PhysicsWorld::new();
2042        let floor = world.add_box(BoxCollider::new(
2043            DVec3::new(0.0, -1.0, 0.0),
2044            DVec3::new(50.0, 1.0, 50.0),
2045        ));
2046        let character = standing(&mut world, config);
2047
2048        let found = character
2049            .probe_ground(&mut world, standing_probe(&config))
2050            .expect("a settled character is standing on its floor");
2051
2052        assert_eq!(found.contact.collider, floor);
2053        assert!(
2054            (found.contact.normal - DVec3::Y).length() < 1e-12,
2055            "the floor faces up, and the probe reported {:?}",
2056            found.contact.normal,
2057        );
2058        assert!(
2059            (found.distance - config.skin_width).abs() < 1e-9,
2060            "a settled capsule floats one skin width ({}) up, and the probe \
2061             measured {}",
2062            config.skin_width,
2063            found.distance,
2064        );
2065        assert!(found.walkable);
2066        assert_eq!(
2067            Some(&found.contact),
2068            character.ground(),
2069            "the move and the probe share one sweep, so they name the same contact",
2070        );
2071    }
2072
2073    #[test]
2074    fn a_probe_from_above_its_distance_finds_nothing() {
2075        let config = CharacterConfig::default();
2076        let mut world = flat_world();
2077        let height = 1.0;
2078        let character = CharacterController::new(
2079            config,
2080            DVec3::new(0.0, centre_for_feet(&config, height), 0.0),
2081        );
2082
2083        assert_eq!(
2084            character.probe_ground(&mut world, standing_probe(&config)),
2085            None,
2086            "the floor is {height} m down and the probe looked {} m",
2087            standing_probe(&config),
2088        );
2089        // And the miss is the distance, not a probe that cannot see the floor.
2090        let far = character
2091            .probe_ground(&mut world, height * 2.0)
2092            .expect("a long enough probe reaches the floor");
2093        assert!(
2094            (far.distance - height).abs() < 1e-9,
2095            "the floor is {height} m below the feet and the probe measured {}",
2096            far.distance,
2097        );
2098    }
2099
2100    #[test]
2101    fn a_probe_on_a_slope_past_the_limit_reads_as_not_walkable() {
2102        let config = CharacterConfig::default();
2103        let mut world = dome_world();
2104        let at = |degrees: f64| on_dome(&config, degrees.to_radians()) + UP * config.skin_width;
2105        let character = CharacterController::new(config, DVec3::ZERO);
2106
2107        let steep = character
2108            .probe_ground_at(&mut world, at(60.0), standing_probe(&config))
2109            .expect("the dome is a skin width under the capsule");
2110        assert!(
2111            !steep.walkable,
2112            "60° is past the default 45° limit, and the probe called it walkable \
2113             with normal {:?}",
2114            steep.contact.normal,
2115        );
2116        assert!(steep.contact.normal.y < config.min_ground_normal_y);
2117
2118        let gentle = character
2119            .probe_ground_at(&mut world, at(30.0), standing_probe(&config))
2120            .expect("the dome is a skin width under the capsule");
2121        assert!(gentle.walkable, "30° is inside the default limit");
2122    }
2123
2124    #[test]
2125    fn a_probe_leaves_the_controller_and_its_world_body_where_they_were() {
2126        let config = CharacterConfig::default();
2127        let mut world = flat_world();
2128        let body = world.add_capsule(Capsule::new(
2129            DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0),
2130            config.radius,
2131            config.half_height,
2132        ));
2133        let mut character =
2134            CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0))
2135                .with_self_collider(body);
2136        character.move_and_slide(&mut world, DVec3::ZERO);
2137        let position = character.position();
2138        let ground = character.ground().copied();
2139        let aabb = world.aabb_of(body);
2140        assert!(ground.is_some(), "the fixture starts on the floor");
2141
2142        let here = character.probe_ground(&mut world, standing_probe(&config));
2143        let aloft = character.probe_ground_at(
2144            &mut world,
2145            DVec3::new(3.0, centre_for_feet(&config, 2.0), 0.0),
2146            standing_probe(&config),
2147        );
2148
2149        assert_ne!(
2150            here.map(|found| found.contact.collider),
2151            Some(body),
2152            "the probe found the character's own body",
2153        );
2154        assert!(here.is_some_and(|found| found.walkable));
2155        assert_eq!(aloft, None);
2156        assert_eq!(character.position(), position);
2157        assert_eq!(character.ground().copied(), ground);
2158        assert_eq!(world.aabb_of(body), aabb);
2159    }
2160
2161    /// **`ground()` is the last move's answer; the probe is the world's
2162    /// current one.** Ported from EW's
2163    /// `support_refresh_rejects_removed_floor_without_advancing_stamina_clocks`:
2164    /// take the floor away and the recorded ground still names it, while a
2165    /// fresh probe finds nothing and moves nothing.
2166    #[test]
2167    fn a_probe_sees_a_removed_floor_that_ground_still_reports() {
2168        let config = CharacterConfig::default();
2169        let mut world = PhysicsWorld::new();
2170        let floor = world.add_box(BoxCollider::new(
2171            DVec3::new(0.0, -1.0, 0.0),
2172            DVec3::new(50.0, 1.0, 50.0),
2173        ));
2174        let character = standing(&mut world, config);
2175        assert!(
2176            character
2177                .probe_ground(&mut world, standing_probe(&config))
2178                .is_some_and(|found| found.walkable)
2179        );
2180        let position = character.position();
2181
2182        assert!(world.remove(floor));
2183
2184        assert!(
2185            character.is_grounded(),
2186            "ground() is the last move's record"
2187        );
2188        assert_eq!(
2189            character.probe_ground(&mut world, standing_probe(&config)),
2190            None
2191        );
2192        assert_eq!(character.position(), position);
2193    }
2194
2195    /// Ported from EW's `unsupported_spawn_cannot_begin_revival_even_with_valid_reach`:
2196    /// a character placed 0.1 m over its floor has no support within the
2197    /// move's slack.
2198    #[test]
2199    fn a_character_spawned_a_tenth_of_a_metre_up_has_no_support() {
2200        let config = CharacterConfig::default();
2201        let mut world = flat_world();
2202        let character =
2203            CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.1), 0.0));
2204
2205        assert_eq!(
2206            character.probe_ground(&mut world, standing_probe(&config)),
2207            None
2208        );
2209    }
2210
2211    #[test]
2212    #[should_panic(expected = "non-negative distance")]
2213    fn a_probe_refuses_a_negative_distance() {
2214        let mut world = flat_world();
2215        let character = standing(&mut world, CharacterConfig::default());
2216        let _ = character.probe_ground(&mut world, -0.1);
2217    }
2218}
2219
2220#[cfg(test)]
2221#[path = "character/query_mask_tests.rs"]
2222mod query_mask_tests;
2223
2224#[cfg(test)]
2225#[path = "character/lying_tests.rs"]
2226mod lying_tests;
2227
2228#[cfg(test)]
2229#[path = "character/lying_move_tests.rs"]
2230mod lying_move_tests;
2231
2232#[cfg(test)]
2233#[path = "character/lying_turn_tests.rs"]
2234mod lying_turn_tests;
2235
2236#[cfg(test)]
2237#[path = "character/lying_contact_tests.rs"]
2238mod lying_contact_tests;
2239
2240#[cfg(test)]
2241#[path = "character/slide_contact_tests.rs"]
2242mod slide_contact_tests;
2243
2244#[cfg(test)]
2245#[path = "character/crease_tests.rs"]
2246mod crease_tests;
2247
2248#[cfg(test)]
2249#[path = "character/edge_tests.rs"]
2250mod edge_tests;
2251
2252#[cfg(test)]
2253#[path = "character/rest_tests.rs"]
2254mod rest_tests;
2255
2256#[cfg(test)]
2257#[path = "character/skin_tests.rs"]
2258mod skin_tests;
2259
2260#[cfg(test)]
2261#[path = "character/preview_tests.rs"]
2262mod preview_tests;