Skip to main content

voxel_framework/player/
mod.rs

1//! Six-degrees-of-freedom (6DOF) player controller for zero-gravity environments.
2//!
3//! This module implements a first-person camera-player that moves freely in all
4//! six directions with no gravity, no floor constraint, and no pitch clamp — the
5//! equivalent of an astronaut or jetpack pilot. The camera entity IS the player:
6//! there is no separate hierarchy between the logical player and the rendered
7//! view.
8//!
9//! Collisions are resolved against loaded voxel chunks using a capsule-vs-AABB
10//! algorithm that correctly handles any 6DOF orientation, including full roll and
11//! inverted pitch.
12//!
13//! # Physics model
14//!
15//! Velocity is smoothed each frame using exponential lerp:
16//!
17//! - **Accelerating** (key held): `velocity = lerp(velocity, target, acceleration * dt)`
18//! - **Decelerating** (no input): `velocity = lerp(velocity, Vec3::ZERO, deceleration * dt)`
19//!
20//! The two rates come from [`PlayerMovementConfig`] (defaults 12 and 7).
21//!
22//! This gives snappy starts and a natural coast-to-stop feel without requiring a
23//! fixed physics timestep.
24//!
25//! # Quick start — [`PlayerPlugin`]
26//!
27//! The simplest integration: add [`PlayerPlugin`] and everything is wired
28//! automatically. Systems run every frame, or only while unpaused when
29//! [`PauseMenuPlugin`](crate::ui::PauseMenuPlugin) is installed.
30//!
31//! ```rust,no_run
32//! use bevy::prelude::*;
33//! use voxel_framework::prelude::*;
34//! use voxel_framework::player::PlayerPlugin;
35//!
36//! App::new()
37//!     .add_plugins(DefaultPlugins)
38//!     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
39//!     .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
40//!     .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
41//!     .run();
42//! ```
43//!
44//! # AppState integration
45//!
46//! When your game has an `AppState` enum, keep [`PlayerPlugin`] and gate (or
47//! order) all of its `Update` systems through the [`PlayerSystems`] set:
48//!
49//! ```rust,no_run
50//! # use bevy::prelude::*;
51//! # use voxel_framework::player::{PlayerPlugin, PlayerSystems};
52//! # use voxel_framework::voxel::DefaultVoxel;
53//! # #[derive(States, Default, Clone, PartialEq, Eq, Hash, Debug)]
54//! # enum AppState { #[default] Playing }
55//! App::new()
56//!     .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
57//!     .configure_sets(Update, PlayerSystems.run_if(in_state(AppState::Playing)));
58//! ```
59//!
60//! Alternatively, skip [`PlayerPlugin`] and register the systems manually
61//! (this drops the plugin's spawn-position persistence):
62//!
63//! ```rust,no_run
64//! # use bevy::prelude::*;
65//! # use voxel_framework::player::{spawn_player, player_look, player_move, player_cursor_system};
66//! # use voxel_framework::player::player_resolve_collision;
67//! # use voxel_framework::voxel::DefaultVoxel;
68//! # #[derive(States, Default, Clone, PartialEq, Eq, Hash, Debug)]
69//! # enum AppState { #[default] Playing }
70//! App::new()
71//!     .add_systems(Startup, spawn_player)
72//!     .add_systems(Update,
73//!         (player_look, player_move::<DefaultVoxel>, player_resolve_collision::<DefaultVoxel>)
74//!             .chain()
75//!             .run_if(in_state(AppState::Playing)),
76//!     )
77//!     .add_systems(Update, player_cursor_system);
78//! ```
79//!
80//! # Camera response to movement
81//!
82//! [`CameraResponseConfig`] adds an optional speed-based field-of-view boost
83//! and a lean toward sideways movement. It is neutral by default. See
84//! [`camera_response`] for how it composes with look, movement and the base
85//! field of view; when registering the systems manually, run
86//! [`camera_response_restore`] before [`player_look`] and
87//! [`camera_response_apply`] after [`player_resolve_collision`].
88//!
89//! # Cursor management contract
90//!
91//! [`spawn_player`] leaves the cursor free. [`player_cursor_system`] manages
92//! the primary window's lock state without requesting OS keyboard focus:
93//!
94//! - **Left click** in the focused window while cursor is free → locks and hides it.
95//! - **Focus loss** → releases the cursor; returning requires another click.
96//! - **First Escape** while cursor is locked → releases cursor (makes it visible).
97//! - **Escape** while cursor is already free → closes the focused window.
98//!
99//! Look and movement require a focused primary window with a captured cursor.
100//! Headless calls without a primary window retain synthetic-input support.
101//!
102//! With [`PauseMenuPlugin`](crate::ui::PauseMenuPlugin) installed the pause
103//! menu owns Escape: [`player_cursor_system`] ignores the key (Escape opens
104//! the menu and never closes the window) and keeps handling click-to-capture
105//! and focus-loss release while the game is unpaused. The menu releases the
106//! cursor when it opens and captures it again on resume.
107//!
108//! # Controls
109//!
110//! | Input        | Action                              |
111//! |--------------|-------------------------------------|
112//! | Mouse        | Yaw + pitch (6DOF, no clamp)        |
113//! | Q / E        | Roll left / right                   |
114//! | W / S        | Forward / backward                  |
115//! | A / D        | Strafe left / right                 |
116//! | Space        | Move along local up                 |
117//! | Shift        | Move along local down               |
118//! | Left click   | Lock cursor                         |
119//! | Escape       | Release cursor (if already free: close focused window); opens the pause menu instead when `PauseMenuPlugin` is installed |
120
121use bevy::ecs::message::MessageWriter;
122use bevy::input::mouse::MouseMotion;
123use bevy::prelude::*;
124use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
125
126use crate::audio::{SfxEvent, SfxRequest};
127use crate::chunk::{CHUNK_SIZE, Chunk, VOXEL_SIZE, world_to_chunk_coord};
128use crate::voxel::VoxelType;
129use crate::world::{ChunkManager, ViewerPosition, WorldDataDir, get_voxel_at};
130
131pub mod camera_response;
132pub mod effects;
133pub mod persistence;
134
135pub use camera_response::{
136    CameraResponse, CameraResponseConfig, camera_response_apply, camera_response_restore,
137};
138
139// ─── Health & damage messages ─────────────────────────────────────────────────
140
141/// Emitted when the player takes damage from any source.
142#[derive(Message, Debug, Clone)]
143pub struct PlayerDamaged {
144    /// Amount of health points lost.
145    pub amount: f32,
146}
147
148/// Emitted when the player's health reaches zero and they respawn.
149#[derive(Message, Debug, Clone)]
150pub struct PlayerDied;
151
152/// Player health and respawn state.
153///
154/// Inserted as a resource by [`PlayerPlugin`]. Games can read and modify
155/// `health` directly (e.g. from environmental hazards); fall damage is applied
156/// automatically when landing with high vertical velocity.
157///
158/// When `health` drops to zero the player is teleported to `spawn_position`
159/// and health is restored to `max_health`. A [`PlayerDied`] message is sent.
160#[derive(Resource, Debug, Clone)]
161pub struct PlayerHealth {
162    /// Current health points. Clamped to `[0, max_health]` after damage.
163    pub health: f32,
164    /// Maximum health points. **Default: `20.0`.**
165    pub max_health: f32,
166    /// World position used for respawn on death.
167    ///
168    /// Defaults to the player's spawn position from [`PlayerConfig`]. Games
169    /// can update this at runtime (e.g. when placing a bed or checkpoint).
170    pub spawn_position: Vec3,
171    /// Vertical fall speed (m/s) below which no fall damage is taken.
172    ///
173    /// Impact speeds below this threshold deal zero damage. **Default: `10.0`.**
174    pub fall_safe_speed: f32,
175}
176
177impl Default for PlayerHealth {
178    fn default() -> Self {
179        Self {
180            health: 20.0,
181            max_health: 20.0,
182            spawn_position: Vec3::new(0.0, 30.0, 0.0),
183            fall_safe_speed: 10.0,
184        }
185    }
186}
187
188// ─── PlayerCrouching resource ─────────────────────────────────────────────────
189
190/// Tracks whether the player is currently crouching.
191///
192/// Updated every frame by [`player_move`] in [`PlayerMode::Grounded`] mode
193/// based on `ControlLeft` key state. Readable by external systems (e.g. UI,
194/// animation) without querying the [`Player`] component directly.
195///
196/// The resource mirrors [`Player::crouching`] and is kept in sync by
197/// [`player_move`] each frame. Modifying it directly has no effect — it is
198/// overwritten by the movement system.
199#[derive(Resource, Default, Debug, Clone, Copy, PartialEq, Eq)]
200pub struct PlayerCrouching(pub bool);
201
202// ─── PlayerMode ──────────────────────────────────────────────────────────────
203
204/// Selects the movement model used by [`PlayerPlugin`] and the player systems.
205///
206/// Set this inside [`PlayerConfig::mode`] before adding [`PlayerPlugin`] (or
207/// before the `Startup` schedule runs).  Changing the mode at runtime is
208/// **not** supported — the value is copied into the [`Player`] component once
209/// on spawn and used from there.
210///
211/// # Variants
212///
213/// - [`PlayerMode::FreeFlightSixDof`] — classic 6DOF, no gravity.  Default.
214/// - [`PlayerMode::FreeFlightAnchored`] — free flight with a world-axis-anchored horizon.
215/// - [`PlayerMode::Grounded`] — gravity + jump, WASD on the XZ plane, pitch
216///   clamped to ±89°.  Suitable for Minetest / Minecraft–style games.
217#[derive(Debug, Clone)]
218pub enum PlayerMode {
219    /// Six-degrees-of-freedom flight. No gravity, no pitch clamp, Q/E roll.
220    ///
221    /// This is the default mode and matches the original behaviour of the
222    /// player controller.  All six movement axes (forward, back, left, right,
223    /// up, down) are relative to the camera's current orientation.
224    FreeFlightSixDof {
225        /// How Q/E roll input is applied.
226        roll_mode: RollMode,
227    },
228    /// Six-degrees-of-freedom flight with an FPS-style, world-axis-anchored
229    /// horizon. Q/E switch the anchor axis instead of rolling.
230    FreeFlightAnchored,
231    /// Gravity-based grounded movement.
232    ///
233    /// - WASD moves on the **world XZ plane** relative to the camera's current
234    ///   yaw, ignoring pitch tilt.
235    /// - `Space` jumps when [`Player::on_ground`] is `true`.
236    /// - Gravity accumulates in [`Player::vertical_velocity`] each frame.
237    /// - Mouse yaw rotates the entity around the **world Y axis** (player stays
238    ///   upright); pitch rotates the view up/down and is clamped to ±89°.
239    /// - Q/E roll is disabled.
240    Grounded {
241        /// Downward acceleration in world units per second squared.
242        ///
243        /// Applied every frame as `vertical_velocity -= gravity * dt`.
244        /// Typical value: `20.0`.
245        gravity: f32,
246        /// Upward velocity impulse applied when the player jumps.
247        ///
248        /// Assigned to [`Player::vertical_velocity`] on the frame `Space` is
249        /// pressed while [`Player::on_ground`] is `true`.  Typical value: `8.0`.
250        jump_speed: f32,
251    },
252}
253
254impl Default for PlayerMode {
255    fn default() -> Self {
256        PlayerMode::FreeFlightSixDof {
257            roll_mode: RollMode::Continuous,
258        }
259    }
260}
261
262// ─── Physics constants ────────────────────────────────────────────────────────
263
264/// Radius of the player's collision capsule in world units (≈ 0.6 voxels).
265///
266/// Each hemispherical end cap of the capsule has this radius. The value keeps
267/// the player from clipping single-voxel corners while still fitting through
268/// one-voxel-wide gaps when combined with [`PLAYER_HALF_HEIGHT`].
269pub const PLAYER_RADIUS: f32 = 0.6;
270
271/// Half-height of the capsule's cylindrical spine in world units (≈ 1.8 voxels).
272///
273/// The spine runs along the player's local Y axis between offsets
274/// `−PLAYER_HALF_HEIGHT` and `+PLAYER_HALF_HEIGHT` from the entity origin.
275/// The total capsule height is `2 × (PLAYER_HALF_HEIGHT + PLAYER_RADIUS)` ≈ 4.8
276/// world units. In 6DOF mode this axis rolls with the player's orientation.
277pub const PLAYER_HALF_HEIGHT: f32 = 1.8;
278
279/// Half-height of the capsule when crouching (≈ 60% of normal).
280///
281/// Reduces the total capsule height enough to let the player pass through
282/// gaps that are one voxel tall. Used by [`player_resolve_collision`] when
283/// [`Player::crouching`] is `true` in [`PlayerMode::Grounded`] mode.
284pub const CROUCH_HALF_HEIGHT: f32 = PLAYER_HALF_HEIGHT * 0.6;
285
286/// Speed multiplier applied to horizontal movement while sprinting.
287///
288/// Active in [`PlayerMode::Grounded`] when `Shift` is held and the player is
289/// on solid ground. Crouch takes priority — if both are held this multiplier
290/// is not applied. See [`player_move`] and [`PlayerCrouching`].
291pub const SPRINT_MULTIPLIER: f32 = 1.6;
292
293/// Lerp factor applied when the player is accelerating.
294const ACCEL: f32 = 12.0;
295
296/// Lerp factor applied when the player is decelerating (no input).
297const DECEL: f32 = 7.0;
298
299/// How quickly the player reaches and loses speed, and when a collision counts
300/// as an impact.
301///
302/// [`PlayerPlugin`] initializes this resource with the defaults. Insert your
303/// own value to tune the feel of movement:
304///
305/// ```rust,no_run
306/// use bevy::prelude::*;
307/// use voxel_framework::prelude::*;
308///
309/// App::new()
310///     .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
311///     .insert_resource(PlayerMovementConfig {
312///         acceleration: 4.0, // slower to reach speed
313///         deceleration: 2.0, // longer coast
314///         ..default()
315///     });
316/// ```
317///
318/// Each frame the velocity moves toward its target by
319/// `min(rate * dt, 1.0)` of the remaining difference, so a higher rate means a
320/// snappier response. The values are read every frame.
321///
322/// [`player_move`] and [`player_resolve_collision`] also run without this
323/// resource (a game registering them by hand) and then use the defaults.
324#[derive(Resource, Debug, Clone, Copy, PartialEq)]
325pub struct PlayerMovementConfig {
326    /// Rate at which velocity approaches the target while a movement key is
327    /// held. Default [`PlayerMovementConfig::DEFAULT_ACCELERATION`]. A
328    /// negative or non-finite value falls back to the default.
329    pub acceleration: f32,
330    /// Rate at which velocity approaches zero with no movement input. In
331    /// grounded mode it is further scaled by the surface friction. Default
332    /// [`PlayerMovementConfig::DEFAULT_DECELERATION`]. A negative or
333    /// non-finite value falls back to the default.
334    pub deceleration: f32,
335    /// Speed into a surface, in world units per second, above which a
336    /// collision emits [`PlayerImpact`]. `f32::INFINITY` disables the message.
337    /// Default [`PlayerMovementConfig::DEFAULT_IMPACT_SPEED_THRESHOLD`].
338    pub impact_speed_threshold: f32,
339    /// When `true`, [`player_move`] does not move the player into a volume
340    /// where a chunk is not loaded yet (see [`player_chunks_loaded`]). The
341    /// player stays in place for that frame and moves again once the chunks
342    /// arrive. Default `false`: a chunk that is not loaded is empty space.
343    ///
344    /// Turn it on for a player that can outrun chunk loading, such as free
345    /// flight over terrain generated in the background. It needs a chunk
346    /// source that loads every requested chunk, like `GeneratorPlugin`; a
347    /// chunk that never loads would hold the player forever.
348    pub wait_for_chunks: bool,
349}
350
351impl PlayerMovementConfig {
352    /// Default [`acceleration`](Self::acceleration).
353    pub const DEFAULT_ACCELERATION: f32 = ACCEL;
354    /// Default [`deceleration`](Self::deceleration).
355    pub const DEFAULT_DECELERATION: f32 = DECEL;
356    /// Default [`impact_speed_threshold`](Self::impact_speed_threshold).
357    pub const DEFAULT_IMPACT_SPEED_THRESHOLD: f32 = 1.0;
358
359    fn acceleration_rate(config: Option<&Self>) -> f32 {
360        config
361            .map(|c| c.acceleration)
362            .filter(|rate| rate.is_finite() && *rate >= 0.0)
363            .unwrap_or(Self::DEFAULT_ACCELERATION)
364    }
365
366    fn deceleration_rate(config: Option<&Self>) -> f32 {
367        config
368            .map(|c| c.deceleration)
369            .filter(|rate| rate.is_finite() && *rate >= 0.0)
370            .unwrap_or(Self::DEFAULT_DECELERATION)
371    }
372
373    fn impact_threshold(config: Option<&Self>) -> f32 {
374        config
375            .map(|c| c.impact_speed_threshold)
376            .unwrap_or(Self::DEFAULT_IMPACT_SPEED_THRESHOLD)
377    }
378}
379
380impl Default for PlayerMovementConfig {
381    fn default() -> Self {
382        Self {
383            acceleration: Self::DEFAULT_ACCELERATION,
384            deceleration: Self::DEFAULT_DECELERATION,
385            impact_speed_threshold: Self::DEFAULT_IMPACT_SPEED_THRESHOLD,
386            wait_for_chunks: false,
387        }
388    }
389}
390
391/// Emitted by [`player_resolve_collision`] when the player runs into terrain.
392///
393/// One message is written when the speed into the surface rises above
394/// [`PlayerMovementConfig::impact_speed_threshold`]. Staying pressed against
395/// the same surface does not repeat it; the speed has to drop below the
396/// threshold (or contact has to end) before another impact is reported.
397///
398/// [`PlayerPlugin`] registers the message. Typical use is feedback scaled by
399/// `speed`, such as a sound.
400#[derive(Message, Debug, Clone, Copy, PartialEq)]
401pub struct PlayerImpact {
402    /// Player position after the collision was resolved.
403    pub position: Vec3,
404    /// Unit vector pointing away from the surface that was hit.
405    pub normal: Vec3,
406    /// Speed into the surface at the moment of contact, in world units per
407    /// second. Always above the configured threshold.
408    pub speed: f32,
409}
410
411/// Internal mouse scale factor applied before the user-facing
412/// [`Player::sensitivity`] multiplier.
413///
414/// Mouse deltas arrive in pixels (often `10+` per frame) so a raw multiplier of
415/// `1.0` would spin the camera wildly. This constant converts pixels to a base
416/// rad/px rate comparable to Minecraft, so that `sensitivity = 1.0` feels
417/// "normal". Users scale around this via the Settings slider (10% → very slow,
418/// 100% → default, above 100% would be faster but the slider caps there).
419const MOUSE_SCALE: f32 = 0.003;
420
421// ─── Snap roll types ─────────────────────────────────────────────────────────
422
423/// Selects how Q/E roll input is applied in [`PlayerMode::FreeFlightSixDof`].
424///
425/// - [`RollMode::Continuous`] — roll while the key is held (original behavior).
426/// - [`RollMode::Snap`] — each key press animates a snap rotation to the
427///   next world-aligned up candidate (a signed world axis projected onto the
428///   roll plane).
429///
430/// Configured by `PlayerMode::FreeFlightSixDof { roll_mode }`; defaults to
431/// [`RollMode::Continuous`].
432///
433/// Ignored by [`PlayerMode::FreeFlightAnchored`]: in anchored flight Q/E switch
434/// the anchor axis instead of rolling.
435#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
436pub enum RollMode {
437    /// Roll continuously while Q/E is held (default, original behavior).
438    #[default]
439    Continuous,
440    /// Snap-rotate to the next world-aligned up candidate per key press with
441    /// easing animation (90° steps when forward is on a world axis).
442    Snap,
443}
444
445/// Easing curve used by [`RollMode::Snap`] animations.
446///
447/// Each variant maps to a simple `f(t) -> f32` curve where `t ∈ [0, 1]`.
448/// The default ([`EaseOutCubic`](SnapRollEasing::EaseOutCubic)) gives a snappy
449/// start that decelerates smoothly.
450#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
451pub enum SnapRollEasing {
452    /// `1 − (1 − t)³` — fast start, smooth deceleration (default).
453    #[default]
454    EaseOutCubic,
455    /// `1 − (1 − t)⁴` — slightly slower deceleration than cubic.
456    EaseOutQuart,
457    /// `t² (3 − 2t)` — symmetric S-curve.
458    Smoothstep,
459    /// `t` — constant angular velocity.
460    Linear,
461}
462
463/// Runtime state for an in-progress snap-roll animation.
464///
465/// Stored in [`Player::snap_anim`]. Created by [`start_or_retarget_snap`],
466/// advanced each frame by [`advance_snap`], and cleared when `finished`.
467///
468/// Angles are *relative* to the orientation captured at press time: the
469/// world-aligned candidate is resolved once by [`start_or_retarget_snap`]
470/// (via [`world_lattice_angles`] / [`next_lattice_step`]) and baked into
471/// `target_angle`; the animation then only applies angle differences through
472/// `rotate_local_z`.
473#[derive(Copy, Clone, Debug)]
474pub(crate) struct SnapRollAnim {
475    pub(crate) start_angle: f32,
476    pub(crate) target_angle: f32,
477    pub(crate) elapsed: f32,
478    pub(crate) duration: f32,
479    pub(crate) easing: SnapRollEasing,
480    pub(crate) current_applied: f32,
481}
482
483/// Minimum squared projection length a world axis needs on the roll plane to
484/// count as a lattice candidate in [`world_lattice_angles`]. Keeps an axis
485/// only when it lies ~45° or more away from local Z, so the axis pair the
486/// player is (roughly) looking along never yields near-degenerate up stops —
487/// a mostly-axis-aligned view gives 4 candidates, while a diagonal view (all
488/// axes at ~54.7°) keeps all 6. The constant is `0.49` rather than the exact
489/// `sin²(45°) = 0.5`: on a perfect 45° edge-on view both axis families sit at
490/// projection² ≈ 0.5 and float rounding could otherwise exclude BOTH,
491/// breaking the ≥4-candidate invariant.
492pub(crate) const SNAP_MIN_PROJ_SQ: f32 = 0.49;
493
494/// Angular tolerance in radians within which the reference up already lies ON
495/// a candidate; [`next_lattice_step`] skips that candidate so a press always
496/// produces visible motion (EPS_ON rule).
497pub(crate) const SNAP_EPS_ON: f32 = 1e-3;
498
499// ─── Component ───────────────────────────────────────────────────────────────
500
501/// State component that marks the player camera entity.
502///
503/// Attach this alongside [`Camera3d`] on a single entity. The camera entity
504/// IS the player — there is no separate logical-player / camera hierarchy.
505/// All player systems query for this component to locate the controlled entity.
506///
507/// Prefer constructing through [`PlayerConfig`] via [`spawn_player`] rather
508/// than inserting [`Player`] directly, which also sets the initial transform and
509/// projection from the resource.
510///
511/// # Default values
512///
513/// | Field         | Default  |
514/// |---------------|----------|
515/// | `speed`       | `4.0`    |
516/// | `sensitivity` | `1.0`    |
517/// | `roll_speed`  | `1.5`    |
518/// | `velocity`    | `ZERO`   |
519#[derive(Component, Debug, Clone)]
520pub struct Player {
521    /// Maximum flight speed in world units per second. Clamped implicitly by
522    /// the lerp target: actual speed never exceeds this value regardless of
523    /// frame rate.
524    pub speed: f32,
525    /// Mouse sensitivity multiplier (dimensionless). `1.0` matches the default
526    /// "Minecraft-like" feel via the internal `MOUSE_SCALE` constant; lower
527    /// values are slower, higher values are faster. The Settings slider exposes
528    /// the range `0.10`–`1.00` (10%–100%) to the user.
529    pub sensitivity: f32,
530    /// Roll angular speed in radians per second applied while Q (roll left) or
531    /// E (roll right) is held.
532    pub roll_speed: f32,
533    /// Current world-space velocity in world units per second. Smoothed each
534    /// frame by [`player_move`] using an exponential lerp; do not set this
535    /// directly unless you want to override the current momentum.
536    pub velocity: Vec3,
537    /// Movement mode, copied from [`PlayerConfig::mode`] on spawn.
538    ///
539    /// Determines which branch of [`player_look`], [`player_move`], and
540    /// [`player_resolve_collision`] is executed each frame.
541    pub mode: PlayerMode,
542    /// Vertical velocity used in [`PlayerMode::Grounded`] mode.
543    ///
544    /// Gravity accumulates here each frame; a jump impulse sets it to
545    /// [`PlayerMode::Grounded::jump_speed`]. Reset to `0.0` when the player
546    /// lands (collision pushes upward).  Unused in [`PlayerMode::FreeFlightSixDof`].
547    pub vertical_velocity: f32,
548    /// Whether the player was on solid ground at the end of the last frame.
549    ///
550    /// Set to `true` by [`player_resolve_collision`] when a voxel collision
551    /// produces an upward push; cleared to `false` at the start of each
552    /// collision pass.  Gating jumps on this flag prevents infinite jumping.
553    /// Unused in [`PlayerMode::FreeFlightSixDof`].
554    pub on_ground: bool,
555    /// Absolute landing speed (m/s) recorded when the player just touched ground.
556    ///
557    /// Set by [`player_resolve_collision`] on the first landing frame;
558    /// zero at all other times. Read by [`player_fall_damage`] to compute
559    /// and apply damage. Only meaningful in [`PlayerMode::Grounded`].
560    pub(crate) impact_speed: f32,
561    /// Accumulated seconds since the last footstep sound was emitted.
562    ///
563    /// Managed by [`player_footstep_system`]. Reset to `0.0` after each
564    /// footstep; only meaningful in [`PlayerMode::Grounded`].
565    pub(crate) footstep_timer: f32,
566    /// Whether the initial chunk load has completed.
567    ///
568    /// Set to `false` on spawn; flipped to `true` in `player_resolve_collision`
569    /// once the chunk at the player's feet is registered in [`ChunkManager`].
570    /// While `false`, gravity is suppressed so the player does not fall through
571    /// un-loaded terrain during world generation.
572    pub(crate) world_loaded: bool,
573    /// `true` until the player's first landing after spawn (or respawn).
574    ///
575    /// Skips fall-damage on that landing so a spawn point slightly above the
576    /// terrain surface does not instantly kill the player.  Cleared on first
577    /// contact with solid ground.
578    pub(crate) spawn_immune: bool,
579    /// Whether the player is currently sprinting.
580    ///
581    /// `true` when `Shift` is held in [`PlayerMode::Grounded`] with
582    /// [`Player::on_ground`] `true`, and [`Player::crouching`] is `false`.
583    /// Crouch takes priority: if both are held this is `false`.
584    /// Always `false` in [`PlayerMode::FreeFlightSixDof`].
585    pub sprinting: bool,
586    /// Whether the player is currently crouching.
587    ///
588    /// `true` when `Ctrl` is held in [`PlayerMode::Grounded`] mode.
589    /// Reduces the effective capsule half-height to [`CROUCH_HALF_HEIGHT`]
590    /// and movement speed to 40% of base speed.
591    /// Always `false` in [`PlayerMode::FreeFlightSixDof`].
592    pub crouching: bool,
593    /// Duration in seconds for a single snap-roll step animation (one hop to
594    /// the next world-aligned up candidate).
595    /// Only used when `roll_mode == RollMode::Snap`. **Default: `0.5`.**
596    pub snap_roll_duration: f32,
597    /// Easing curve for snap-roll animations.
598    /// Only used when `roll_mode == RollMode::Snap`.
599    pub snap_roll_easing: SnapRollEasing,
600    /// Active snap-roll animation state (runtime-only, not persisted).
601    pub(crate) snap_anim: Option<SnapRollAnim>,
602    /// Current anchor axis for [`PlayerMode::FreeFlightAnchored`] look: always one of the
603    /// 6 signed world axes. Yaw orbits this axis; pitch is clamped to ±89°
604    /// from the plane perpendicular to it. Initialized on spawn to the signed
605    /// world axis nearest the spawn orientation's up. Unused in
606    /// [`PlayerMode::FreeFlightSixDof`].
607    pub anchor_up: Vec3,
608    /// Source signed world axis of an in-flight anchor switch, committed to
609    /// [`Player::anchor_up`] when the animation finishes (runtime-only).
610    pub(crate) pending_anchor: Option<Vec3>,
611}
612
613impl Default for Player {
614    fn default() -> Self {
615        Self {
616            speed: 4.0,
617            sensitivity: 1.0,
618            roll_speed: 1.5,
619            velocity: Vec3::ZERO,
620            mode: PlayerMode::default(),
621            vertical_velocity: 0.0,
622            on_ground: false,
623            impact_speed: 0.0,
624            footstep_timer: 0.0,
625            world_loaded: false,
626            spawn_immune: true,
627            sprinting: false,
628            crouching: false,
629            snap_roll_duration: 0.5,
630            snap_roll_easing: SnapRollEasing::EaseOutCubic,
631            snap_anim: None,
632            anchor_up: Vec3::Y,
633            pending_anchor: None,
634        }
635    }
636}
637
638// ─── Configuration resource ───────────────────────────────────────────────────
639
640/// Startup configuration for [`spawn_player`].
641///
642/// Insert this resource before [`PlayerPlugin`] (or before the `Startup`
643/// schedule runs) to override any default. Fields are consumed once by
644/// [`spawn_player`]; changing the resource after spawn has no effect.
645///
646/// # Example
647///
648/// ```rust,no_run
649/// use bevy::prelude::*;
650/// use voxel_framework::player::PlayerConfig;
651///
652/// App::new()
653///     .insert_resource(PlayerConfig {
654///         spawn_position: Vec3::new(0.0, 50.0, 150.0),
655///         speed: 8.0,
656///         fov_degrees: 80.0,
657///         ..Default::default()
658///     });
659/// ```
660///
661/// # Default values
662///
663/// | Field           | Default                   |
664/// |-----------------|---------------------------|
665/// | `spawn_position`| `(0.0, 0.0, 30.0)`        |
666/// | `speed`         | `4.0` wu/s                |
667/// | `sensitivity`   | `1.0` (unitless multiplier) |
668/// | `roll_speed`    | `1.5` rad/s               |
669/// | `look_at`       | `Vec3::ZERO`              |
670/// | `fov_degrees`   | `90.0`                    |
671#[derive(Resource, Debug, Clone)]
672pub struct PlayerConfig {
673    /// World-space position at which the player entity is spawned.
674    pub spawn_position: Vec3,
675    /// Maximum flight speed in world units per second. Copied into
676    /// [`Player::speed`] on spawn.
677    pub speed: f32,
678    /// Mouse sensitivity multiplier (dimensionless). Copied into
679    /// [`Player::sensitivity`] on spawn. `1.0` = default "Minecraft-like" feel;
680    /// see `MOUSE_SCALE` for the underlying rad/px rate.
681    pub sensitivity: f32,
682    /// Roll angular speed in radians per second. Copied into
683    /// [`Player::roll_speed`] on spawn.
684    pub roll_speed: f32,
685    /// World-space point the camera looks toward immediately after spawning.
686    /// Only affects the initial orientation; the player can look anywhere
687    /// afterwards via mouse input.
688    pub look_at: Vec3,
689    /// Vertical field-of-view in degrees. Valid range: `50.0`–`120.0`.
690    /// Converted to radians and stored in the [`PerspectiveProjection`] on
691    /// spawn; runtime changes must be made directly on the [`Projection`]
692    /// component (e.g., via the Settings menu).
693    pub fov_degrees: f32,
694    /// Movement model used by the player systems.
695    ///
696    /// Defaults to [`PlayerMode::FreeFlightSixDof`] for backwards compatibility.
697    /// Set to [`PlayerMode::Grounded`] for gravity-based gameplay.
698    pub mode: PlayerMode,
699    /// Duration in seconds for a single snap-roll step animation (one hop to
700    /// the next world-aligned up candidate).
701    /// Copied into [`Player::snap_roll_duration`] on spawn. **Default: `0.5`.**
702    pub snap_roll_duration_secs: f32,
703    /// Easing curve for snap-roll animations.
704    /// Copied into [`Player::snap_roll_easing`] on spawn.
705    pub snap_roll_easing: SnapRollEasing,
706}
707
708impl Default for PlayerConfig {
709    fn default() -> Self {
710        Self {
711            spawn_position: Vec3::new(0.0, 0.0, 30.0),
712            speed: 4.0,
713            sensitivity: 1.0,
714            roll_speed: 1.5,
715            look_at: Vec3::ZERO,
716            fov_degrees: 90.0,
717            mode: PlayerMode::default(),
718            snap_roll_duration_secs: 0.5,
719            snap_roll_easing: SnapRollEasing::EaseOutCubic,
720        }
721    }
722}
723
724// ─── Systems ──────────────────────────────────────────────────────────────────
725
726/// Spawns the player camera entity configured by [`PlayerConfig`].
727///
728/// This system is **idempotent**: if a [`Player`] entity already exists in the
729/// world it returns immediately without spawning a second one. This makes it
730/// safe to register on `Startup` even when transitioning through `AppState`
731/// variants that re-enter the startup flow.
732///
733/// Leaves the cursor free. A focused left click through [`player_cursor_system`]
734/// activates native player input; pointer capture never grants keyboard focus.
735///
736/// Writes the spawn position to [`ViewerPosition`] when that resource exists,
737/// so the world streams around the player before the first input.
738pub fn spawn_player(
739    mut commands: Commands,
740    config: Res<PlayerConfig>,
741    existing: Query<(), With<Player>>,
742    mut health: ResMut<PlayerHealth>,
743    viewer: Option<ResMut<ViewerPosition>>,
744) {
745    if !existing.is_empty() {
746        return;
747    }
748
749    // Stream the world around the spawn from the first frame, before any
750    // input makes the player move.
751    if let Some(mut viewer) = viewer {
752        viewer.position = config.spawn_position;
753    }
754
755    // Sync spawn_position with the configured spawn so respawn lands in the right place.
756    health.spawn_position = config.spawn_position;
757
758    let spawn = config.spawn_position;
759    let look_at = config.look_at;
760    let fov = config.fov_degrees.to_radians();
761    let mode = config.mode.clone();
762
763    // Build the transform first so the anchor axis can be derived from the
764    // actual spawn orientation.
765    let transform = Transform::from_translation(spawn).looking_at(look_at, Vec3::Y);
766
767    commands.spawn((
768        Player {
769            speed: config.speed,
770            sensitivity: config.sensitivity,
771            roll_speed: config.roll_speed,
772            velocity: Vec3::ZERO,
773            mode,
774            vertical_velocity: 0.0,
775            on_ground: false,
776            impact_speed: 0.0,
777            footstep_timer: 0.0,
778            world_loaded: false,
779            spawn_immune: true,
780            sprinting: false,
781            crouching: false,
782            snap_roll_duration: config.snap_roll_duration_secs,
783            snap_roll_easing: config.snap_roll_easing,
784            snap_anim: None,
785            anchor_up: nearest_world_axis(*transform.up()),
786            pending_anchor: None,
787        },
788        Camera3d::default(),
789        Projection::Perspective(PerspectiveProjection { fov, ..default() }),
790        transform,
791    ));
792}
793
794// ─── Snap roll helpers ──────────────────────────────────────────────────────
795
796pub(crate) fn apply_easing(t: f32, easing: SnapRollEasing) -> f32 {
797    match easing {
798        SnapRollEasing::EaseOutCubic => 1.0 - (1.0 - t).powi(3),
799        SnapRollEasing::EaseOutQuart => 1.0 - (1.0 - t).powi(4),
800        SnapRollEasing::Smoothstep => t * t * (3.0 - 2.0 * t),
801        SnapRollEasing::Linear => t,
802    }
803}
804
805/// The 6 signed world axes in canonical order.
806///
807/// The order is load-bearing: it is the candidate iteration order of
808/// [`world_lattice_candidates`] and the deterministic tie-break sequence of
809/// [`nearest_world_axis`] (first-in-order wins).
810pub(crate) const AXES: [Vec3; 6] = [
811    Vec3::X,
812    Vec3::NEG_X,
813    Vec3::Y,
814    Vec3::NEG_Y,
815    Vec3::Z,
816    Vec3::NEG_Z,
817];
818
819/// Like [`world_lattice_angles`] but returns `(angle δ, SOURCE signed world
820/// axis)` per surviving candidate.
821///
822/// The candidate set is the 6 signed world axes ([`AXES`]) projected onto
823/// the plane perpendicular to `local_z` and normalized. Axes whose projection
824/// has length² < [`SNAP_MIN_PROJ_SQ`] are excluded — an axis within 45° of
825/// the roll axis is "the one you are looking along" and would yield a
826/// perceptually arbitrary up stop (at least 4 candidates always survive).
827/// Each angle is `δ = atan2(cross(up, c) · local_z, up · c)` — the
828/// [`Transform::rotate_local_z`] convention, so δ feeds it unmodified.
829pub(crate) fn world_lattice_candidates(local_z: Vec3, up: Vec3) -> Vec<(f32, Vec3)> {
830    let mut candidates = Vec::with_capacity(6);
831    for axis in AXES {
832        let proj = axis - axis.dot(local_z) * local_z;
833        if proj.length_squared() < SNAP_MIN_PROJ_SQ {
834            continue;
835        }
836        let c = proj.normalize();
837        candidates.push((up.cross(c).dot(local_z).atan2(up.dot(c)), axis));
838    }
839    candidates
840}
841
842/// Signed roll angles δ ∈ (−π, π] from `up` to each surviving world-axis
843/// candidate around the roll axis `local_z` (Bevy's BACK vector).
844///
845/// Thin wrapper over [`world_lattice_candidates`] that drops each candidate's
846/// source axis — see that function for the lattice rule.
847pub(crate) fn world_lattice_angles(local_z: Vec3, up: Vec3) -> Vec<f32> {
848    world_lattice_candidates(local_z, up)
849        .into_iter()
850        .map(|(a, _)| a)
851        .collect()
852}
853
854/// Next lattice step in press direction `dir` (+1 = Q / CCW, −1 = E / CW).
855///
856/// dir > 0 → min over `{δ > SNAP_EPS_ON ? δ : δ + TAU}`;
857/// dir < 0 → max over `{δ < −SNAP_EPS_ON ? δ : δ − TAU}`.
858/// Candidates within [`SNAP_EPS_ON`] of the reference up wrap a full turn
859/// (EPS_ON rule), so the result is always a nonzero signed angle.
860pub(crate) fn next_lattice_step(angles: &[f32], dir: i32) -> f32 {
861    use std::f32::consts::TAU;
862    if dir > 0 {
863        angles
864            .iter()
865            .map(|&d| if d > SNAP_EPS_ON { d } else { d + TAU })
866            .fold(f32::INFINITY, f32::min)
867    } else {
868        angles
869            .iter()
870            .map(|&d| if d < -SNAP_EPS_ON { d } else { d - TAU })
871            .fold(f32::NEG_INFINITY, f32::max)
872    }
873}
874
875/// Mirror of [`next_lattice_step`] carrying each candidate's source axis:
876/// same [`SNAP_EPS_ON`] wrap, min (dir > 0) / max (dir < 0) by wrapped angle.
877/// Returns the wrapped angle together with the winning candidate's SOURCE
878/// signed world axis.
879///
880/// The caller guarantees a non-empty slice (the [`SNAP_MIN_PROJ_SQ`]
881/// ≥4-candidate invariant); panics otherwise rather than returning garbage.
882pub(crate) fn next_lattice_candidate(cands: &[(f32, Vec3)], dir: i32) -> (f32, Vec3) {
883    use std::f32::consts::TAU;
884    assert!(
885        !cands.is_empty(),
886        "next_lattice_candidate: empty candidate slice — SNAP_MIN_PROJ_SQ \
887         guarantees at least 4 lattice candidates"
888    );
889    if dir > 0 {
890        cands
891            .iter()
892            .map(|&(d, axis)| (if d > SNAP_EPS_ON { d } else { d + TAU }, axis))
893            .min_by(|a, b| a.0.total_cmp(&b.0))
894            .unwrap()
895    } else {
896        cands
897            .iter()
898            .map(|&(d, axis)| (if d < -SNAP_EPS_ON { d } else { d - TAU }, axis))
899            .max_by(|a, b| a.0.total_cmp(&b.0))
900            .unwrap()
901    }
902}
903
904/// Builds (or retargets) a snap-roll animation toward the next world-aligned
905/// up candidate in press direction `dir`.
906///
907/// `local_z` / `up` are `*transform.local_z()` / `*transform.up()` at press
908/// time. Every press resolves through one primitive — "next candidate in
909/// direction `dir` from a reference up" ([`world_lattice_angles`] +
910/// [`next_lattice_step`]):
911///
912/// - **Fresh press** — reference = `up`; the animation starts at `0.0`
913///   toward the first step.
914/// - **Same direction mid-animation** — reference = the in-flight target up
915///   (`up` advanced by the not-yet-applied residual; exact because
916///   `up ⊥ local_z`); retargets one candidate further, resuming from the
917///   currently applied angle.
918/// - **Opposite direction mid-animation** — reference = `up`; reverses to
919///   the nearest candidate behind, resuming from the currently applied angle.
920///
921/// The target is fixed here at press time and never re-resolved mid-flight.
922/// Angles stay relative: [`advance_snap`] applies only differences via
923/// `rotate_local_z`, so the animation lands exactly on the world candidate
924/// computed from `local_z` / `up`.
925pub(crate) fn start_or_retarget_snap(
926    existing: Option<SnapRollAnim>,
927    local_z: Vec3,
928    up: Vec3,
929    dir: i32,
930    duration: f32,
931    easing: SnapRollEasing,
932) -> SnapRollAnim {
933    match existing {
934        None => {
935            let step = next_lattice_step(&world_lattice_angles(local_z, up), dir);
936            SnapRollAnim {
937                start_angle: 0.0,
938                target_angle: step,
939                elapsed: 0.0,
940                duration,
941                easing,
942                current_applied: 0.0,
943            }
944        }
945        Some(anim) => {
946            let same_dir = (dir > 0 && anim.target_angle > anim.start_angle)
947                || (dir < 0 && anim.target_angle < anim.start_angle);
948
949            if same_dir {
950                // Reference = in-flight target up: advance `up` by the
951                // not-yet-applied residual, then extend one candidate further.
952                let residual = anim.target_angle - anim.current_applied;
953                let ref_up = Quat::from_axis_angle(local_z, residual) * up;
954                let step = next_lattice_step(&world_lattice_angles(local_z, ref_up), dir);
955                SnapRollAnim {
956                    start_angle: anim.current_applied,
957                    target_angle: anim.target_angle + step,
958                    elapsed: 0.0,
959                    duration,
960                    easing,
961                    current_applied: anim.current_applied,
962                }
963            } else {
964                // Opposite direction: nearest candidate behind current up.
965                let step = next_lattice_step(&world_lattice_angles(local_z, up), dir);
966                SnapRollAnim {
967                    start_angle: anim.current_applied,
968                    target_angle: anim.current_applied + step,
969                    elapsed: 0.0,
970                    duration,
971                    easing,
972                    current_applied: anim.current_applied,
973                }
974            }
975        }
976    }
977}
978
979/// The reference up [`start_or_retarget_snap`] resolves candidates from,
980/// replicated as a pure helper so the Anchored arm can compute the SOURCE
981/// axis of the exact candidate the animation will land on:
982///
983/// - Same direction mid-animation → `up` advanced by the not-yet-applied
984///   residual (`Quat::from_axis_angle(local_z, target − applied) * up`).
985/// - Fresh press or opposite direction → `up` unchanged.
986pub(crate) fn snap_reference_up(
987    existing: Option<SnapRollAnim>,
988    local_z: Vec3,
989    up: Vec3,
990    dir: i32,
991) -> Vec3 {
992    match existing {
993        Some(anim) => {
994            let same_dir = (dir > 0 && anim.target_angle > anim.start_angle)
995                || (dir < 0 && anim.target_angle < anim.start_angle);
996            if same_dir {
997                let residual = anim.target_angle - anim.current_applied;
998                Quat::from_axis_angle(local_z, residual) * up
999            } else {
1000                up
1001            }
1002        }
1003        None => up,
1004    }
1005}
1006
1007/// Clamps a pitch delta so `asin(forward · anchor_up)` stays within ±89°.
1008///
1009/// `pitch = asin(clamp(forward · anchor_up, −1, 1))`; returns
1010/// `clamp(pitch + pitch_d, ±89°) − pitch`. The clamp-then-subtract form gives
1011/// exact truncation at the poles for free: at the limit, outward deltas
1012/// return 0 while inward deltas pass through. Pure and NaN-free (the dot is
1013/// clamped to asin's domain).
1014pub(crate) fn clamp_pitch_delta(forward: Vec3, anchor_up: Vec3, pitch_d: f32) -> f32 {
1015    let limit = 89_f32.to_radians();
1016    let pitch = forward.dot(anchor_up).clamp(-1.0, 1.0).asin();
1017    (pitch + pitch_d).clamp(-limit, limit) - pitch
1018}
1019
1020/// Signed world axis with the maximum dot product against `v`.
1021///
1022/// Iterates [`AXES`] in canonical order keeping the max with strict `>`, so
1023/// ties break deterministically toward the first axis in the order
1024/// `[X, NEG_X, Y, NEG_Y, Z, NEG_Z]`. Used to initialize
1025/// [`Player::anchor_up`] at spawn.
1026pub(crate) fn nearest_world_axis(v: Vec3) -> Vec3 {
1027    let mut best = AXES[0];
1028    let mut best_dot = v.dot(AXES[0]);
1029    for axis in AXES.into_iter().skip(1) {
1030        let d = v.dot(axis);
1031        if d > best_dot {
1032            best = axis;
1033            best_dot = d;
1034        }
1035    }
1036    best
1037}
1038
1039pub(crate) fn advance_snap(anim: &mut SnapRollAnim, dt: f32) -> (f32, bool) {
1040    anim.elapsed += dt;
1041    let t = (anim.elapsed / anim.duration).clamp(0.0, 1.0);
1042    let eased = apply_easing(t, anim.easing);
1043    let total = anim.start_angle + (anim.target_angle - anim.start_angle) * eased;
1044    let delta = total - anim.current_applied;
1045    anim.current_applied = total;
1046    let finished = anim.elapsed >= anim.duration;
1047    if finished {
1048        // Snap exactly to target to avoid FP residue
1049        let correction = anim.target_angle - anim.current_applied;
1050        anim.current_applied = anim.target_angle;
1051        return (delta + correction, true);
1052    }
1053    (delta, false)
1054}
1055
1056/// Updates the player orientation from mouse movement and Q/E roll keys.
1057///
1058/// Implements **true 6DOF rotation** with no pitch clamp. Each axis rotates
1059/// around the entity's *local* frame:
1060///
1061/// - Mouse X → `rotate_local_y` (yaw relative to current up)
1062/// - Mouse Y → `rotate_local_x` (pitch relative to current right)
1063/// - Q / E   → `rotate_local_z` (roll at [`Player::roll_speed`] rad/s)
1064///
1065/// Rotating in local space means all three axes compose correctly regardless
1066/// of the accumulated orientation — the player can pitch past vertical, roll
1067/// upside-down, and continue steering intuitively without gimbal lock.
1068///
1069/// All [`MouseMotion`] events for the frame are accumulated into a single
1070/// delta before applying rotation, preventing inter-frame jitter at high
1071/// polling rates.
1072pub fn player_look(
1073    mut query: Query<(&mut Player, &mut Transform)>,
1074    mut mouse_motion: MessageReader<MouseMotion>,
1075    keys: Res<ButtonInput<KeyCode>>,
1076    time: Res<Time>,
1077    windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>,
1078) {
1079    if !player_input_active(windows) {
1080        mouse_motion.clear();
1081        return;
1082    }
1083    let Ok((mut player, mut transform)) = query.single_mut() else {
1084        return;
1085    };
1086
1087    // Accumulate mouse delta for this frame.
1088    let mut delta = Vec2::ZERO;
1089    for event in mouse_motion.read() {
1090        delta += event.delta;
1091    }
1092
1093    match &player.mode {
1094        PlayerMode::FreeFlightSixDof { roll_mode } => {
1095            if delta != Vec2::ZERO {
1096                let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
1097                let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
1098                // Rotate around LOCAL axes — preserves 6DOF orientation.
1099                transform.rotate_local_y(yaw_d);
1100                transform.rotate_local_x(pitch_d);
1101            }
1102
1103            // Q / E roll.
1104            match roll_mode {
1105                RollMode::Continuous => {
1106                    let mut roll = 0.0_f32;
1107                    if keys.pressed(KeyCode::KeyQ) {
1108                        roll += 1.0;
1109                    }
1110                    if keys.pressed(KeyCode::KeyE) {
1111                        roll -= 1.0;
1112                    }
1113                    if roll != 0.0 {
1114                        transform.rotate_local_z(roll * player.roll_speed * time.delta_secs());
1115                    }
1116                }
1117                RollMode::Snap => {
1118                    if keys.just_pressed(KeyCode::KeyQ) {
1119                        player.snap_anim = Some(start_or_retarget_snap(
1120                            player.snap_anim,
1121                            *transform.local_z(),
1122                            *transform.up(),
1123                            1,
1124                            player.snap_roll_duration,
1125                            player.snap_roll_easing,
1126                        ));
1127                    }
1128                    if keys.just_pressed(KeyCode::KeyE) {
1129                        player.snap_anim = Some(start_or_retarget_snap(
1130                            player.snap_anim,
1131                            *transform.local_z(),
1132                            *transform.up(),
1133                            -1,
1134                            player.snap_roll_duration,
1135                            player.snap_roll_easing,
1136                        ));
1137                    }
1138                    if let Some(ref mut anim) = player.snap_anim {
1139                        let (delta, finished) = advance_snap(anim, time.delta_secs());
1140                        transform.rotate_local_z(delta);
1141                        if finished {
1142                            player.snap_anim = None;
1143                        }
1144                    }
1145                }
1146            }
1147        }
1148        PlayerMode::FreeFlightAnchored => {
1149            if delta != Vec2::ZERO {
1150                let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
1151                let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
1152                // Yaw: WORLD-space rotation around the anchor axis. While a
1153                // switch animation runs this is still the OLD anchor —
1154                // pending_anchor is only committed on finish.
1155                transform.rotate(Quat::from_axis_angle(player.anchor_up, yaw_d));
1156                // Pitch: local-X rotation, clamped so the elevation against
1157                // the anchor stays within ±89°.
1158                let clamped = clamp_pitch_delta(*transform.forward(), player.anchor_up, pitch_d);
1159                transform.rotate_local_x(clamped);
1160            }
1161
1162            // Q / E: switch the anchor to the next lattice candidate
1163            // (RollMode is ignored in Anchored look).
1164            if keys.just_pressed(KeyCode::KeyQ) {
1165                let local_z = *transform.local_z();
1166                let up = *transform.up();
1167                let ref_up = snap_reference_up(player.snap_anim, local_z, up, 1);
1168                let (_, axis) =
1169                    next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
1170                player.pending_anchor = Some(axis);
1171                player.snap_anim = Some(start_or_retarget_snap(
1172                    player.snap_anim,
1173                    local_z,
1174                    up,
1175                    1,
1176                    player.snap_roll_duration,
1177                    player.snap_roll_easing,
1178                ));
1179            }
1180            if keys.just_pressed(KeyCode::KeyE) {
1181                let local_z = *transform.local_z();
1182                let up = *transform.up();
1183                let ref_up = snap_reference_up(player.snap_anim, local_z, up, -1);
1184                let (_, axis) =
1185                    next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), -1);
1186                player.pending_anchor = Some(axis);
1187                player.snap_anim = Some(start_or_retarget_snap(
1188                    player.snap_anim,
1189                    local_z,
1190                    up,
1191                    -1,
1192                    player.snap_roll_duration,
1193                    player.snap_roll_easing,
1194                ));
1195            }
1196            if let Some(ref mut anim) = player.snap_anim {
1197                let (delta, finished) = advance_snap(anim, time.delta_secs());
1198                transform.rotate_local_z(delta);
1199                if finished {
1200                    // Commit the pure signed world axis, then renormalize
1201                    // the frame: look_to preserves forward and snaps
1202                    // screen-up onto the new anchor's projection, absorbing
1203                    // any roll accumulated vs. the new axis mid-animation.
1204                    if let Some(anchor) = player.pending_anchor.take() {
1205                        player.anchor_up = anchor;
1206                    }
1207                    let fwd = *transform.forward();
1208                    transform.look_to(fwd, player.anchor_up);
1209                    player.snap_anim = None;
1210                }
1211            }
1212        }
1213        PlayerMode::Grounded { .. } => {
1214            if delta != Vec2::ZERO {
1215                let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
1216                let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
1217
1218                // Yaw: rotate around WORLD Y so the player stays upright.
1219                transform.rotate_y(yaw_d);
1220
1221                // Pitch: decompose current rotation, apply clamped pitch.
1222                let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
1223                let new_pitch = (pitch + pitch_d).clamp(-89_f32.to_radians(), 89_f32.to_radians());
1224                transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, new_pitch, 0.0);
1225            }
1226            // No roll in grounded mode.
1227        }
1228    }
1229}
1230
1231/// Translates the player based on keyboard input and updates [`ViewerPosition`].
1232///
1233/// Movement axes are derived from the current entity rotation, so all six
1234/// directions (forward, back, left, right, up, down) are always relative to
1235/// wherever the player is currently looking — including after roll and pitch.
1236///
1237/// **Velocity smoothing** uses exponential lerp clamped to `[0, 1]`:
1238///
1239/// ```text
1240/// factor = if moving { acceleration } else { deceleration }  // PlayerMovementConfig
1241/// velocity = lerp(velocity, target, (factor * dt).min(1.0))
1242/// ```
1243///
1244/// This is frame-rate-independent for reasonable frame times and produces a
1245/// snappy start with a natural coast-to-stop deceleration.
1246///
1247/// With [`PlayerMovementConfig::wait_for_chunks`] the translation of a frame
1248/// is dropped when it would put the player where a chunk is not loaded yet.
1249///
1250/// After translating the entity, the system writes the new world position to
1251/// [`ViewerPosition`] so the chunk streaming system can load/unload chunks
1252/// around the player without querying the player transform directly.
1253pub fn player_move<V: VoxelType>(
1254    mut query: Query<(&mut Player, &mut Transform)>,
1255    keys: Res<ButtonInput<KeyCode>>,
1256    time: Res<Time>,
1257    mut viewer: ResMut<ViewerPosition>,
1258    manager: Res<ChunkManager>,
1259    chunks: Query<&Chunk<V>>,
1260    mut crouch_res: ResMut<PlayerCrouching>,
1261    applied: Option<Res<effects::AppliedEffectModifiers>>,
1262    windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>,
1263    movement: Option<Res<PlayerMovementConfig>>,
1264) {
1265    let Ok((mut player, mut transform)) = query.single_mut() else {
1266        return;
1267    };
1268
1269    if !player_input_active(windows) {
1270        player.velocity = Vec3::ZERO;
1271        return;
1272    }
1273    let dt = time.delta_secs();
1274    let accel = PlayerMovementConfig::acceleration_rate(movement.as_deref());
1275    let decel = PlayerMovementConfig::deceleration_rate(movement.as_deref());
1276    let wait_for_chunks = movement.as_deref().is_some_and(|m| m.wait_for_chunks);
1277    let start = transform.translation;
1278
1279    match player.mode.clone() {
1280        PlayerMode::FreeFlightSixDof { .. } | PlayerMode::FreeFlightAnchored => {
1281            // Sprint/crouch are not applicable in FreeFlight.
1282            player.sprinting = false;
1283            player.crouching = false;
1284            crouch_res.0 = false;
1285
1286            // Local-space axes — full 6DOF.
1287            let forward = transform.rotation * Vec3::NEG_Z;
1288            let right = transform.rotation * Vec3::X;
1289            let up = transform.rotation * Vec3::Y;
1290
1291            let mut direction = Vec3::ZERO;
1292            if keys.pressed(KeyCode::KeyW) {
1293                direction += forward;
1294            }
1295            if keys.pressed(KeyCode::KeyS) {
1296                direction -= forward;
1297            }
1298            if keys.pressed(KeyCode::KeyA) {
1299                direction -= right;
1300            }
1301            if keys.pressed(KeyCode::KeyD) {
1302                direction += right;
1303            }
1304            if keys.pressed(KeyCode::Space) {
1305                direction += up;
1306            }
1307            if keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight) {
1308                direction -= up;
1309            }
1310
1311            let target = if direction != Vec3::ZERO {
1312                direction.normalize() * player.speed
1313            } else {
1314                Vec3::ZERO
1315            };
1316
1317            let factor = if direction != Vec3::ZERO {
1318                accel
1319            } else {
1320                decel
1321            };
1322            player.velocity = player.velocity.lerp(target, (factor * dt).min(1.0));
1323            transform.translation += player.velocity * dt;
1324        }
1325        PlayerMode::Grounded {
1326            gravity,
1327            jump_speed,
1328        } => {
1329            // Horizontal movement on XZ using yaw-only orientation.
1330            let yaw = transform.rotation.to_euler(EulerRot::YXZ).0;
1331            let forward = Vec3::new(-yaw.sin(), 0.0, -yaw.cos());
1332            let right = Vec3::new(yaw.cos(), 0.0, -yaw.sin());
1333
1334            let mut h_dir = Vec3::ZERO;
1335            if keys.pressed(KeyCode::KeyW) {
1336                h_dir += forward;
1337            }
1338            if keys.pressed(KeyCode::KeyS) {
1339                h_dir -= forward;
1340            }
1341            if keys.pressed(KeyCode::KeyA) {
1342                h_dir -= right;
1343            }
1344            if keys.pressed(KeyCode::KeyD) {
1345                h_dir += right;
1346            }
1347
1348            // Sprint (Shift) and crouch (Ctrl) speed multipliers.
1349            // Crouch takes priority over sprint if both are held.
1350            // Sprint only activates when on solid ground (no air-sprinting).
1351            let crouching =
1352                keys.pressed(KeyCode::ControlLeft) || keys.pressed(KeyCode::ControlRight);
1353            let sprinting = !crouching
1354                && player.on_ground
1355                && (keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight));
1356            player.crouching = crouching;
1357            player.sprinting = sprinting;
1358            crouch_res.0 = crouching;
1359            let speed_mult = if crouching {
1360                0.5
1361            } else if sprinting {
1362                SPRINT_MULTIPLIER
1363            } else {
1364                1.0
1365            };
1366
1367            // Sample the block under the player's feet to get movement modifiers.
1368            let foot_pos = transform.translation - Vec3::Y * (PLAYER_HALF_HEIGHT + 0.3);
1369            let modifier = get_voxel_at::<V>(foot_pos, &manager, &chunks)
1370                .map(|v| v.movement_modifier())
1371                .unwrap_or_default();
1372
1373            let effect_speed = applied.as_deref().map(|a| a.0.speed_mult).unwrap_or(1.0);
1374            let h_target = if h_dir != Vec3::ZERO {
1375                h_dir.normalize() * player.speed * speed_mult * modifier.speed_mult * effect_speed
1376            } else {
1377                Vec3::ZERO
1378            };
1379
1380            let effective_decel = decel * modifier.friction_mult;
1381            let factor = if h_dir != Vec3::ZERO {
1382                accel
1383            } else {
1384                effective_decel
1385            };
1386            player.velocity = player.velocity.lerp(h_target, (factor * dt).min(1.0));
1387
1388            // Freeze gravity until the initial chunk load completes so the
1389            // player does not fall through un-loaded terrain on startup.
1390            if !player.world_loaded {
1391                player.vertical_velocity = 0.0;
1392                transform.translation += player.velocity * dt;
1393                if wait_for_chunks && !player_chunks_loaded(transform.translation, &manager) {
1394                    transform.translation = start;
1395                }
1396                viewer.position = transform.translation;
1397                return;
1398            }
1399
1400            // Jump impulse (only when on the ground; disabled while crouching).
1401            if keys.just_pressed(KeyCode::Space) && player.on_ground && !crouching {
1402                let effect_jump = applied.as_deref().map(|a| a.0.jump_mult).unwrap_or(1.0);
1403                player.vertical_velocity = jump_speed * modifier.jump_mult * effect_jump;
1404            }
1405
1406            // Apply gravity.
1407            player.vertical_velocity -= gravity * modifier.gravity_mult * dt;
1408
1409            // Water buoyancy: if the player's center voxel is transparent (e.g.
1410            // water), apply a gentle upward push each frame to make them float
1411            // toward the surface. The movement_modifier already reduces gravity
1412            // via gravity_mult; buoyancy adds a positive upward impulse.
1413            let center_voxel = get_voxel_at::<V>(transform.translation, &manager, &chunks);
1414            if center_voxel.map(|v| v.alpha() < 1.0).unwrap_or(false) {
1415                player.vertical_velocity += jump_speed * 0.3 * dt;
1416            }
1417
1418            // Translate: horizontal from smoothed velocity + vertical from gravity.
1419            transform.translation += player.velocity * dt;
1420            transform.translation.y += player.vertical_velocity * dt;
1421        }
1422    }
1423
1424    // Missing chunks are unknown, not empty: stay in place until they load.
1425    // The viewer stays on the player, which is what requests them.
1426    if wait_for_chunks && !player_chunks_loaded(transform.translation, &manager) {
1427        transform.translation = start;
1428        // Gravity must not pile up into one big fall while waiting.
1429        player.vertical_velocity = 0.0;
1430    }
1431
1432    // Keep the streaming origin at the player position.
1433    viewer.position = transform.translation;
1434}
1435
1436/// Resolves capsule-vs-voxel AABB collisions and repositions the player.
1437///
1438/// The collision shape is a capsule whose spine runs along the player's **local
1439/// Y axis** between `±PLAYER_HALF_HEIGHT`. Because the spine follows the
1440/// entity rotation, roll and pitch do not break collision detection — the
1441/// capsule tilts with the player.
1442///
1443/// **Algorithm (per chunk, per solid voxel in the AABB):**
1444///
1445/// 1. Compute the axis-aligned bounding box of the capsule in chunk-local space.
1446/// 2. Clamp the AABB to the chunk bounds to skip out-of-range voxels.
1447/// 3. For each solid voxel in the range, call `push_capsule_out` which:
1448///    a. Finds the closest point on the capsule spine to the voxel AABB center.
1449///    b. Treats that point as a sphere center of radius [`PLAYER_RADIUS`].
1450///    c. Computes the minimum separation vector from the sphere to the voxel AABB.
1451///    d. Accumulates the push into the running position.
1452///
1453/// The final corrected position is written back to the player transform. This
1454/// system should always run **after** [`player_move`] in the same frame.
1455///
1456/// When the player arrives at a surface faster than
1457/// [`PlayerMovementConfig::impact_speed_threshold`], one [`PlayerImpact`] is
1458/// written (if the message is registered). The player's velocity is not
1459/// changed by the collision.
1460pub fn player_resolve_collision<V: VoxelType>(
1461    mut player_q: Query<(&mut Player, &mut Transform)>,
1462    chunk_q: Query<(&Chunk<V>, &Transform), Without<Player>>,
1463    manager: Res<ChunkManager>,
1464    movement: Option<Res<PlayerMovementConfig>>,
1465    impacts: Option<ResMut<Messages<PlayerImpact>>>,
1466    mut was_impacting: Local<bool>,
1467) {
1468    let Ok((mut player, mut player_tf)) = player_q.single_mut() else {
1469        return;
1470    };
1471
1472    // Grounded mode tracks whether the player is standing on solid ground.
1473    let is_grounded = matches!(player.mode, PlayerMode::Grounded { .. });
1474    // Velocity the player arrives with, before landing zeroes the vertical part.
1475    let incoming_velocity = if is_grounded {
1476        player.velocity + Vec3::Y * player.vertical_velocity
1477    } else {
1478        player.velocity
1479    };
1480    let start_pos = player_tf.translation;
1481    if is_grounded {
1482        player.on_ground = false;
1483        player.impact_speed = 0.0; // reset each frame; set below on landing
1484    }
1485
1486    // Use reduced capsule height when crouching so the player fits through
1487    // 1-block-tall gaps. In FreeFlight mode crouching is always false.
1488    let half_height = if player.crouching {
1489        CROUCH_HALF_HEIGHT
1490    } else {
1491        PLAYER_HALF_HEIGHT
1492    };
1493
1494    // Enable gravity only once the chunk containing the player's feet is
1495    // registered in ChunkManager — meaning the generator has actually produced
1496    // terrain data for that chunk.  Checking a distant chunk being present
1497    // (chunk_q.is_empty) is not sufficient: it fires too early.
1498    if !player.world_loaded {
1499        let feet = player_tf.translation - Vec3::Y * half_height;
1500        let coord = crate::chunk::world_to_chunk_coord(feet);
1501        if manager.is_loaded(coord) {
1502            player.world_loaded = true;
1503        }
1504    }
1505
1506    let mut pos = player_tf.translation;
1507    // FreeFlight: capsule spine follows entity rotation (true 6DOF).
1508    // Grounded: spine is always world-vertical (Vec3::Y) so the capsule stands upright.
1509    let up = if is_grounded {
1510        Vec3::Y
1511    } else {
1512        player_tf.rotation * Vec3::Y
1513    };
1514
1515    let extent = half_height + PLAYER_RADIUS;
1516    let voxel_size = VOXEL_SIZE;
1517
1518    for (chunk, chunk_tf) in &chunk_q {
1519        let chunk_pos = chunk_tf.translation;
1520        let local = pos - chunk_pos;
1521
1522        // AABB of voxels that could possibly overlap the capsule.
1523        let min_vox = IVec3::new(
1524            ((local.x - extent) / voxel_size).floor() as i32,
1525            ((local.y - extent) / voxel_size).floor() as i32,
1526            ((local.z - extent) / voxel_size).floor() as i32,
1527        );
1528        let max_vox = IVec3::new(
1529            ((local.x + extent) / voxel_size).ceil() as i32,
1530            ((local.y + extent) / voxel_size).ceil() as i32,
1531            ((local.z + extent) / voxel_size).ceil() as i32,
1532        );
1533
1534        // Clamp to chunk bounds for the loop — is_solid_at returns false for
1535        // out-of-range coords, but skipping them avoids pointless iterations.
1536        let lo = min_vox.max(IVec3::ZERO);
1537        let hi = max_vox.min(IVec3::splat(CHUNK_SIZE as i32 - 1));
1538
1539        for vx in lo.x..=hi.x {
1540            for vy in lo.y..=hi.y {
1541                for vz in lo.z..=hi.z {
1542                    if !chunk.is_solid_at(vx as usize, vy as usize, vz as usize) {
1543                        continue;
1544                    }
1545                    let new_pos = push_capsule_out(pos, up, half_height, chunk_pos, vx, vy, vz);
1546
1547                    // In grounded mode detect landing: a positive Y correction
1548                    // means the player was pushed upward off a solid surface.
1549                    if is_grounded && new_pos.y > pos.y + 0.001 {
1550                        if !player.on_ground {
1551                            // First contact this frame — record impact speed for fall damage.
1552                            player.impact_speed = player.vertical_velocity.abs();
1553                        }
1554                        player.on_ground = true;
1555                        player.vertical_velocity = 0.0;
1556                    }
1557
1558                    pos = new_pos;
1559                }
1560            }
1561        }
1562    }
1563
1564    player_tf.translation = pos;
1565
1566    // Report an impact when the speed into the surface rises above the
1567    // threshold. The total push-out gives the surface normal.
1568    let push = pos - start_pos;
1569    let speed_into_surface = push
1570        .try_normalize()
1571        .map(|normal| (normal, (-incoming_velocity.dot(normal)).max(0.0)));
1572    let threshold = PlayerMovementConfig::impact_threshold(movement.as_deref());
1573    let is_impacting = speed_into_surface.is_some_and(|(_, speed)| speed > threshold);
1574    if is_impacting
1575        && !*was_impacting
1576        && let Some((normal, speed)) = speed_into_surface
1577        && let Some(mut impacts) = impacts
1578    {
1579        impacts.write(PlayerImpact {
1580            position: pos,
1581            normal,
1582            speed,
1583        });
1584    }
1585    *was_impacting = is_impacting;
1586}
1587
1588// ─── Cursor grab ──────────────────────────────────────────────────────────────
1589
1590/// Manages the primary window's cursor capture.
1591///
1592/// | Trigger | Cursor state before | Effect |
1593/// |---------|---------------------|--------|
1594/// | Window loses focus | Locked | Releases cursor, shows it |
1595/// | Left click in the focused window | Free (`None`) | Locks cursor, hides it |
1596/// | Escape | Locked | Releases cursor, shows it |
1597/// | Escape | Free | Despawns the window entity (closes the app) |
1598///
1599/// ## With the pause menu
1600///
1601/// When [`PauseMenuPlugin`](crate::ui::PauseMenuPlugin) is installed (its
1602/// [`PauseMenuState`](crate::ui::PauseMenuState) exists) the pause menu owns
1603/// Escape: this system ignores the key, so Escape opens the menu instead of
1604/// releasing the cursor or closing the window. Click-to-capture and
1605/// focus-loss release keep working while the state is `Playing`, and clicks
1606/// are ignored while a menu is open, so menu buttons never capture the cursor.
1607/// The two can be used together; [`PlayerPlugin`] does exactly that.
1608pub fn player_cursor_system(
1609    mut commands: Commands,
1610    mouse: Res<ButtonInput<MouseButton>>,
1611    keys: Res<ButtonInput<KeyCode>>,
1612    mut windows: Query<(Entity, &Window, &mut CursorOptions), With<PrimaryWindow>>,
1613    pause: Option<Res<State<crate::ui::PauseMenuState>>>,
1614) {
1615    use crate::ui::PauseMenuState;
1616
1617    let pause_menu_installed = pause.is_some();
1618    let menu_open = pause.is_some_and(|state| !matches!(state.get(), PauseMenuState::Playing));
1619
1620    for (entity, window, mut cursor) in windows.iter_mut() {
1621        if !window.focused {
1622            if cursor.grab_mode != CursorGrabMode::None || !cursor.visible {
1623                cursor.grab_mode = CursorGrabMode::None;
1624                cursor.visible = true;
1625            }
1626            continue;
1627        }
1628        if menu_open {
1629            // The pause menu shows a free cursor; its clicks are for buttons.
1630            continue;
1631        }
1632        if mouse.just_pressed(MouseButton::Left)
1633            && cursor.grab_mode == bevy::window::CursorGrabMode::None
1634        {
1635            cursor.grab_mode = bevy::window::CursorGrabMode::Locked;
1636            cursor.visible = false;
1637        }
1638
1639        // With the pause menu installed, Escape opens the menu instead.
1640        if !pause_menu_installed && keys.just_pressed(KeyCode::Escape) {
1641            if cursor.grab_mode != bevy::window::CursorGrabMode::None {
1642                cursor.grab_mode = bevy::window::CursorGrabMode::None;
1643                cursor.visible = true;
1644            } else {
1645                commands.entity(entity).despawn();
1646            }
1647        }
1648    }
1649}
1650
1651/// Whether the primary window owns player input (focused and cursor captured).
1652/// No primary window preserves synthetic input for headless simulations.
1653///
1654/// Useful as a run condition for other gameplay input systems. Keep
1655/// [`player_look`] scheduled: it discards inactive mouse deltas itself.
1656/// This checks Bevy's current window state, not OS activation or grab success.
1657pub fn player_input_active(windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>) -> bool {
1658    match windows.single() {
1659        Ok((window, cursor)) => window.focused && cursor.grab_mode != CursorGrabMode::None,
1660        Err(_) => windows.is_empty(),
1661    }
1662}
1663
1664/// Applies fall damage when the player lands after a significant drop.
1665///
1666/// Reads `Player::impact_speed` set by [`player_resolve_collision`] and
1667/// computes damage as `(impact_speed - fall_safe_speed).max(0) * 2.0`. When
1668/// health reaches zero the player is teleported to [`PlayerHealth::spawn_position`]
1669/// and a [`PlayerDied`] message is sent.
1670///
1671/// Run this system **after** [`player_resolve_collision`].
1672pub fn player_fall_damage(
1673    mut player_q: Query<(&mut Player, &mut Transform)>,
1674    mut health: ResMut<PlayerHealth>,
1675    mut damaged_writer: MessageWriter<PlayerDamaged>,
1676    mut died_writer: MessageWriter<PlayerDied>,
1677) {
1678    let Ok((mut player, mut transform)) = player_q.single_mut() else {
1679        return;
1680    };
1681
1682    if player.impact_speed <= 0.0 {
1683        return;
1684    }
1685
1686    // First landing after spawn or respawn is immune to fall damage so the
1687    // player doesn't die just because the spawn point is a few blocks above
1688    // the terrain surface.
1689    if player.spawn_immune {
1690        player.spawn_immune = false;
1691        player.impact_speed = 0.0;
1692        return;
1693    }
1694
1695    let damage = (player.impact_speed - health.fall_safe_speed).max(0.0) * 2.0;
1696    player.impact_speed = 0.0;
1697
1698    if damage <= 0.0 {
1699        return;
1700    }
1701
1702    health.health = (health.health - damage).max(0.0);
1703    damaged_writer.write(PlayerDamaged { amount: damage });
1704
1705    if health.health <= 0.0 {
1706        health.health = health.max_health;
1707        transform.translation = health.spawn_position;
1708        // Reset velocity so the player doesn't inherit falling momentum after respawn.
1709        player.vertical_velocity = 0.0;
1710        player.velocity = Vec3::ZERO;
1711        player.world_loaded = false; // re-freeze gravity until feet chunk reloads
1712        player.spawn_immune = true; // grant immunity on the next landing too
1713        died_writer.write(PlayerDied);
1714    }
1715}
1716
1717/// Processes incoming damage messages and runs the death / respawn check.
1718///
1719/// Regen and poison are handled exclusively by
1720/// [`apply_health_effects`](crate::player::effects::apply_health_effects)
1721/// inside [`StatusEffectsPlugin`](crate::player::effects::StatusEffectsPlugin).
1722/// This system only reads [`AppliedEffectModifiers`](crate::player::effects::AppliedEffectModifiers) to apply damage resistance
1723/// to incoming [`PlayerDamaged`] events. `AppliedEffectModifiers` is optional —
1724/// the system degrades gracefully when no `StatusEffectsPlugin` is registered.
1725///
1726/// Run this system **every frame**, regardless of pause state.
1727pub fn health_system(
1728    applied: Option<Res<effects::AppliedEffectModifiers>>,
1729    mut health: ResMut<PlayerHealth>,
1730    mut damaged_reader: bevy::ecs::message::MessageReader<PlayerDamaged>,
1731    mut died_writer: MessageWriter<PlayerDied>,
1732) {
1733    // Process every pending damage event, reduced by damage resistance.
1734    for event in damaged_reader.read() {
1735        let resistance = applied
1736            .as_ref()
1737            .map(|a| a.0.damage_resistance)
1738            .unwrap_or(0.0);
1739        let actual = event.amount * (1.0 - resistance.clamp(0.0, 1.0));
1740        health.health = (health.health - actual).max(0.0);
1741    }
1742
1743    // Death check — instant respawn (position is handled by respawn_system).
1744    if health.health <= 0.0 {
1745        health.health = health.max_health;
1746        died_writer.write(PlayerDied);
1747    }
1748}
1749
1750/// Teleports the streaming origin to the spawn position on player death.
1751///
1752/// Listens for [`PlayerDied`] messages and updates [`ViewerPosition`] so the
1753/// chunk streaming system starts loading terrain around the respawn location
1754/// immediately. Physical entity teleportation is handled by
1755/// [`player_fall_damage`].
1756///
1757/// If no [`PlayerConfig`] resource is present, the player is teleported to
1758/// [`Vec3::ZERO`].
1759pub fn respawn_system(
1760    mut died_reader: bevy::ecs::message::MessageReader<PlayerDied>,
1761    mut viewer: ResMut<ViewerPosition>,
1762    config: Option<Res<PlayerConfig>>,
1763) {
1764    for _ in died_reader.read() {
1765        let spawn = config
1766            .as_ref()
1767            .map(|c| c.spawn_position)
1768            .unwrap_or(Vec3::ZERO);
1769        viewer.position = spawn;
1770    }
1771}
1772
1773// ─── Push helper ─────────────────────────────────────────────────────────────
1774
1775/// Returns the corrected capsule-center position after pushing out of a solid voxel.
1776///
1777/// The algorithm treats the capsule as a swept sphere along the spine segment
1778/// `[pos − up*half_height, pos + up*half_height]`:
1779///
1780/// 1. Find the point on the spine segment closest to the voxel AABB center
1781///    (clamped parametric projection, `t ∈ [0, 1]`).
1782/// 2. Treat that spine point as a sphere center `sphere_c` with radius
1783///    [`PLAYER_RADIUS`].
1784/// 3. Find the point on the voxel AABB closest to `sphere_c`.
1785/// 4. If the sphere overlaps the AABB (distance² < `PLAYER_RADIUS²`), compute
1786///    the minimum translation vector and apply it to `pos`.
1787///
1788/// A degenerate case (sphere center exactly inside the voxel) is handled by
1789/// pushing along the dominant axis of the relative offset to avoid a zero-
1790/// length normal.
1791fn push_capsule_out(
1792    pos: Vec3,
1793    up: Vec3,
1794    half_height: f32,
1795    chunk_pos: Vec3,
1796    vx: i32,
1797    vy: i32,
1798    vz: i32,
1799) -> Vec3 {
1800    let vmin = chunk_pos + Vec3::new(vx as f32, vy as f32, vz as f32) * VOXEL_SIZE;
1801    let vmax = vmin + Vec3::splat(VOXEL_SIZE);
1802
1803    // Capsule spine endpoints.
1804    let p0 = pos - up * half_height;
1805    let p1 = pos + up * half_height;
1806    let spine = p1 - p0;
1807
1808    // Closest point on spine to the voxel center.
1809    let vox_center = (vmin + vmax) * 0.5;
1810    let len_sq = spine.length_squared();
1811    let sphere_c = if len_sq > f32::EPSILON {
1812        let t = ((vox_center - p0).dot(spine) / len_sq).clamp(0.0, 1.0);
1813        p0 + spine * t
1814    } else {
1815        pos
1816    };
1817
1818    // Sphere-AABB collision.
1819    let closest = sphere_c.clamp(vmin, vmax);
1820    let diff = sphere_c - closest;
1821    let dist_sq = diff.length_squared();
1822
1823    if dist_sq >= PLAYER_RADIUS * PLAYER_RADIUS {
1824        return pos;
1825    }
1826
1827    let delta = if dist_sq > f32::EPSILON {
1828        let dist = dist_sq.sqrt();
1829        (diff / dist) * (PLAYER_RADIUS - dist)
1830    } else {
1831        // Degenerate: center exactly inside voxel — push along dominant axis.
1832        let rel = sphere_c - vox_center;
1833        let abs_rel = rel.abs();
1834        let half = VOXEL_SIZE * 0.5 + PLAYER_RADIUS;
1835        if abs_rel.x >= abs_rel.y && abs_rel.x >= abs_rel.z {
1836            Vec3::new(half * rel.x.signum() - rel.x, 0.0, 0.0)
1837        } else if abs_rel.y >= abs_rel.z {
1838            Vec3::new(0.0, half * rel.y.signum() - rel.y, 0.0)
1839        } else {
1840            Vec3::new(0.0, 0.0, half * rel.z.signum() - rel.z)
1841        }
1842    };
1843
1844    pos + delta
1845}
1846
1847/// Emits [`SfxRequest`] footstep sounds when the player walks on solid ground.
1848///
1849/// Samples the voxel directly below the player's feet and passes its byte
1850/// representation as [`SfxEvent::Footstep`] so games can map surface types to
1851/// different audio assets. The step interval scales with horizontal speed.
1852pub fn player_footstep_system<V: VoxelType>(
1853    mut query: Query<(&mut Player, &Transform)>,
1854    time: Res<Time>,
1855    manager: Res<ChunkManager>,
1856    chunks: Query<&Chunk<V>>,
1857    mut sfx: MessageWriter<SfxRequest>,
1858) {
1859    let Ok((mut player, transform)) = query.single_mut() else {
1860        return;
1861    };
1862
1863    if !matches!(player.mode, PlayerMode::Grounded { .. }) || !player.on_ground {
1864        return;
1865    }
1866
1867    let h_speed = Vec3::new(player.velocity.x, 0.0, player.velocity.z).length();
1868    if h_speed < 0.5 {
1869        player.footstep_timer = 0.0;
1870        return;
1871    }
1872
1873    // Step interval: shorter at higher speeds (clamped between 0.2–0.5s).
1874    let step_interval = (0.5 / h_speed).clamp(0.2, 0.5);
1875    player.footstep_timer += time.delta_secs();
1876
1877    if player.footstep_timer < step_interval {
1878        return;
1879    }
1880    player.footstep_timer = 0.0;
1881
1882    // Sample voxel just below the player's feet.
1883    let foot_pos = transform.translation - Vec3::Y * (PLAYER_HALF_HEIGHT + 0.3);
1884    let voxel_byte = get_voxel_at::<V>(foot_pos, &manager, &chunks)
1885        .map(|v| v.to_byte())
1886        .unwrap_or(0);
1887
1888    sfx.write(SfxRequest {
1889        event: SfxEvent::Footstep(voxel_byte),
1890        position: None,
1891    });
1892}
1893
1894// ─── Spawn persistence ────────────────────────────────────────────────────────
1895
1896/// Startup system that applies a persisted spawn position to [`PlayerConfig`]
1897/// and [`PlayerHealth`] before the player entity is spawned.
1898///
1899/// Reads the world data directory from [`WorldDataDir`] (set by
1900/// [`PlayerPlugin::with_world`]).  Silent no-op if `player_data.json` does not
1901/// exist.
1902fn load_spawn_on_startup(
1903    mut config: ResMut<PlayerConfig>,
1904    mut health: ResMut<PlayerHealth>,
1905    world_data_dir: Res<WorldDataDir>,
1906) {
1907    let data_dir = world_data_dir.as_str();
1908    if let Some(pos) = persistence::load_spawn_position(data_dir) {
1909        config.spawn_position = pos;
1910        health.spawn_position = pos;
1911    } else {
1912        // First run: persist the configured default so subsequent runs reload it.
1913        persistence::save_spawn_position(config.spawn_position, data_dir);
1914    }
1915}
1916
1917/// System that saves [`PlayerHealth::spawn_position`] to disk on [`AppExit`].
1918///
1919/// This preserves a custom spawn set at runtime (e.g. sleeping in a bed)
1920/// across sessions.  The [`PlayerConfig::spawn_position`] default is used as
1921/// fallback when no file exists.
1922fn save_spawn_on_exit(
1923    health: Res<PlayerHealth>,
1924    world_data_dir: Res<WorldDataDir>,
1925    mut exit_reader: bevy::ecs::message::MessageReader<AppExit>,
1926) {
1927    for _ in exit_reader.read() {
1928        persistence::save_spawn_position(health.spawn_position, world_data_dir.as_str());
1929    }
1930}
1931
1932// ─── Run condition ────────────────────────────────────────────────────────────
1933
1934/// Returns `true` when every chunk the player's capsule can touch at
1935/// `position` is loaded.
1936///
1937/// The volume is a cube around `position` with half side
1938/// [`PLAYER_HALF_HEIGHT`]` + `[`PLAYER_RADIUS`], which encloses the capsule in
1939/// any orientation. A chunk counts as loaded once it is registered in the
1940/// [`ChunkManager`], also when it is all air.
1941///
1942/// [`player_move`] uses it for [`PlayerMovementConfig::wait_for_chunks`]. A
1943/// game can call it for its own rules, for example to delay a teleport.
1944pub fn player_chunks_loaded(position: Vec3, manager: &ChunkManager) -> bool {
1945    let extent = Vec3::splat(PLAYER_HALF_HEIGHT + PLAYER_RADIUS);
1946    let min = world_to_chunk_coord(position - extent);
1947    let max = world_to_chunk_coord(position + extent);
1948    (min.x..=max.x).all(|x| {
1949        (min.y..=max.y).all(|y| (min.z..=max.z).all(|z| manager.is_loaded(IVec3::new(x, y, z))))
1950    })
1951}
1952
1953/// Copies the player's position to [`ViewerPosition`].
1954///
1955/// [`player_move`] writes the viewer position only on the frames where it
1956/// moves the player: not while the cursor is free and not while a menu is
1957/// open. This system covers every frame, so the world streams around the
1958/// player from the spawn on, and also after collision resolution or a game
1959/// system moved the player.
1960///
1961/// [`PlayerPlugin`] runs it in [`PlayerSystems`] after
1962/// [`player_resolve_collision`] and before the streaming system, without the
1963/// pause condition. It does nothing without exactly one [`Player`] or without
1964/// a [`ViewerPosition`] resource.
1965pub fn player_sync_viewer(
1966    player: Query<&Transform, With<Player>>,
1967    viewer: Option<ResMut<ViewerPosition>>,
1968) {
1969    let (Ok(transform), Some(mut viewer)) = (player.single(), viewer) else {
1970        return;
1971    };
1972    // Avoid marking the resource as changed on every frame.
1973    if viewer.position != transform.translation {
1974        viewer.position = transform.translation;
1975    }
1976}
1977
1978/// Returns `true` when gameplay should be active.
1979///
1980/// If [`crate::ui::PauseMenuState`] is registered, returns `true`
1981/// only while in the `Playing` variant. If the state is not present (i.e.
1982/// [`crate::ui::PauseMenuPlugin`] was not added), always returns `true` so the
1983/// player systems run unconditionally.
1984fn gameplay_active(state: Option<Res<bevy::prelude::State<crate::ui::PauseMenuState>>>) -> bool {
1985    use crate::ui::PauseMenuState;
1986    state.map_or(true, |s| matches!(s.get(), PauseMenuState::Playing))
1987}
1988
1989// ─── System set ───────────────────────────────────────────────────────────────
1990
1991/// System set containing every `Update` system that [`PlayerPlugin`] adds.
1992///
1993/// Use it to order the player against your own systems or to add a run
1994/// condition without registering the player systems by hand:
1995///
1996/// ```rust,no_run
1997/// use bevy::prelude::*;
1998/// use voxel_framework::prelude::*;
1999///
2000/// #[derive(States, Default, Clone, PartialEq, Eq, Hash, Debug)]
2001/// enum AppState { #[default] Menu, InGame }
2002///
2003/// App::new()
2004///     .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
2005///     .configure_sets(Update, PlayerSystems.run_if(in_state(AppState::InGame)));
2006/// ```
2007///
2008/// Conditions added here combine with the plugin's own pause gating.
2009#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
2010pub struct PlayerSystems;
2011
2012// ─── Plugin ───────────────────────────────────────────────────────────────────
2013
2014/// Plugin that wires up the complete 6DOF player controller.
2015///
2016/// Registers [`PlayerConfig`] as an init resource, spawns the player camera
2017/// on `Startup`, and chains the three frame-update systems in the correct
2018/// dependency order every `Update`:
2019///
2020/// ```text
2021/// player_look → player_move → player_resolve_collision<V>
2022/// ```
2023///
2024/// [`camera_response_restore`] runs before that chain and
2025/// [`camera_response_apply`] after it; both do nothing with the default
2026/// [`CameraResponseConfig`], which the plugin initializes.
2027///
2028/// [`player_cursor_system`] is added as a separate, un-chained `Update` system
2029/// so cursor events are processed independently of the movement pipeline.
2030///
2031/// ## Pause menu
2032///
2033/// The plugin works together with [`PauseMenuPlugin`](crate::ui::PauseMenuPlugin):
2034/// when that plugin is installed, look, movement and collision run only in
2035/// `PauseMenuState::Playing`, and Escape opens the menu. The cursor system,
2036/// health and respawn keep running while paused; the cursor system then only
2037/// releases the cursor on focus loss. Without the pause menu
2038/// everything runs every frame.
2039///
2040/// ## Extra conditions and ordering
2041///
2042/// All `Update` systems of the plugin are in [`PlayerSystems`]. Configure that
2043/// set to gate the player on your own state or to order it against your
2044/// systems. Registering the systems manually is still possible:
2045///
2046/// ```rust,no_run
2047/// # use bevy::prelude::*;
2048/// # use voxel_framework::player::{spawn_player, player_look, player_move,
2049/// #     player_resolve_collision};
2050/// # use voxel_framework::voxel::DefaultVoxel;
2051/// # #[derive(States, Default, Clone, PartialEq, Eq, Hash, Debug)]
2052/// # enum AppState { #[default] Playing }
2053/// App::new()
2054///     .add_systems(Startup, spawn_player)
2055///     .add_systems(Update,
2056///         (player_look, player_move::<DefaultVoxel>, player_resolve_collision::<DefaultVoxel>)
2057///             .chain()
2058///             .run_if(in_state(AppState::Playing)),
2059///     );
2060/// ```
2061///
2062/// The generic parameter `V` must match the [`VoxelType`] used by the loaded
2063/// [`Chunk`] entities so the collision system can read
2064/// solid-voxel data.
2065pub struct PlayerPlugin<V: VoxelType> {
2066    _marker: std::marker::PhantomData<V>,
2067    world_name: String,
2068}
2069
2070impl<V: VoxelType> PlayerPlugin<V> {
2071    /// Creates a `PlayerPlugin` using the default world name (`"world"`).
2072    pub fn new() -> Self {
2073        Self {
2074            _marker: std::marker::PhantomData,
2075            world_name: String::new(),
2076        }
2077    }
2078
2079    /// Creates a `PlayerPlugin` that stores player data under
2080    /// `./worlds/{world_name}/player_data.json`.
2081    pub fn with_world(world_name: impl Into<String>) -> Self {
2082        Self {
2083            _marker: std::marker::PhantomData,
2084            world_name: world_name.into(),
2085        }
2086    }
2087}
2088
2089impl<V: VoxelType> Default for PlayerPlugin<V> {
2090    fn default() -> Self {
2091        Self::new()
2092    }
2093}
2094
2095impl<V: VoxelType> Plugin for PlayerPlugin<V> {
2096    fn build(&self, app: &mut App) {
2097        let name = if self.world_name.is_empty() {
2098            "world"
2099        } else {
2100            &self.world_name
2101        };
2102        app.insert_resource(WorldDataDir::for_world(name));
2103        app.init_resource::<PlayerConfig>();
2104        app.init_resource::<PlayerHealth>();
2105        app.init_resource::<PlayerCrouching>();
2106        app.add_message::<PlayerDamaged>();
2107        app.add_message::<PlayerDied>();
2108        app.init_resource::<PlayerMovementConfig>();
2109        app.add_message::<PlayerImpact>();
2110        // `player_footstep_system` writes it. `SfxPlugin` registers it too,
2111        // but this plugin must also run in an app without audio.
2112        app.add_message::<SfxRequest>();
2113        app.init_resource::<CameraResponseConfig>();
2114        app.add_systems(Startup, (load_spawn_on_startup, spawn_player).chain());
2115        app.add_systems(
2116            Update,
2117            (
2118                camera_response_restore,
2119                player_look,
2120                player_move::<V>,
2121                player_resolve_collision::<V>,
2122                player_fall_damage,
2123                player_footstep_system::<V>,
2124            )
2125                .chain()
2126                .run_if(gameplay_active)
2127                .in_set(PlayerSystems),
2128        );
2129        // health_system and respawn_system are not gated by pause.
2130        app.add_systems(
2131            Update,
2132            (health_system, respawn_system).in_set(PlayerSystems),
2133        );
2134        app.add_systems(
2135            Update,
2136            // Not gated by pause: the system ignores clicks and Escape itself
2137            // while a menu is open, and must still release on focus loss.
2138            player_cursor_system
2139                .before(player_look)
2140                .in_set(PlayerSystems),
2141        );
2142        app.add_systems(
2143            Update,
2144            // Not gated by pause: while a menu is open the system puts the
2145            // camera back to its base field of view and orientation, so the
2146            // settings screen reads and edits the base value.
2147            camera_response_apply
2148                .after(player_footstep_system::<V>)
2149                .in_set(PlayerSystems),
2150        );
2151        app.add_systems(
2152            Update,
2153            // Not gated by pause or by input: the viewer is where the player
2154            // is, whether or not the player moved this frame.
2155            player_sync_viewer
2156                .after(player_resolve_collision::<V>)
2157                .before(crate::world::systems::streaming_system)
2158                .in_set(PlayerSystems),
2159        );
2160        app.add_systems(PostUpdate, save_spawn_on_exit);
2161    }
2162}
2163
2164// ─── Tests ────────────────────────────────────────────────────────────────────
2165
2166#[cfg(test)]
2167mod tests {
2168    use super::*;
2169
2170    #[test]
2171    fn player_default_values() {
2172        let p = Player::default();
2173        assert_eq!(p.speed, 4.0);
2174        assert_eq!(p.sensitivity, 1.0);
2175        assert_eq!(p.roll_speed, 1.5);
2176        assert_eq!(p.velocity, Vec3::ZERO);
2177    }
2178
2179    #[test]
2180    fn player_config_default_values() {
2181        let c = PlayerConfig::default();
2182        assert_eq!(c.speed, 4.0);
2183        assert_eq!(c.fov_degrees, 90.0);
2184        assert!(matches!(
2185            c.mode,
2186            PlayerMode::FreeFlightSixDof {
2187                roll_mode: RollMode::Continuous
2188            }
2189        ));
2190        assert!((c.snap_roll_duration_secs - 0.5).abs() < f32::EPSILON);
2191        assert_eq!(c.snap_roll_easing, SnapRollEasing::EaseOutCubic);
2192    }
2193
2194    #[test]
2195    fn snap_roll_completes_to_90deg() {
2196        let mut anim = start_or_retarget_snap(
2197            None,
2198            Vec3::Z,
2199            Vec3::Y,
2200            1,
2201            0.18,
2202            SnapRollEasing::EaseOutCubic,
2203        );
2204        let (delta, finished) = advance_snap(&mut anim, 0.18);
2205        assert!(finished);
2206        assert!(
2207            (delta - std::f32::consts::FRAC_PI_2).abs() < 1e-4,
2208            "Expected ~PI/2, got {delta}"
2209        );
2210    }
2211
2212    #[test]
2213    fn snap_roll_easing_monotonic() {
2214        let mut anim = start_or_retarget_snap(
2215            None,
2216            Vec3::Z,
2217            Vec3::Y,
2218            1,
2219            0.18,
2220            SnapRollEasing::EaseOutCubic,
2221        );
2222        let step = 0.045;
2223        let mut deltas = Vec::new();
2224        for _ in 0..4 {
2225            let (d, _) = advance_snap(&mut anim, step);
2226            assert!(d > 0.0, "Delta should be positive, got {d}");
2227            deltas.push(d);
2228        }
2229        let total: f32 = deltas.iter().sum();
2230        assert!(
2231            (total - std::f32::consts::FRAC_PI_2).abs() < 1e-3,
2232            "Sum should be ~PI/2, got {total}"
2233        );
2234        // Ease-out: deltas should be non-increasing (each <= previous)
2235        for i in 1..deltas.len() {
2236            assert!(
2237                deltas[i] <= deltas[i - 1] + 1e-6,
2238                "Easing not monotonically decreasing: {:?}",
2239                deltas
2240            );
2241        }
2242    }
2243
2244    #[test]
2245    fn snap_roll_same_direction_extends_target() {
2246        let mut anim = start_or_retarget_snap(
2247            None,
2248            Vec3::Z,
2249            Vec3::Y,
2250            1,
2251            0.18,
2252            SnapRollEasing::EaseOutCubic,
2253        );
2254        // Advance ~30%
2255        advance_snap(&mut anim, 0.054);
2256        let prev_applied = anim.current_applied;
2257        // The transform has rotated with the animation: up at press time
2258        // reflects the applied angle (world-aligned start).
2259        let up = Quat::from_axis_angle(Vec3::Z, anim.current_applied) * Vec3::Y;
2260        let new_anim = start_or_retarget_snap(
2261            Some(anim),
2262            Vec3::Z,
2263            up,
2264            1,
2265            0.18,
2266            SnapRollEasing::EaseOutCubic,
2267        );
2268        assert!((new_anim.start_angle - prev_applied).abs() < 1e-6);
2269        assert!(
2270            (new_anim.target_angle - std::f32::consts::PI).abs() < 1e-4,
2271            "Expected target ~PI (2x90°), got {}",
2272            new_anim.target_angle
2273        );
2274    }
2275
2276    #[test]
2277    fn snap_roll_opposite_direction_reverses_to_lattice() {
2278        let mut anim = start_or_retarget_snap(
2279            None,
2280            Vec3::Z,
2281            Vec3::Y,
2282            1,
2283            0.18,
2284            SnapRollEasing::EaseOutCubic,
2285        );
2286        // Advance ~30% (heading to PI/2 ≈ 1.571)
2287        advance_snap(&mut anim, 0.054);
2288        let current = anim.current_applied;
2289        assert!(current > 0.0 && current < std::f32::consts::FRAC_PI_2);
2290        // The transform has rotated with the animation: up at press time
2291        // reflects the applied angle (world-aligned start).
2292        let up = Quat::from_axis_angle(Vec3::Z, current) * Vec3::Y;
2293        let new_anim = start_or_retarget_snap(
2294            Some(anim),
2295            Vec3::Z,
2296            up,
2297            -1,
2298            0.18,
2299            SnapRollEasing::EaseOutCubic,
2300        );
2301        // Should target 0.0 (nearest lattice below current in negative direction)
2302        assert!(
2303            new_anim.target_angle.abs() < 1e-6,
2304            "Expected target ~0, got {}",
2305            new_anim.target_angle
2306        );
2307    }
2308
2309    #[test]
2310    fn continuous_mode_unchanged() {
2311        let player = Player::default();
2312        assert!(matches!(
2313            player.mode,
2314            PlayerMode::FreeFlightSixDof {
2315                roll_mode: RollMode::Continuous
2316            }
2317        ));
2318        assert!(player.snap_anim.is_none());
2319    }
2320
2321    #[test]
2322    fn snap_roll_config_copies_to_player() {
2323        let config = PlayerConfig {
2324            mode: PlayerMode::FreeFlightSixDof {
2325                roll_mode: RollMode::Snap,
2326            },
2327            snap_roll_duration_secs: 0.3,
2328            snap_roll_easing: SnapRollEasing::Smoothstep,
2329            ..default()
2330        };
2331        let player = Player {
2332            mode: config.mode.clone(),
2333            snap_roll_duration: config.snap_roll_duration_secs,
2334            snap_roll_easing: config.snap_roll_easing,
2335            ..default()
2336        };
2337        assert!(matches!(
2338            player.mode,
2339            PlayerMode::FreeFlightSixDof {
2340                roll_mode: RollMode::Snap
2341            }
2342        ));
2343        assert!((player.snap_roll_duration - 0.3).abs() < f32::EPSILON);
2344        assert_eq!(player.snap_roll_easing, SnapRollEasing::Smoothstep);
2345    }
2346
2347    #[test]
2348    fn snap_roll_start_from_none_is_independent() {
2349        let anim1 = start_or_retarget_snap(
2350            None,
2351            Vec3::Z,
2352            Vec3::Y,
2353            1,
2354            0.18,
2355            SnapRollEasing::EaseOutCubic,
2356        );
2357        let anim2 = start_or_retarget_snap(
2358            None,
2359            Vec3::Z,
2360            Vec3::Y,
2361            1,
2362            0.18,
2363            SnapRollEasing::EaseOutCubic,
2364        );
2365        assert!((anim1.target_angle - anim2.target_angle).abs() < f32::EPSILON);
2366        assert!((anim1.start_angle - anim2.start_angle).abs() < f32::EPSILON);
2367    }
2368
2369    #[test]
2370    fn lattice_axis_forward_yields_four_candidates_at_90deg() {
2371        // Looking straight down: local Z (back) parallel to world Y.
2372        let mut angles = world_lattice_angles(Vec3::Y, Vec3::Z);
2373        assert_eq!(angles.len(), 4, "Y axis pair must be excluded: {angles:?}");
2374        angles.sort_by(f32::total_cmp);
2375        for pair in angles.windows(2) {
2376            assert!(
2377                (pair[1] - pair[0] - std::f32::consts::FRAC_PI_2).abs() < 1e-5,
2378                "Candidates must be exactly 90° apart: {angles:?}"
2379            );
2380        }
2381    }
2382
2383    #[test]
2384    fn lattice_near_axis_forward_still_yields_four_candidates() {
2385        // Playtest regression: view drifted a few degrees off a world axis
2386        // must NOT resurrect the near-forward axis pair as junk candidates
2387        // (6 stops with two perceptually arbitrary ones). 45° dominance rule.
2388        let local_z = Quat::from_axis_angle(Vec3::X, 8_f32.to_radians()) * Vec3::Z;
2389        let up = Quat::from_axis_angle(local_z, 5_f32.to_radians())
2390            * (Vec3::Y - Vec3::Y.dot(local_z) * local_z).normalize();
2391
2392        let angles = world_lattice_angles(local_z, up);
2393        assert_eq!(
2394            angles.len(),
2395            4,
2396            "Near-axis view must exclude the ±Z pair, got {angles:?}"
2397        );
2398
2399        // Exact 45° edge-on view: both axis families sit at proj² ≈ 0.5.
2400        // Float rounding must never exclude both (≥4 invariant) — the 0.49
2401        // threshold keeps the tie inclusive, so all 6 survive.
2402        let boundary_z = Vec3::new(0.0, 1.0, 1.0).normalize();
2403        let boundary_up = (Vec3::Y - Vec3::Y.dot(boundary_z) * boundary_z).normalize();
2404        assert_eq!(
2405            world_lattice_angles(boundary_z, boundary_up).len(),
2406            6,
2407            "At exactly 45° both axis families are equally valid"
2408        );
2409    }
2410
2411    #[test]
2412    fn lattice_diagonal_forward_yields_six_candidates_cycling_2pi() {
2413        use std::f32::consts::{FRAC_PI_2, FRAC_PI_3, TAU};
2414        // Forward = (1,1,1)/√3, so local Z (back) is the opposite diagonal.
2415        let local_z = -Vec3::ONE.normalize();
2416        // Start exactly on a candidate: world X projected onto the roll plane.
2417        let start = (Vec3::X - Vec3::X.dot(local_z) * local_z).normalize();
2418
2419        let angles = world_lattice_angles(local_z, start);
2420        assert_eq!(
2421            angles.len(),
2422            6,
2423            "All 6 axes survive on a diagonal: {angles:?}"
2424        );
2425
2426        // Six Q presses walk the hexagon: each step ~60° (never 90°),
2427        // the total is a full turn, and we return to the start candidate.
2428        let mut up = start;
2429        let mut total = 0.0_f32;
2430        for _ in 0..6 {
2431            let step = next_lattice_step(&world_lattice_angles(local_z, up), 1);
2432            assert!(
2433                (step - FRAC_PI_3).abs() < 1e-3,
2434                "Expected ~60° step, got {step}"
2435            );
2436            assert!(
2437                (step - FRAC_PI_2).abs() > 0.1,
2438                "Step must not be 90°, got {step}"
2439            );
2440            total += step;
2441            up = Quat::from_axis_angle(local_z, step) * up;
2442        }
2443        assert!(
2444            (total - TAU).abs() < 1e-3,
2445            "Six presses must sum to 2π, got {total}"
2446        );
2447        assert!(
2448            up.dot(start) > 0.9999,
2449            "Cycle must return to start, got {up:?}"
2450        );
2451    }
2452
2453    #[test]
2454    fn lattice_drifted_up_travels_residual() {
2455        // Up rolled 10° off the Y candidate (CCW, rotate_local_z convention).
2456        let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
2457        let angles = world_lattice_angles(Vec3::Z, up);
2458
2459        let q = next_lattice_step(&angles, 1);
2460        let e = next_lattice_step(&angles, -1);
2461        assert!(
2462            (q - 80_f32.to_radians()).abs() < 1e-4,
2463            "Q must travel ≈+80°, got {q}"
2464        );
2465        assert!(
2466            (e + 10_f32.to_radians()).abs() < 1e-4,
2467            "E must travel ≈−10°, got {e}"
2468        );
2469
2470        // Both presses land within ε of a world candidate.
2471        let up_q = Quat::from_axis_angle(Vec3::Z, q) * up;
2472        let up_e = Quat::from_axis_angle(Vec3::Z, e) * up;
2473        assert!(
2474            up_q.dot(Vec3::NEG_X) > 0.9999,
2475            "Q must land on −X, got {up_q:?}"
2476        );
2477        assert!(
2478            up_e.dot(Vec3::Y) > 0.9999,
2479            "E must land on +Y, got {up_e:?}"
2480        );
2481    }
2482
2483    #[test]
2484    fn lattice_eps_on_skips_exact_candidate() {
2485        // Up exactly on a candidate: the press must travel a full step, not ~0.
2486        let angles = world_lattice_angles(Vec3::Z, Vec3::Y);
2487        let q = next_lattice_step(&angles, 1);
2488        let e = next_lattice_step(&angles, -1);
2489        assert!(
2490            (q - std::f32::consts::FRAC_PI_2).abs() < 1e-5,
2491            "Q from an exact candidate must be +90°, got {q}"
2492        );
2493        assert!(
2494            (e + std::f32::consts::FRAC_PI_2).abs() < 1e-5,
2495            "E from an exact candidate must be −90°, got {e}"
2496        );
2497    }
2498
2499    #[test]
2500    fn snap_retarget_drifted_frame_lands_on_candidates() {
2501        let local_z = Vec3::Z;
2502        // Start 10° off the Y candidate: fresh Q targets the −X candidate (+80°).
2503        let up0 = Quat::from_axis_angle(local_z, 10_f32.to_radians()) * Vec3::Y;
2504
2505        // Same-direction press mid-flight extends to the NEXT candidate (−Y).
2506        let mut anim =
2507            start_or_retarget_snap(None, local_z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
2508        advance_snap(&mut anim, 0.054);
2509        let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2510        let extended = start_or_retarget_snap(
2511            Some(anim),
2512            local_z,
2513            up_mid,
2514            1,
2515            0.18,
2516            SnapRollEasing::EaseOutCubic,
2517        );
2518        let up_ext = Quat::from_axis_angle(local_z, extended.target_angle) * up0;
2519        assert!(
2520            up_ext.dot(Vec3::NEG_Y) > 0.9999,
2521            "Extend must land on −Y, got {up_ext:?}"
2522        );
2523
2524        // Opposite press mid-flight reverses to the candidate behind (+Y).
2525        let mut anim =
2526            start_or_retarget_snap(None, local_z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
2527        advance_snap(&mut anim, 0.054);
2528        let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2529        let reversed = start_or_retarget_snap(
2530            Some(anim),
2531            local_z,
2532            up_mid,
2533            -1,
2534            0.18,
2535            SnapRollEasing::EaseOutCubic,
2536        );
2537        let up_rev = Quat::from_axis_angle(local_z, reversed.target_angle) * up0;
2538        assert!(
2539            up_rev.dot(Vec3::Y) > 0.9999,
2540            "Reverse must land on +Y, got {up_rev:?}"
2541        );
2542    }
2543
2544    #[test]
2545    fn push_capsule_no_collision() {
2546        // Voxel at origin, player far away — should not move.
2547        let pos = Vec3::new(10.0, 10.0, 10.0);
2548        let result = push_capsule_out(pos, Vec3::Y, PLAYER_HALF_HEIGHT, Vec3::ZERO, 0, 0, 0);
2549        assert_eq!(result, pos);
2550    }
2551
2552    #[test]
2553    fn push_capsule_resolves_overlap() {
2554        // Player center directly on top of a voxel — must be pushed out.
2555        let pos = Vec3::new(0.5, 0.5, 0.5); // inside voxel [0,0,0]
2556        let result = push_capsule_out(pos, Vec3::Y, PLAYER_HALF_HEIGHT, Vec3::ZERO, 0, 0, 0);
2557        // After push, capsule sphere should clear the voxel.
2558        let vox_center = Vec3::splat(0.5);
2559        let closest = result.clamp(Vec3::ZERO, Vec3::ONE);
2560        let dist = (result - closest).length();
2561        assert!(
2562            dist >= PLAYER_RADIUS - 0.001,
2563            "dist={dist} must be >= PLAYER_RADIUS={PLAYER_RADIUS}"
2564        );
2565        let _ = vox_center; // silence unused warning
2566    }
2567
2568    // ─── Anchored look: pitch clamp ──────────────────────────────────────────
2569
2570    #[test]
2571    fn clamp_pitch_under_limit_passes_through() {
2572        // Level forward (pitch 0 vs +Y anchor): moderate deltas are untouched.
2573        let d = clamp_pitch_delta(Vec3::NEG_Z, Vec3::Y, 30_f32.to_radians());
2574        assert!((d - 30_f32.to_radians()).abs() < 1e-5, "got {d}");
2575        let d = clamp_pitch_delta(Vec3::NEG_Z, Vec3::Y, -30_f32.to_radians());
2576        assert!((d + 30_f32.to_radians()).abs() < 1e-5, "got {d}");
2577    }
2578
2579    #[test]
2580    fn clamp_pitch_crossing_limit_truncates() {
2581        // From +80° elevation a +20° request truncates to +9° (lands at +89°).
2582        let f_hi = Vec3::new(0.0, 80_f32.to_radians().sin(), -(80_f32.to_radians().cos()));
2583        let d = clamp_pitch_delta(f_hi, Vec3::Y, 20_f32.to_radians());
2584        assert!(
2585            (d - 9_f32.to_radians()).abs() < 1e-4,
2586            "expected ~+9°, got {d}"
2587        );
2588
2589        // Mirror: from −80° a −20° request truncates to −9° (lands at −89°).
2590        let f_lo = Vec3::new(
2591            0.0,
2592            -(80_f32.to_radians().sin()),
2593            -(80_f32.to_radians().cos()),
2594        );
2595        let d = clamp_pitch_delta(f_lo, Vec3::Y, -20_f32.to_radians());
2596        assert!(
2597            (d + 9_f32.to_radians()).abs() < 1e-4,
2598            "expected ~−9°, got {d}"
2599        );
2600    }
2601
2602    #[test]
2603    fn clamp_pitch_at_limit_blocks_outward_allows_inward() {
2604        // Exactly at the +89° pole: outward is blocked, inward passes through.
2605        let f = Vec3::new(0.0, 89_f32.to_radians().sin(), -(89_f32.to_radians().cos()));
2606        let outward = clamp_pitch_delta(f, Vec3::Y, 5_f32.to_radians());
2607        assert!(
2608            outward.abs() < 1e-4,
2609            "outward delta at the pole must be ~0, got {outward}"
2610        );
2611        let inward = clamp_pitch_delta(f, Vec3::Y, -5_f32.to_radians());
2612        assert!(
2613            (inward + 5_f32.to_radians()).abs() < 1e-4,
2614            "inward delta must pass through, got {inward}"
2615        );
2616    }
2617
2618    // ─── Anchored look: lattice candidates ───────────────────────────────────
2619
2620    #[test]
2621    fn candidates_axis_forward_have_source_axes() {
2622        use std::f32::consts::FRAC_PI_2;
2623        // Axial view (local Z = world Z, up = Y): the ±Z pair is filtered, the
2624        // four survivors carry their source axes with the expected angles.
2625        let cands = world_lattice_candidates(Vec3::Z, Vec3::Y);
2626        assert_eq!(cands.len(), 4, "±Z must be excluded: {cands:?}");
2627        let angle_of = |axis: Vec3| {
2628            cands
2629                .iter()
2630                .find(|(_, a)| *a == axis)
2631                .unwrap_or_else(|| panic!("axis {axis:?} missing from {cands:?}"))
2632                .0
2633        };
2634        assert!(
2635            (angle_of(Vec3::X) + FRAC_PI_2).abs() < 1e-5,
2636            "X must sit at −π/2"
2637        );
2638        assert!(
2639            (angle_of(Vec3::NEG_X) - FRAC_PI_2).abs() < 1e-5,
2640            "−X must sit at +π/2"
2641        );
2642        assert!(angle_of(Vec3::Y).abs() < 1e-5, "Y must sit at 0");
2643        assert!(
2644            (angle_of(Vec3::NEG_Y).abs() - std::f32::consts::PI).abs() < 1e-5,
2645            "−Y must sit at ±π"
2646        );
2647    }
2648
2649    #[test]
2650    fn candidates_diagonal_forward_yield_six_axes() {
2651        // Diagonal view: every signed world axis survives, each exactly once.
2652        let local_z = -Vec3::ONE.normalize();
2653        let up = (Vec3::X - Vec3::X.dot(local_z) * local_z).normalize();
2654        let cands = world_lattice_candidates(local_z, up);
2655        assert_eq!(
2656            cands.len(),
2657            6,
2658            "all 6 axes survive on a diagonal: {cands:?}"
2659        );
2660        for axis in AXES {
2661            assert_eq!(
2662                cands.iter().filter(|(_, a)| *a == axis).count(),
2663                1,
2664                "axis {axis:?} must appear exactly once: {cands:?}"
2665            );
2666        }
2667    }
2668
2669    #[test]
2670    fn lattice_angles_equal_candidate_angles() {
2671        // The wrapper must be observably identical to the candidate angles.
2672        let diag_z = -Vec3::ONE.normalize();
2673        let diag_up = (Vec3::X - Vec3::X.dot(diag_z) * diag_z).normalize();
2674        for (local_z, up) in [(Vec3::Z, Vec3::Y), (diag_z, diag_up)] {
2675            let angles = world_lattice_angles(local_z, up);
2676            let cands = world_lattice_candidates(local_z, up);
2677            assert_eq!(angles.len(), cands.len());
2678            for (a, (c, _)) in angles.iter().zip(cands.iter()) {
2679                assert_eq!(a, c, "wrapper angle {a} != candidate angle {c}");
2680            }
2681        }
2682    }
2683
2684    // ─── Anchored look: candidate stepping ───────────────────────────────────
2685
2686    #[test]
2687    fn next_lattice_candidate_matches_next_lattice_step() {
2688        // Drifted up (10° off Y): the axis-carrying mirror must agree with the
2689        // locked next_lattice_step in both directions.
2690        let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
2691        let cands = world_lattice_candidates(Vec3::Z, up);
2692        let angles = world_lattice_angles(Vec3::Z, up);
2693        for dir in [1, -1] {
2694            let (cand_angle, _) = next_lattice_candidate(&cands, dir);
2695            let step = next_lattice_step(&angles, dir);
2696            assert_eq!(cand_angle, step, "dir {dir}: {cand_angle} != {step}");
2697        }
2698    }
2699
2700    #[test]
2701    fn next_candidate_q_yields_neg_x_e_yields_x() {
2702        use std::f32::consts::FRAC_PI_2;
2703        // From (local_z = Z, up = Y): Q travels +90° to the −X candidate,
2704        // E travels −90° to the +X candidate.
2705        let cands = world_lattice_candidates(Vec3::Z, Vec3::Y);
2706        let (q_angle, q_axis) = next_lattice_candidate(&cands, 1);
2707        assert!(
2708            (q_angle - FRAC_PI_2).abs() < 1e-5,
2709            "Q must travel +π/2, got {q_angle}"
2710        );
2711        assert_eq!(q_axis, Vec3::NEG_X);
2712        let (e_angle, e_axis) = next_lattice_candidate(&cands, -1);
2713        assert!(
2714            (e_angle + FRAC_PI_2).abs() < 1e-5,
2715            "E must travel −π/2, got {e_angle}"
2716        );
2717        assert_eq!(e_axis, Vec3::X);
2718    }
2719
2720    // ─── Anchored look: reference up and anchor commit ───────────────────────
2721
2722    #[test]
2723    fn snap_reference_up_fresh_and_opposite_use_up() {
2724        let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
2725        // Fresh press: no animation → reference is the current up.
2726        assert_eq!(snap_reference_up(None, Vec3::Z, up, 1), up);
2727        // Opposite-direction press mid-animation → reference is still up.
2728        let mut anim =
2729            start_or_retarget_snap(None, Vec3::Z, up, 1, 0.18, SnapRollEasing::EaseOutCubic);
2730        advance_snap(&mut anim, 0.054);
2731        assert_eq!(snap_reference_up(Some(anim), Vec3::Z, up, -1), up);
2732    }
2733
2734    #[test]
2735    fn snap_reference_up_same_dir_advances_residual() {
2736        let up0 = Vec3::Y;
2737        let mut anim =
2738            start_or_retarget_snap(None, Vec3::Z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
2739        advance_snap(&mut anim, 0.054);
2740        // The transform rotated with the animation: up now reflects the
2741        // applied angle. Same-dir reference = up advanced by the residual,
2742        // i.e. the in-flight target up.
2743        let up_mid = Quat::from_axis_angle(Vec3::Z, anim.current_applied) * up0;
2744        let ref_up = snap_reference_up(Some(anim), Vec3::Z, up_mid, 1);
2745        let expected =
2746            Quat::from_axis_angle(Vec3::Z, anim.target_angle - anim.current_applied) * up_mid;
2747        assert!(
2748            ref_up.dot(expected) > 0.9999,
2749            "ref {ref_up:?} != target up {expected:?}"
2750        );
2751        // For this fresh anim the in-flight target is the −X candidate.
2752        assert!(
2753            ref_up.dot(Vec3::NEG_X) > 0.9999,
2754            "expected ~−X, got {ref_up:?}"
2755        );
2756    }
2757
2758    #[test]
2759    fn anchor_commit_matches_pending_projection() {
2760        let local_z = Vec3::Z;
2761        let dur = 0.18;
2762        let ease = SnapRollEasing::EaseOutCubic;
2763        let up0 = Quat::from_axis_angle(local_z, 10_f32.to_radians()) * Vec3::Y;
2764        let proj = |axis: Vec3| (axis - axis.dot(local_z) * local_z).normalize();
2765
2766        // Fresh Q: pending axis −X; the animation must land on its projection.
2767        let ref_up = snap_reference_up(None, local_z, up0, 1);
2768        let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
2769        assert_eq!(axis, Vec3::NEG_X);
2770        let anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
2771        let landed = Quat::from_axis_angle(local_z, anim.target_angle) * up0;
2772        assert!(
2773            landed.dot(proj(axis)) > 0.9999,
2774            "fresh: {landed:?} != proj({axis:?})"
2775        );
2776
2777        // Extend (same dir mid-anim): pending axis −Y, one candidate further.
2778        let mut anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
2779        advance_snap(&mut anim, 0.054);
2780        let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2781        let ref_up = snap_reference_up(Some(anim), local_z, up_mid, 1);
2782        let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
2783        assert_eq!(axis, Vec3::NEG_Y);
2784        let extended = start_or_retarget_snap(Some(anim), local_z, up_mid, 1, dur, ease);
2785        let landed = Quat::from_axis_angle(local_z, extended.target_angle) * up0;
2786        assert!(
2787            landed.dot(proj(axis)) > 0.9999,
2788            "extend: {landed:?} != proj({axis:?})"
2789        );
2790
2791        // Reverse (opposite dir mid-anim): pending axis +Y, behind current up.
2792        let mut anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
2793        advance_snap(&mut anim, 0.054);
2794        let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2795        let ref_up = snap_reference_up(Some(anim), local_z, up_mid, -1);
2796        let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), -1);
2797        assert_eq!(axis, Vec3::Y);
2798        let reversed = start_or_retarget_snap(Some(anim), local_z, up_mid, -1, dur, ease);
2799        let landed = Quat::from_axis_angle(local_z, reversed.target_angle) * up0;
2800        assert!(
2801            landed.dot(proj(axis)) > 0.9999,
2802            "reverse: {landed:?} != proj({axis:?})"
2803        );
2804    }
2805
2806    // ─── Anchored look: spawn anchor and defaults ────────────────────────────
2807
2808    #[test]
2809    fn nearest_world_axis_snaps_biased_vectors() {
2810        assert_eq!(nearest_world_axis(Vec3::new(0.9, 0.1, 0.2)), Vec3::X);
2811        assert_eq!(nearest_world_axis(Vec3::new(-2.0, 0.5, 0.5)), Vec3::NEG_X);
2812        assert_eq!(nearest_world_axis(Vec3::new(0.1, -1.5, 0.3)), Vec3::NEG_Y);
2813        assert_eq!(nearest_world_axis(Vec3::new(-0.1, 0.2, 0.95)), Vec3::Z);
2814        assert_eq!(nearest_world_axis(Vec3::new(0.2, 0.3, -0.9)), Vec3::NEG_Z);
2815    }
2816
2817    #[test]
2818    fn nearest_world_axis_tie_uses_axes_order() {
2819        // Strict `>` keeps the first max in AXES order [X, −X, Y, −Y, Z, −Z].
2820        assert_eq!(nearest_world_axis(Vec3::new(1.0, 1.0, 0.0)), Vec3::X);
2821        assert_eq!(nearest_world_axis(Vec3::new(0.0, 1.0, 1.0)), Vec3::Y);
2822        assert_eq!(nearest_world_axis(Vec3::new(-1.0, -1.0, -1.0)), Vec3::NEG_X);
2823    }
2824
2825    #[test]
2826    fn player_mode_defaults_to_sixdof() {
2827        let p = Player::default();
2828        assert!(matches!(
2829            p.mode,
2830            PlayerMode::FreeFlightSixDof {
2831                roll_mode: RollMode::Continuous
2832            }
2833        ));
2834        assert_eq!(p.anchor_up, Vec3::Y);
2835        assert!(p.pending_anchor.is_none());
2836        assert!(matches!(
2837            PlayerConfig::default().mode,
2838            PlayerMode::FreeFlightSixDof {
2839                roll_mode: RollMode::Continuous
2840            }
2841        ));
2842    }
2843
2844    #[test]
2845    fn anchored_mode_config_copies_to_player() {
2846        // Non-default value must propagate config → component.
2847        let config = PlayerConfig {
2848            mode: PlayerMode::FreeFlightAnchored,
2849            ..default()
2850        };
2851        let player = Player {
2852            mode: config.mode.clone(),
2853            ..default()
2854        };
2855        assert!(matches!(player.mode, PlayerMode::FreeFlightAnchored));
2856    }
2857
2858    // ---- Frame-loop integration tests -------------------------------------
2859    //
2860    // Three Anchored behaviors are frame-loop properties, not pure functions:
2861    // a level horizon under diagonal input, mouse-look staying on the OLD
2862    // anchor while a switch animates, and `RollMode::Continuous` being inert.
2863    // These drive `player_look` through a headless `App`.
2864
2865    /// Builds a headless app that runs `player_look` over one Anchored player
2866    /// starting from the identity transform (forward −Z, up +Y, right +X).
2867    fn anchored_app() -> (App, Entity) {
2868        let mut app = App::new();
2869        app.add_message::<MouseMotion>();
2870        app.insert_resource(ButtonInput::<KeyCode>::default());
2871        app.insert_resource(Time::<()>::default());
2872        app.add_systems(Update, player_look);
2873        let entity = app
2874            .world_mut()
2875            .spawn((
2876                Player {
2877                    mode: PlayerMode::FreeFlightAnchored,
2878                    ..default()
2879                },
2880                Transform::default(),
2881            ))
2882            .id();
2883        (app, entity)
2884    }
2885
2886    /// App running only [`player_cursor_system`], with a focused primary
2887    /// window and, optionally, a pause-menu state resource.
2888    fn cursor_app(
2889        pause: Option<crate::ui::PauseMenuState>,
2890        locked: bool,
2891    ) -> (App, bevy::ecs::entity::Entity) {
2892        use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
2893        let mut app = App::new();
2894        app.init_resource::<ButtonInput<KeyCode>>()
2895            .init_resource::<ButtonInput<MouseButton>>()
2896            .add_systems(Update, player_cursor_system);
2897        if let Some(state) = pause {
2898            app.insert_resource(State::new(state));
2899        }
2900        let window = app
2901            .world_mut()
2902            .spawn((
2903                Window {
2904                    focused: true,
2905                    ..default()
2906                },
2907                PrimaryWindow,
2908                CursorOptions {
2909                    grab_mode: if locked {
2910                        CursorGrabMode::Locked
2911                    } else {
2912                        CursorGrabMode::None
2913                    },
2914                    visible: !locked,
2915                    ..default()
2916                },
2917            ))
2918            .id();
2919        (app, window)
2920    }
2921
2922    fn grab_mode(app: &App, window: bevy::ecs::entity::Entity) -> bevy::window::CursorGrabMode {
2923        app.world()
2924            .get::<bevy::window::CursorOptions>(window)
2925            .expect("window should still exist")
2926            .grab_mode
2927    }
2928
2929    #[test]
2930    fn pause_menu_owns_escape_so_a_free_cursor_does_not_close_the_window() {
2931        use crate::ui::PauseMenuState;
2932        let (mut app, window) = cursor_app(Some(PauseMenuState::Playing), false);
2933        app.world_mut()
2934            .resource_mut::<ButtonInput<KeyCode>>()
2935            .press(KeyCode::Escape);
2936
2937        app.update();
2938
2939        assert!(
2940            app.world().get_entity(window).is_ok(),
2941            "Escape belongs to the pause menu when it is installed"
2942        );
2943    }
2944
2945    #[test]
2946    fn pause_menu_owns_escape_so_a_captured_cursor_is_not_released_here() {
2947        use crate::ui::PauseMenuState;
2948        use bevy::window::CursorGrabMode;
2949        let (mut app, window) = cursor_app(Some(PauseMenuState::Playing), true);
2950        app.world_mut()
2951            .resource_mut::<ButtonInput<KeyCode>>()
2952            .press(KeyCode::Escape);
2953
2954        app.update();
2955
2956        // The pause menu releases it when it enters `Paused`.
2957        assert_eq!(grab_mode(&app, window), CursorGrabMode::Locked);
2958    }
2959
2960    #[test]
2961    fn with_pause_menu_a_focused_click_captures_and_focus_loss_releases() {
2962        use crate::ui::PauseMenuState;
2963        use bevy::window::CursorGrabMode;
2964        let (mut app, window) = cursor_app(Some(PauseMenuState::Playing), false);
2965        app.world_mut()
2966            .resource_mut::<ButtonInput<MouseButton>>()
2967            .press(MouseButton::Left);
2968        app.update();
2969        assert_eq!(grab_mode(&app, window), CursorGrabMode::Locked);
2970
2971        app.world_mut()
2972            .resource_mut::<ButtonInput<MouseButton>>()
2973            .reset_all();
2974        app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
2975        app.update();
2976        assert_eq!(grab_mode(&app, window), CursorGrabMode::None);
2977    }
2978
2979    #[test]
2980    fn menu_clicks_do_not_capture_the_cursor_while_paused_or_in_settings() {
2981        use crate::ui::PauseMenuState;
2982        use bevy::window::CursorGrabMode;
2983        for state in [PauseMenuState::Paused, PauseMenuState::Settings] {
2984            // The system is added without a run condition, as a game composing
2985            // the player systems by hand would.
2986            let (mut app, window) = cursor_app(Some(state), false);
2987            app.world_mut()
2988                .resource_mut::<ButtonInput<MouseButton>>()
2989                .press(MouseButton::Left);
2990
2991            app.update();
2992
2993            assert_eq!(grab_mode(&app, window), CursorGrabMode::None);
2994        }
2995    }
2996
2997    #[test]
2998    fn player_systems_set_gates_the_plugin_systems() {
2999        use bevy::window::{CursorGrabMode, PrimaryWindow};
3000        let mut app = App::new();
3001        app.add_plugins(PlayerPlugin::<crate::voxel::DefaultVoxel>::new());
3002        app.init_resource::<ButtonInput<KeyCode>>()
3003            .init_resource::<ButtonInput<MouseButton>>();
3004        // A game-owned condition on the whole plugin, without re-registering
3005        // its systems by hand.
3006        app.configure_sets(Update, PlayerSystems.run_if(|| false));
3007        let window = app
3008            .world_mut()
3009            .spawn((
3010                Window {
3011                    focused: true,
3012                    ..default()
3013                },
3014                PrimaryWindow,
3015            ))
3016            .id();
3017        app.world_mut()
3018            .resource_mut::<ButtonInput<MouseButton>>()
3019            .press(MouseButton::Left);
3020
3021        // Only `Update`: the plugin's `Startup` systems touch the disk.
3022        app.world_mut().run_schedule(Update);
3023
3024        assert_eq!(
3025            grab_mode(&app, window),
3026            CursorGrabMode::None,
3027            "a disabled PlayerSystems set must stop the cursor system"
3028        );
3029    }
3030
3031    #[test]
3032    fn player_plugin_runs_without_the_audio_and_ui_plugins() {
3033        let mut app = App::new();
3034        app.add_plugins(MinimalPlugins)
3035            .add_plugins(bevy::input::InputPlugin)
3036            .add_plugins(crate::world::WorldPlugin)
3037            .add_plugins(PlayerPlugin::<crate::voxel::DefaultVoxel>::new());
3038
3039        // `player_footstep_system` writes `SfxRequest`; an unregistered
3040        // message makes the schedule panic. Only `Update`: the plugin's
3041        // `Startup` systems touch the disk.
3042        app.world_mut().run_schedule(Update);
3043    }
3044
3045    #[test]
3046    fn focus_loss_releases_the_cursor_even_while_a_menu_is_open() {
3047        use crate::ui::PauseMenuState;
3048        use bevy::window::CursorGrabMode;
3049        let (mut app, window) = cursor_app(Some(PauseMenuState::Paused), true);
3050        app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
3051
3052        app.update();
3053
3054        assert_eq!(grab_mode(&app, window), CursorGrabMode::None);
3055    }
3056
3057    #[test]
3058    fn without_pause_menu_escape_keeps_its_two_stage_behavior() {
3059        use bevy::window::CursorGrabMode;
3060        let (mut app, window) = cursor_app(None, true);
3061        app.world_mut()
3062            .resource_mut::<ButtonInput<KeyCode>>()
3063            .press(KeyCode::Escape);
3064        app.update();
3065        assert_eq!(grab_mode(&app, window), CursorGrabMode::None);
3066
3067        // Still held as "just pressed": the second stage closes the window.
3068        app.update();
3069        assert!(app.world().get_entity(window).is_err());
3070    }
3071
3072    #[test]
3073    fn focus_loss_releases_capture_and_ignores_unfocused_click_and_escape() {
3074        use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
3075        let mut app = App::new();
3076        app.init_resource::<ButtonInput<KeyCode>>()
3077            .init_resource::<ButtonInput<MouseButton>>()
3078            .add_systems(Update, player_cursor_system);
3079        let window = app
3080            .world_mut()
3081            .spawn((
3082                Window {
3083                    focused: false,
3084                    ..default()
3085                },
3086                PrimaryWindow,
3087                CursorOptions {
3088                    grab_mode: CursorGrabMode::Locked,
3089                    visible: false,
3090                    ..default()
3091                },
3092            ))
3093            .id();
3094        app.world_mut()
3095            .resource_mut::<ButtonInput<KeyCode>>()
3096            .press(KeyCode::Escape);
3097        app.world_mut()
3098            .resource_mut::<ButtonInput<MouseButton>>()
3099            .press(MouseButton::Left);
3100        app.update();
3101        let cursor = app
3102            .world()
3103            .get::<CursorOptions>(window)
3104            .expect("unfocused Escape must not close the window");
3105        assert_eq!(cursor.grab_mode, CursorGrabMode::None);
3106        assert!(cursor.visible);
3107        app.world_mut()
3108            .resource_mut::<ButtonInput<KeyCode>>()
3109            .reset_all();
3110        app.world_mut()
3111            .resource_mut::<ButtonInput<MouseButton>>()
3112            .reset_all();
3113        app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
3114        app.update();
3115        assert_eq!(
3116            app.world().get::<CursorOptions>(window).unwrap().grab_mode,
3117            CursorGrabMode::None
3118        );
3119        app.world_mut()
3120            .resource_mut::<ButtonInput<MouseButton>>()
3121            .press(MouseButton::Left);
3122        app.update();
3123        assert_eq!(
3124            app.world().get::<CursorOptions>(window).unwrap().grab_mode,
3125            CursorGrabMode::Locked
3126        );
3127    }
3128
3129    #[test]
3130    fn inactive_primary_window_discards_look_without_replaying_it() {
3131        use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
3132        let (mut app, player) = anchored_app();
3133        let window = app
3134            .world_mut()
3135            .spawn((
3136                Window {
3137                    focused: false,
3138                    ..default()
3139                },
3140                PrimaryWindow,
3141            ))
3142            .id();
3143        step(&mut app, Vec2::new(100.0, 20.0), &[KeyCode::KeyQ], 0.1);
3144        assert_eq!(
3145            app.world().get::<Transform>(player).unwrap().rotation,
3146            Quat::IDENTITY
3147        );
3148        assert!(
3149            app.world()
3150                .get::<Player>(player)
3151                .unwrap()
3152                .snap_anim
3153                .is_none()
3154        );
3155        app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
3156        app.world_mut()
3157            .get_mut::<CursorOptions>(window)
3158            .unwrap()
3159            .grab_mode = CursorGrabMode::Locked;
3160        step(&mut app, Vec2::ZERO, &[], 0.1);
3161        assert_eq!(
3162            app.world().get::<Transform>(player).unwrap().rotation,
3163            Quat::IDENTITY
3164        );
3165        step(&mut app, Vec2::new(10.0, 0.0), &[], 0.1);
3166        assert_ne!(
3167            app.world().get::<Transform>(player).unwrap().rotation,
3168            Quat::IDENTITY
3169        );
3170    }
3171
3172    #[test]
3173    fn spawning_player_leaves_cursor_free_until_focused_click() {
3174        use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
3175        let mut app = App::new();
3176        app.init_resource::<PlayerConfig>()
3177            .init_resource::<PlayerHealth>()
3178            .add_systems(Startup, spawn_player);
3179        let window = app
3180            .world_mut()
3181            .spawn((Window::default(), PrimaryWindow))
3182            .id();
3183        app.update();
3184        let cursor = app.world().get::<CursorOptions>(window).unwrap();
3185        assert_eq!(cursor.grab_mode, CursorGrabMode::None);
3186        assert!(cursor.visible);
3187    }
3188
3189    #[test]
3190    fn spawn_player_puts_the_viewer_at_the_spawn_position() {
3191        let spawn = Vec3::new(500.0, 20.0, -300.0);
3192        let mut app = App::new();
3193        app.insert_resource(PlayerConfig {
3194            spawn_position: spawn,
3195            ..default()
3196        })
3197        .init_resource::<PlayerHealth>()
3198        .init_resource::<ViewerPosition>()
3199        .add_systems(Startup, spawn_player);
3200
3201        app.update();
3202
3203        assert_eq!(app.world().resource::<ViewerPosition>().position, spawn);
3204    }
3205
3206    #[test]
3207    fn spawn_player_works_without_a_viewer_position() {
3208        let mut app = App::new();
3209        app.init_resource::<PlayerConfig>()
3210            .init_resource::<PlayerHealth>()
3211            .add_systems(Startup, spawn_player);
3212
3213        app.update();
3214
3215        let mut players = app.world_mut().query::<&Player>();
3216        assert_eq!(players.iter(app.world()).count(), 1);
3217    }
3218
3219    /// App with the whole [`PlayerPlugin`] and one player placed by hand.
3220    /// Runs only `Update`: the plugin's `Startup` systems touch the disk.
3221    fn plugin_app_with_player(position: Vec3) -> (App, Entity) {
3222        let mut app = App::new();
3223        app.add_plugins(MinimalPlugins)
3224            .add_plugins(bevy::input::InputPlugin)
3225            .add_plugins(crate::world::WorldPlugin)
3226            .add_plugins(PlayerPlugin::<crate::voxel::DefaultVoxel>::new());
3227        let player = app
3228            .world_mut()
3229            .spawn((Player::default(), Transform::from_translation(position)))
3230            .id();
3231        (app, player)
3232    }
3233
3234    #[test]
3235    fn the_viewer_follows_a_player_whose_input_is_not_active() {
3236        use bevy::window::PrimaryWindow;
3237        let position = Vec3::new(500.0, 20.0, -300.0);
3238        let (mut app, _) = plugin_app_with_player(position);
3239        // A window with a free cursor: `player_move` returns before its own
3240        // write to `ViewerPosition`.
3241        app.world_mut().spawn((Window::default(), PrimaryWindow));
3242
3243        app.world_mut().run_schedule(Update);
3244
3245        assert_eq!(app.world().resource::<ViewerPosition>().position, position);
3246    }
3247
3248    #[test]
3249    fn the_viewer_follows_the_player_while_gameplay_is_paused() {
3250        let position = Vec3::new(-64.0, 8.0, 128.0);
3251        let (mut app, player) = plugin_app_with_player(Vec3::ZERO);
3252        // What a pause menu does: the movement chain stops running.
3253        app.insert_resource(State::new(crate::ui::PauseMenuState::Paused));
3254        app.world_mut()
3255            .get_mut::<Transform>(player)
3256            .unwrap()
3257            .translation = position;
3258
3259        app.world_mut().run_schedule(Update);
3260
3261        assert_eq!(app.world().resource::<ViewerPosition>().position, position);
3262    }
3263
3264    /// App running only [`player_move`] with one free-flight player and no
3265    /// window, so synthetic input is active.
3266    fn movement_app(config: Option<PlayerMovementConfig>, velocity: Vec3) -> (App, Entity) {
3267        let mut app = App::new();
3268        app.init_resource::<ButtonInput<KeyCode>>()
3269            .init_resource::<Time>()
3270            .init_resource::<ViewerPosition>()
3271            .init_resource::<ChunkManager>()
3272            .init_resource::<PlayerCrouching>()
3273            .add_systems(Update, player_move::<crate::voxel::DefaultVoxel>);
3274        if let Some(config) = config {
3275            app.insert_resource(config);
3276        }
3277        let player = app
3278            .world_mut()
3279            .spawn((
3280                Player {
3281                    velocity,
3282                    ..default()
3283                },
3284                Transform::default(),
3285            ))
3286            .id();
3287        (app, player)
3288    }
3289
3290    /// Advances 0.1 s with `keys` held and returns the player's speed.
3291    fn speed_after_step(app: &mut App, player: Entity, keys: &[KeyCode]) -> f32 {
3292        app.world_mut()
3293            .resource_mut::<Time>()
3294            .advance_by(std::time::Duration::from_millis(100));
3295        for key in keys {
3296            app.world_mut()
3297                .resource_mut::<ButtonInput<KeyCode>>()
3298                .press(*key);
3299        }
3300        app.update();
3301        app.world().get::<Player>(player).unwrap().velocity.length()
3302    }
3303
3304    /// Advances 0.1 s and returns how far the player moved.
3305    fn distance_after_step(app: &mut App, player: Entity) -> f32 {
3306        let before = app.world().get::<Transform>(player).unwrap().translation;
3307        app.world_mut()
3308            .resource_mut::<Time>()
3309            .advance_by(std::time::Duration::from_millis(100));
3310        app.update();
3311        let after = app.world().get::<Transform>(player).unwrap().translation;
3312        after.distance(before)
3313    }
3314
3315    fn waiting_for_chunks() -> Option<PlayerMovementConfig> {
3316        Some(PlayerMovementConfig {
3317            wait_for_chunks: true,
3318            ..default()
3319        })
3320    }
3321
3322    /// Registers every chunk in a 3×3×3 block around the origin as loaded.
3323    fn load_chunks_around_origin(app: &mut App) {
3324        for x in -1..=1 {
3325            for y in -1..=1 {
3326                for z in -1..=1 {
3327                    let entity = app.world_mut().spawn_empty().id();
3328                    app.world_mut()
3329                        .resource_mut::<ChunkManager>()
3330                        .register(IVec3::new(x, y, z), entity);
3331                }
3332            }
3333        }
3334    }
3335
3336    #[test]
3337    fn by_default_the_player_moves_into_chunks_that_are_not_loaded() {
3338        let (mut app, player) = movement_app(None, Vec3::X * 10.0);
3339        assert!(!PlayerMovementConfig::default().wait_for_chunks);
3340
3341        assert!(distance_after_step(&mut app, player) > 0.0);
3342    }
3343
3344    #[test]
3345    fn a_waiting_player_does_not_move_into_chunks_that_are_not_loaded() {
3346        let (mut app, player) = movement_app(waiting_for_chunks(), Vec3::X * 10.0);
3347
3348        assert_eq!(distance_after_step(&mut app, player), 0.0);
3349        // The streaming origin stays on the player, so the chunks get loaded.
3350        assert_eq!(
3351            app.world().resource::<ViewerPosition>().position,
3352            app.world().get::<Transform>(player).unwrap().translation
3353        );
3354    }
3355
3356    #[test]
3357    fn a_waiting_player_moves_once_the_chunks_around_it_are_loaded() {
3358        let (mut app, player) = movement_app(waiting_for_chunks(), Vec3::X * 10.0);
3359        assert_eq!(distance_after_step(&mut app, player), 0.0);
3360
3361        load_chunks_around_origin(&mut app);
3362
3363        assert!(distance_after_step(&mut app, player) > 0.0);
3364    }
3365
3366    #[test]
3367    fn a_waiting_player_needs_every_chunk_its_capsule_touches() {
3368        let (mut app, player) = movement_app(waiting_for_chunks(), Vec3::X * 10.0);
3369        load_chunks_around_origin(&mut app);
3370        // At a chunk corner the capsule reaches into the neighbors.
3371        let near_edge = Vec3::new(31.9, 8.0, 8.0);
3372        app.world_mut()
3373            .get_mut::<Transform>(player)
3374            .unwrap()
3375            .translation = near_edge;
3376
3377        // Chunk (2, 0, 0) is not loaded and the capsule would reach into it.
3378        assert_eq!(distance_after_step(&mut app, player), 0.0);
3379    }
3380
3381    #[test]
3382    fn a_waiting_grounded_player_does_not_build_up_fall_speed() {
3383        let (mut app, player) = movement_app(waiting_for_chunks(), Vec3::ZERO);
3384        {
3385            let mut p = app.world_mut().get_mut::<Player>(player).unwrap();
3386            p.mode = PlayerMode::Grounded {
3387                gravity: 20.0,
3388                jump_speed: 8.0,
3389            };
3390            p.world_loaded = true;
3391        }
3392
3393        for _ in 0..5 {
3394            assert_eq!(distance_after_step(&mut app, player), 0.0);
3395        }
3396
3397        let p = app.world().get::<Player>(player).unwrap();
3398        assert_eq!(p.vertical_velocity, 0.0);
3399    }
3400
3401    #[test]
3402    fn player_chunks_loaded_checks_the_volume_of_the_capsule() {
3403        let mut manager = ChunkManager::default();
3404        let middle = Vec3::splat(8.0);
3405        assert!(!player_chunks_loaded(middle, &manager));
3406
3407        manager.register(IVec3::ZERO, Entity::PLACEHOLDER);
3408        assert!(player_chunks_loaded(middle, &manager));
3409        // Closer to the face than the capsule is long: the neighbor counts.
3410        assert!(!player_chunks_loaded(Vec3::new(15.5, 8.0, 8.0), &manager));
3411    }
3412
3413    #[test]
3414    fn movement_config_defaults_match_the_built_in_feel() {
3415        let config = PlayerMovementConfig::default();
3416        assert_eq!(config.acceleration, 12.0);
3417        assert_eq!(config.deceleration, 7.0);
3418        assert_eq!(config.impact_speed_threshold, 1.0);
3419
3420        // Without the resource the systems behave exactly like the default.
3421        let (mut bare, bare_player) = movement_app(None, Vec3::ZERO);
3422        let (mut with, with_player) = movement_app(Some(config), Vec3::ZERO);
3423        assert_eq!(
3424            speed_after_step(&mut bare, bare_player, &[KeyCode::KeyW]),
3425            speed_after_step(&mut with, with_player, &[KeyCode::KeyW]),
3426        );
3427    }
3428
3429    #[test]
3430    fn acceleration_controls_how_fast_speed_builds() {
3431        let slow = PlayerMovementConfig {
3432            acceleration: 1.0,
3433            ..default()
3434        };
3435        let (mut app, player) = movement_app(Some(slow), Vec3::ZERO);
3436
3437        let speed = speed_after_step(&mut app, player, &[KeyCode::KeyW]);
3438
3439        // One 0.1 s step at rate 1.0 covers a tenth of the way to full speed.
3440        let full = Player::default().speed;
3441        assert!((speed - 0.1 * full).abs() < 1e-4, "speed was {speed}");
3442    }
3443
3444    #[test]
3445    fn deceleration_controls_how_fast_the_player_stops() {
3446        let coast = PlayerMovementConfig {
3447            deceleration: 1.0,
3448            ..default()
3449        };
3450        let (mut app, player) = movement_app(Some(coast), Vec3::Z);
3451
3452        let speed = speed_after_step(&mut app, player, &[]);
3453
3454        assert!((speed - 0.9).abs() < 1e-4, "speed was {speed}");
3455    }
3456
3457    #[test]
3458    fn unusable_movement_rates_fall_back_to_the_defaults() {
3459        let broken = PlayerMovementConfig {
3460            acceleration: f32::NAN,
3461            deceleration: -3.0,
3462            ..default()
3463        };
3464        let (mut app, player) = movement_app(Some(broken), Vec3::ZERO);
3465        let (mut reference, reference_player) = movement_app(None, Vec3::ZERO);
3466
3467        assert_eq!(
3468            speed_after_step(&mut app, player, &[KeyCode::KeyW]),
3469            speed_after_step(&mut reference, reference_player, &[KeyCode::KeyW]),
3470        );
3471        let (mut app, player) = movement_app(Some(broken), Vec3::Z);
3472        let (mut reference, reference_player) = movement_app(None, Vec3::Z);
3473        assert_eq!(
3474            speed_after_step(&mut app, player, &[]),
3475            speed_after_step(&mut reference, reference_player, &[]),
3476        );
3477    }
3478
3479    /// App running only [`player_resolve_collision`] over one solid chunk at
3480    /// the origin, with a free-flight player sunk slightly into its top face.
3481    fn impact_app(register_message: bool) -> (App, Entity) {
3482        use crate::voxel::DefaultVoxel;
3483        let mut app = App::new();
3484        app.init_resource::<ChunkManager>();
3485        if register_message {
3486            app.add_message::<PlayerImpact>();
3487        }
3488        app.add_systems(Update, player_resolve_collision::<DefaultVoxel>);
3489        app.world_mut().spawn((
3490            crate::test_support::filled_chunk(DefaultVoxel::Rock),
3491            Transform::default(),
3492        ));
3493        let player = app
3494            .world_mut()
3495            .spawn((Player::default(), Transform::default()))
3496            .id();
3497        (app, player)
3498    }
3499
3500    /// Puts the player 0.05 units into the top face, moving at `velocity`.
3501    fn sink_into_top(app: &mut App, player: Entity, velocity: Vec3) {
3502        let top = CHUNK_SIZE as f32 * VOXEL_SIZE;
3503        let resting_y = top + PLAYER_HALF_HEIGHT + PLAYER_RADIUS;
3504        app.world_mut()
3505            .get_mut::<Transform>(player)
3506            .unwrap()
3507            .translation = Vec3::new(8.5, resting_y - 0.05, 8.5);
3508        app.world_mut().get_mut::<Player>(player).unwrap().velocity = velocity;
3509    }
3510
3511    fn drain_impacts(app: &mut App) -> Vec<PlayerImpact> {
3512        app.world_mut()
3513            .resource_mut::<Messages<PlayerImpact>>()
3514            .drain()
3515            .collect()
3516    }
3517
3518    #[test]
3519    fn flying_into_terrain_reports_one_impact_with_normal_and_speed() {
3520        let (mut app, player) = impact_app(true);
3521        sink_into_top(&mut app, player, Vec3::new(0.0, -5.0, 0.0));
3522
3523        app.update();
3524
3525        let impacts = drain_impacts(&mut app);
3526        assert_eq!(impacts.len(), 1);
3527        let impact = impacts[0];
3528        assert!(
3529            impact.normal.distance(Vec3::Y) < 1e-3,
3530            "{:?}",
3531            impact.normal
3532        );
3533        assert!((impact.speed - 5.0).abs() < 1e-3, "{}", impact.speed);
3534        assert_eq!(
3535            impact.position,
3536            app.world().get::<Transform>(player).unwrap().translation
3537        );
3538
3539        // Still pressed against the surface: no second report.
3540        sink_into_top(&mut app, player, Vec3::new(0.0, -5.0, 0.0));
3541        app.update();
3542        assert!(drain_impacts(&mut app).is_empty());
3543
3544        // Contact ends, then a new hit is reported again.
3545        app.world_mut()
3546            .get_mut::<Transform>(player)
3547            .unwrap()
3548            .translation
3549            .y += 10.0;
3550        app.update();
3551        sink_into_top(&mut app, player, Vec3::new(0.0, -3.0, 0.0));
3552        app.update();
3553        let impacts = drain_impacts(&mut app);
3554        assert_eq!(impacts.len(), 1);
3555        assert!((impacts[0].speed - 3.0).abs() < 1e-3);
3556    }
3557
3558    #[test]
3559    fn only_the_speed_into_the_surface_counts() {
3560        let (mut app, player) = impact_app(true);
3561        // Fast along the surface, slow into it.
3562        sink_into_top(&mut app, player, Vec3::new(9.0, -0.5, 0.0));
3563
3564        app.update();
3565
3566        assert!(drain_impacts(&mut app).is_empty());
3567    }
3568
3569    #[test]
3570    fn impact_threshold_is_configurable() {
3571        let (mut app, player) = impact_app(true);
3572        app.insert_resource(PlayerMovementConfig {
3573            impact_speed_threshold: 8.0,
3574            ..default()
3575        });
3576        sink_into_top(&mut app, player, Vec3::new(0.0, -5.0, 0.0));
3577        app.update();
3578        assert!(drain_impacts(&mut app).is_empty());
3579
3580        app.insert_resource(PlayerMovementConfig {
3581            impact_speed_threshold: f32::INFINITY,
3582            ..default()
3583        });
3584        sink_into_top(&mut app, player, Vec3::new(0.0, -500.0, 0.0));
3585        app.update();
3586        assert!(drain_impacts(&mut app).is_empty());
3587    }
3588
3589    #[test]
3590    fn collision_still_resolves_without_the_impact_message() {
3591        let (mut app, player) = impact_app(false);
3592        sink_into_top(&mut app, player, Vec3::new(0.0, -5.0, 0.0));
3593        let before = app.world().get::<Transform>(player).unwrap().translation.y;
3594
3595        app.update();
3596
3597        let after = app.world().get::<Transform>(player).unwrap().translation.y;
3598        assert!(after > before, "the player is pushed out of the terrain");
3599    }
3600
3601    #[test]
3602    fn inactive_movement_clears_velocity_and_preserves_position() {
3603        use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
3604        let mut app = App::new();
3605        app.init_resource::<ButtonInput<KeyCode>>()
3606            .init_resource::<Time>()
3607            .init_resource::<ViewerPosition>()
3608            .init_resource::<ChunkManager>()
3609            .init_resource::<PlayerCrouching>()
3610            .add_systems(Update, player_move::<crate::voxel::DefaultVoxel>);
3611        let window = app
3612            .world_mut()
3613            .spawn((
3614                Window {
3615                    focused: false,
3616                    ..default()
3617                },
3618                PrimaryWindow,
3619                CursorOptions {
3620                    grab_mode: CursorGrabMode::Locked,
3621                    ..default()
3622                },
3623            ))
3624            .id();
3625        let player = app
3626            .world_mut()
3627            .spawn((
3628                Player {
3629                    velocity: Vec3::Z,
3630                    ..default()
3631                },
3632                Transform::default(),
3633            ))
3634            .id();
3635        app.world_mut()
3636            .resource_mut::<Time>()
3637            .advance_by(std::time::Duration::from_millis(100));
3638        app.world_mut()
3639            .resource_mut::<ButtonInput<KeyCode>>()
3640            .press(KeyCode::KeyW);
3641        app.update();
3642        assert_eq!(
3643            app.world().get::<Transform>(player).unwrap().translation,
3644            Vec3::ZERO
3645        );
3646        assert_eq!(
3647            app.world().get::<Player>(player).unwrap().velocity,
3648            Vec3::ZERO
3649        );
3650        app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
3651        app.world_mut()
3652            .get_mut::<CursorOptions>(window)
3653            .unwrap()
3654            .grab_mode = CursorGrabMode::None;
3655        app.update();
3656        assert_eq!(
3657            app.world().get::<Transform>(player).unwrap().translation,
3658            Vec3::ZERO
3659        );
3660        app.world_mut()
3661            .get_mut::<CursorOptions>(window)
3662            .unwrap()
3663            .grab_mode = CursorGrabMode::Locked;
3664        app.update();
3665        assert!(app.world().get::<Transform>(player).unwrap().translation.z < 0.0);
3666    }
3667
3668    /// Advances one frame: sets `dt`, applies the exact held-key set (freshly
3669    /// added keys register as `just_pressed`, persisting keys do not), injects
3670    /// mouse motion, then runs the schedule.
3671    fn step(app: &mut App, mouse: Vec2, held: &[KeyCode], dt: f32) {
3672        app.world_mut()
3673            .resource_mut::<Time>()
3674            .advance_by(std::time::Duration::from_secs_f32(dt));
3675        {
3676            let mut input = app.world_mut().resource_mut::<ButtonInput<KeyCode>>();
3677            input.clear(); // drop last frame's just_pressed / just_released
3678            let stale: Vec<KeyCode> = input
3679                .get_pressed()
3680                .copied()
3681                .filter(|k| !held.contains(k))
3682                .collect();
3683            for k in stale {
3684                input.release(k);
3685            }
3686            for k in held {
3687                input.press(*k);
3688            } // re-press keeps held keys out of just_pressed
3689        }
3690        if mouse != Vec2::ZERO {
3691            app.world_mut().write_message(MouseMotion { delta: mouse });
3692        }
3693        app.update();
3694    }
3695
3696    fn forward_of(app: &App, entity: Entity) -> Vec3 {
3697        *app.world()
3698            .entity(entity)
3699            .get::<Transform>()
3700            .unwrap()
3701            .forward()
3702    }
3703
3704    #[test]
3705    fn anchored_diagonal_input_keeps_horizon_level() {
3706        let (mut app, e) = anchored_app();
3707        // Strong diagonal input for enough frames to push pitch into the clamp.
3708        for _ in 0..15 {
3709            step(&mut app, Vec2::new(60.0, -80.0), &[], 0.016);
3710            let right = *app.world().entity(e).get::<Transform>().unwrap().right();
3711            // World-yaw around Y ∘ local-X pitch never rolls the frame: the
3712            // camera's right vector stays in the horizontal plane.
3713            assert!(
3714                right.dot(Vec3::Y).abs() < 1e-4,
3715                "horizon rolled: right·Y = {}",
3716                right.dot(Vec3::Y)
3717            );
3718        }
3719        // The ±89° clamp both engaged (we pushed past 88°) and held (never over).
3720        let elevation = forward_of(&app, e).dot(Vec3::Y).abs();
3721        assert!(
3722            elevation >= 88_f32.to_radians().sin(),
3723            "clamp never engaged: |forward·Y| = {elevation}"
3724        );
3725        assert!(
3726            elevation <= 89_f32.to_radians().sin() + 1e-4,
3727            "pitch exceeded ±89°: |forward·Y| = {elevation}"
3728        );
3729    }
3730
3731    #[test]
3732    fn anchored_switch_yaw_uses_old_anchor() {
3733        let (mut app, e) = anchored_app();
3734        // Frame 1: tap Q to begin a switch. The default 0.5s duration keeps it
3735        // running across the next frame (2 × 0.1s = 0.2s < 0.5s).
3736        step(&mut app, Vec2::ZERO, &[KeyCode::KeyQ], 0.1);
3737        {
3738            let p = app.world().entity(e).get::<Player>().unwrap();
3739            assert!(p.snap_anim.is_some(), "Q should start a switch animation");
3740            assert!(p.pending_anchor.is_some(), "pending anchor should be set");
3741            assert_eq!(p.anchor_up, Vec3::Y, "anchor must not commit mid-animation");
3742        }
3743        let before = forward_of(&app, e);
3744        // Frame 2: release Q, yaw with the mouse while the switch still runs.
3745        step(&mut app, Vec2::new(50.0, 0.0), &[], 0.1);
3746        let p = app.world().entity(e).get::<Player>().unwrap();
3747        assert!(p.snap_anim.is_some(), "animation should still be running");
3748        assert_eq!(
3749            p.anchor_up,
3750            Vec3::Y,
3751            "yaw must not commit the pending anchor"
3752        );
3753        let after = forward_of(&app, e);
3754        // Yaw ran around the OLD anchor (world Y): a rotation about Y preserves
3755        // forward·Y, and the pending axis is non-Y, so a wrong anchor would
3756        // tilt forward out of the horizontal plane.
3757        assert!(
3758            after.dot(Vec3::Y).abs() < 1e-5,
3759            "yaw left the Y-plane → wrong anchor"
3760        );
3761        assert!(
3762            (after - before).length() > 1e-3,
3763            "yaw had no visible effect"
3764        );
3765    }
3766
3767    #[test]
3768    fn anchored_q_switches_anchor() {
3769        let (mut app, e) = anchored_app();
3770        // In SixDof this would roll the frame every tick; in Anchored, Q must
3771        // instead begin an animated anchor switch — RollMode is inert.
3772        step(&mut app, Vec2::ZERO, &[KeyCode::KeyQ], 0.1);
3773        let p = app.world().entity(e).get::<Player>().unwrap();
3774        assert!(
3775            p.snap_anim.is_some() && p.pending_anchor.is_some(),
3776            "Continuous roll_mode must be inert in Anchored — Q takes the switch path"
3777        );
3778    }
3779}