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