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, ACCEL * dt)`
18//! - **Decelerating** (no input): `velocity = lerp(velocity, Vec3::ZERO, DECEL * dt)`
19//!
20//! This gives snappy starts and a natural coast-to-stop feel without requiring a
21//! fixed physics timestep.
22//!
23//! # Quick start — [`PlayerPlugin`]
24//!
25//! The simplest integration: add [`PlayerPlugin`] and everything is wired
26//! automatically. Systems run unconditionally every frame.
27//!
28//! ```rust,no_run
29//! use bevy::prelude::*;
30//! use voxel_framework::prelude::*;
31//! use voxel_framework::player::PlayerPlugin;
32//!
33//! App::new()
34//! .add_plugins(DefaultPlugins)
35//! .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
36//! .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
37//! .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
38//! .run();
39//! ```
40//!
41//! # AppState integration — manual systems
42//!
43//! When your game has an `AppState` enum, skip [`PlayerPlugin`] and register the
44//! systems manually so they only run during gameplay:
45//!
46//! ```rust,no_run
47//! # use bevy::prelude::*;
48//! # use voxel_framework::player::{spawn_player, player_look, player_move, player_cursor_system};
49//! # use voxel_framework::player::player_resolve_collision;
50//! # use voxel_framework::voxel::DefaultVoxel;
51//! # #[derive(States, Default, Clone, PartialEq, Eq, Hash, Debug)]
52//! # enum AppState { #[default] Playing }
53//! App::new()
54//! .add_systems(Startup, spawn_player)
55//! .add_systems(Update,
56//! (player_look, player_move::<DefaultVoxel>, player_resolve_collision::<DefaultVoxel>)
57//! .chain()
58//! .run_if(in_state(AppState::Playing)),
59//! )
60//! .add_systems(Update, player_cursor_system);
61//! ```
62//!
63//! # Cursor management contract
64//!
65//! [`spawn_player`] leaves the cursor free. [`player_cursor_system`] manages
66//! the primary window's lock state without requesting OS keyboard focus:
67//!
68//! - **Left click** in the focused window while cursor is free → locks and hides it.
69//! - **Focus loss** → releases the cursor; returning requires another click.
70//! - **First Escape** while cursor is locked → releases cursor (makes it visible).
71//! - **Escape** while cursor is already free → closes the focused window.
72//!
73//! Look and movement require a focused primary window with a captured cursor.
74//! Headless calls without a primary window retain synthetic-input support.
75//!
76//! If you use [`PauseMenuPlugin`](crate::ui::PauseMenuPlugin) alongside this
77//! module, do **not** add [`player_cursor_system`] — the pause menu handles cursor
78//! management itself.
79//!
80//! # Controls
81//!
82//! | Input | Action |
83//! |--------------|-------------------------------------|
84//! | Mouse | Yaw + pitch (6DOF, no clamp) |
85//! | Q / E | Roll left / right |
86//! | W / S | Forward / backward |
87//! | A / D | Strafe left / right |
88//! | Space | Move along local up |
89//! | Shift | Move along local down |
90//! | Left click | Lock cursor |
91//! | Escape | Release cursor (if already free: close focused window) |
92
93use bevy::ecs::message::MessageWriter;
94use bevy::input::mouse::MouseMotion;
95use bevy::prelude::*;
96use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
97
98use crate::audio::{SfxEvent, SfxRequest};
99use crate::chunk::{CHUNK_SIZE, Chunk, VOXEL_SIZE};
100use crate::voxel::VoxelType;
101use crate::world::{ChunkManager, ViewerPosition, WorldDataDir, get_voxel_at};
102
103pub mod effects;
104pub mod persistence;
105
106// ─── Health & damage messages ─────────────────────────────────────────────────
107
108/// Emitted when the player takes damage from any source.
109#[derive(Message, Debug, Clone)]
110pub struct PlayerDamaged {
111 /// Amount of health points lost.
112 pub amount: f32,
113}
114
115/// Emitted when the player's health reaches zero and they respawn.
116#[derive(Message, Debug, Clone)]
117pub struct PlayerDied;
118
119/// Player health and respawn state.
120///
121/// Inserted as a resource by [`PlayerPlugin`]. Games can read and modify
122/// `health` directly (e.g. from environmental hazards); fall damage is applied
123/// automatically when landing with high vertical velocity.
124///
125/// When `health` drops to zero the player is teleported to `spawn_position`
126/// and health is restored to `max_health`. A [`PlayerDied`] message is sent.
127#[derive(Resource, Debug, Clone)]
128pub struct PlayerHealth {
129 /// Current health points. Clamped to `[0, max_health]` after damage.
130 pub health: f32,
131 /// Maximum health points. **Default: `20.0`.**
132 pub max_health: f32,
133 /// World position used for respawn on death.
134 ///
135 /// Defaults to the player's spawn position from [`PlayerConfig`]. Games
136 /// can update this at runtime (e.g. when placing a bed or checkpoint).
137 pub spawn_position: Vec3,
138 /// Vertical fall speed (m/s) below which no fall damage is taken.
139 ///
140 /// Impact speeds below this threshold deal zero damage. **Default: `10.0`.**
141 pub fall_safe_speed: f32,
142}
143
144impl Default for PlayerHealth {
145 fn default() -> Self {
146 Self {
147 health: 20.0,
148 max_health: 20.0,
149 spawn_position: Vec3::new(0.0, 30.0, 0.0),
150 fall_safe_speed: 10.0,
151 }
152 }
153}
154
155// ─── PlayerCrouching resource ─────────────────────────────────────────────────
156
157/// Tracks whether the player is currently crouching.
158///
159/// Updated every frame by [`player_move`] in [`PlayerMode::Grounded`] mode
160/// based on `ControlLeft` key state. Readable by external systems (e.g. UI,
161/// animation) without querying the [`Player`] component directly.
162///
163/// The resource mirrors [`Player::crouching`] and is kept in sync by
164/// [`player_move`] each frame. Modifying it directly has no effect — it is
165/// overwritten by the movement system.
166#[derive(Resource, Default, Debug, Clone, Copy, PartialEq, Eq)]
167pub struct PlayerCrouching(pub bool);
168
169// ─── PlayerMode ──────────────────────────────────────────────────────────────
170
171/// Selects the movement model used by [`PlayerPlugin`] and the player systems.
172///
173/// Set this inside [`PlayerConfig::mode`] before adding [`PlayerPlugin`] (or
174/// before the `Startup` schedule runs). Changing the mode at runtime is
175/// **not** supported — the value is copied into the [`Player`] component once
176/// on spawn and used from there.
177///
178/// # Variants
179///
180/// - [`PlayerMode::FreeFlightSixDof`] — classic 6DOF, no gravity. Default.
181/// - [`PlayerMode::FreeFlightAnchored`] — free flight with a world-axis-anchored horizon.
182/// - [`PlayerMode::Grounded`] — gravity + jump, WASD on the XZ plane, pitch
183/// clamped to ±89°. Suitable for Minetest / Minecraft–style games.
184#[derive(Debug, Clone)]
185pub enum PlayerMode {
186 /// Six-degrees-of-freedom flight. No gravity, no pitch clamp, Q/E roll.
187 ///
188 /// This is the default mode and matches the original behaviour of the
189 /// player controller. All six movement axes (forward, back, left, right,
190 /// up, down) are relative to the camera's current orientation.
191 FreeFlightSixDof {
192 /// How Q/E roll input is applied.
193 roll_mode: RollMode,
194 },
195 /// Six-degrees-of-freedom flight with an FPS-style, world-axis-anchored
196 /// horizon. Q/E switch the anchor axis instead of rolling.
197 FreeFlightAnchored,
198 /// Gravity-based grounded movement.
199 ///
200 /// - WASD moves on the **world XZ plane** relative to the camera's current
201 /// yaw, ignoring pitch tilt.
202 /// - `Space` jumps when [`Player::on_ground`] is `true`.
203 /// - Gravity accumulates in [`Player::vertical_velocity`] each frame.
204 /// - Mouse yaw rotates the entity around the **world Y axis** (player stays
205 /// upright); pitch rotates the view up/down and is clamped to ±89°.
206 /// - Q/E roll is disabled.
207 Grounded {
208 /// Downward acceleration in world units per second squared.
209 ///
210 /// Applied every frame as `vertical_velocity -= gravity * dt`.
211 /// Typical value: `20.0`.
212 gravity: f32,
213 /// Upward velocity impulse applied when the player jumps.
214 ///
215 /// Assigned to [`Player::vertical_velocity`] on the frame `Space` is
216 /// pressed while [`Player::on_ground`] is `true`. Typical value: `8.0`.
217 jump_speed: f32,
218 },
219}
220
221impl Default for PlayerMode {
222 fn default() -> Self {
223 PlayerMode::FreeFlightSixDof {
224 roll_mode: RollMode::Continuous,
225 }
226 }
227}
228
229// ─── Physics constants ────────────────────────────────────────────────────────
230
231/// Radius of the player's collision capsule in world units (≈ 0.6 voxels).
232///
233/// Each hemispherical end cap of the capsule has this radius. The value keeps
234/// the player from clipping single-voxel corners while still fitting through
235/// one-voxel-wide gaps when combined with [`PLAYER_HALF_HEIGHT`].
236pub const PLAYER_RADIUS: f32 = 0.6;
237
238/// Half-height of the capsule's cylindrical spine in world units (≈ 1.8 voxels).
239///
240/// The spine runs along the player's local Y axis between offsets
241/// `−PLAYER_HALF_HEIGHT` and `+PLAYER_HALF_HEIGHT` from the entity origin.
242/// The total capsule height is `2 × (PLAYER_HALF_HEIGHT + PLAYER_RADIUS)` ≈ 4.8
243/// world units. In 6DOF mode this axis rolls with the player's orientation.
244pub const PLAYER_HALF_HEIGHT: f32 = 1.8;
245
246/// Half-height of the capsule when crouching (≈ 60% of normal).
247///
248/// Reduces the total capsule height enough to let the player pass through
249/// gaps that are one voxel tall. Used by [`player_resolve_collision`] when
250/// [`Player::crouching`] is `true` in [`PlayerMode::Grounded`] mode.
251pub const CROUCH_HALF_HEIGHT: f32 = PLAYER_HALF_HEIGHT * 0.6;
252
253/// Speed multiplier applied to horizontal movement while sprinting.
254///
255/// Active in [`PlayerMode::Grounded`] when `Shift` is held and the player is
256/// on solid ground. Crouch takes priority — if both are held this multiplier
257/// is not applied. See [`player_move`] and [`PlayerCrouching`].
258pub const SPRINT_MULTIPLIER: f32 = 1.6;
259
260/// Lerp factor applied when the player is accelerating.
261const ACCEL: f32 = 12.0;
262
263/// Lerp factor applied when the player is decelerating (no input).
264const DECEL: f32 = 7.0;
265
266/// Internal mouse scale factor applied before the user-facing
267/// [`Player::sensitivity`] multiplier.
268///
269/// Mouse deltas arrive in pixels (often `10+` per frame) so a raw multiplier of
270/// `1.0` would spin the camera wildly. This constant converts pixels to a base
271/// rad/px rate comparable to Minecraft, so that `sensitivity = 1.0` feels
272/// "normal". Users scale around this via the Settings slider (10% → very slow,
273/// 100% → default, above 100% would be faster but the slider caps there).
274const MOUSE_SCALE: f32 = 0.003;
275
276// ─── Snap roll types ─────────────────────────────────────────────────────────
277
278/// Selects how Q/E roll input is applied in [`PlayerMode::FreeFlightSixDof`].
279///
280/// - [`RollMode::Continuous`] — roll while the key is held (original behavior).
281/// - [`RollMode::Snap`] — each key press animates a snap rotation to the
282/// next world-aligned up candidate (a signed world axis projected onto the
283/// roll plane).
284///
285/// Configured by `PlayerMode::FreeFlightSixDof { roll_mode }`; defaults to
286/// [`RollMode::Continuous`].
287///
288/// Ignored by [`PlayerMode::FreeFlightAnchored`]: in anchored flight Q/E switch
289/// the anchor axis instead of rolling.
290#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
291pub enum RollMode {
292 /// Roll continuously while Q/E is held (default, original behavior).
293 #[default]
294 Continuous,
295 /// Snap-rotate to the next world-aligned up candidate per key press with
296 /// easing animation (90° steps when forward is on a world axis).
297 Snap,
298}
299
300/// Easing curve used by [`RollMode::Snap`] animations.
301///
302/// Each variant maps to a simple `f(t) -> f32` curve where `t ∈ [0, 1]`.
303/// The default ([`EaseOutCubic`](SnapRollEasing::EaseOutCubic)) gives a snappy
304/// start that decelerates smoothly.
305#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
306pub enum SnapRollEasing {
307 /// `1 − (1 − t)³` — fast start, smooth deceleration (default).
308 #[default]
309 EaseOutCubic,
310 /// `1 − (1 − t)⁴` — slightly slower deceleration than cubic.
311 EaseOutQuart,
312 /// `t² (3 − 2t)` — symmetric S-curve.
313 Smoothstep,
314 /// `t` — constant angular velocity.
315 Linear,
316}
317
318/// Runtime state for an in-progress snap-roll animation.
319///
320/// Stored in [`Player::snap_anim`]. Created by [`start_or_retarget_snap`],
321/// advanced each frame by [`advance_snap`], and cleared when `finished`.
322///
323/// Angles are *relative* to the orientation captured at press time: the
324/// world-aligned candidate is resolved once by [`start_or_retarget_snap`]
325/// (via [`world_lattice_angles`] / [`next_lattice_step`]) and baked into
326/// `target_angle`; the animation then only applies angle differences through
327/// `rotate_local_z`.
328#[derive(Copy, Clone, Debug)]
329pub(crate) struct SnapRollAnim {
330 pub(crate) start_angle: f32,
331 pub(crate) target_angle: f32,
332 pub(crate) elapsed: f32,
333 pub(crate) duration: f32,
334 pub(crate) easing: SnapRollEasing,
335 pub(crate) current_applied: f32,
336}
337
338/// Minimum squared projection length a world axis needs on the roll plane to
339/// count as a lattice candidate in [`world_lattice_angles`]. Keeps an axis
340/// only when it lies ~45° or more away from local Z, so the axis pair the
341/// player is (roughly) looking along never yields near-degenerate up stops —
342/// a mostly-axis-aligned view gives 4 candidates, while a diagonal view (all
343/// axes at ~54.7°) keeps all 6. The constant is `0.49` rather than the exact
344/// `sin²(45°) = 0.5`: on a perfect 45° edge-on view both axis families sit at
345/// projection² ≈ 0.5 and float rounding could otherwise exclude BOTH,
346/// breaking the ≥4-candidate invariant.
347pub(crate) const SNAP_MIN_PROJ_SQ: f32 = 0.49;
348
349/// Angular tolerance in radians within which the reference up already lies ON
350/// a candidate; [`next_lattice_step`] skips that candidate so a press always
351/// produces visible motion (EPS_ON rule).
352pub(crate) const SNAP_EPS_ON: f32 = 1e-3;
353
354// ─── Component ───────────────────────────────────────────────────────────────
355
356/// State component that marks the player camera entity.
357///
358/// Attach this alongside [`Camera3d`] on a single entity. The camera entity
359/// IS the player — there is no separate logical-player / camera hierarchy.
360/// All player systems query for this component to locate the controlled entity.
361///
362/// Prefer constructing through [`PlayerConfig`] via [`spawn_player`] rather
363/// than inserting [`Player`] directly, which also sets the initial transform and
364/// projection from the resource.
365///
366/// # Default values
367///
368/// | Field | Default |
369/// |---------------|----------|
370/// | `speed` | `4.0` |
371/// | `sensitivity` | `1.0` |
372/// | `roll_speed` | `1.5` |
373/// | `velocity` | `ZERO` |
374#[derive(Component, Debug, Clone)]
375pub struct Player {
376 /// Maximum flight speed in world units per second. Clamped implicitly by
377 /// the lerp target: actual speed never exceeds this value regardless of
378 /// frame rate.
379 pub speed: f32,
380 /// Mouse sensitivity multiplier (dimensionless). `1.0` matches the default
381 /// "Minecraft-like" feel via the internal `MOUSE_SCALE` constant; lower
382 /// values are slower, higher values are faster. The Settings slider exposes
383 /// the range `0.10`–`1.00` (10%–100%) to the user.
384 pub sensitivity: f32,
385 /// Roll angular speed in radians per second applied while Q (roll left) or
386 /// E (roll right) is held.
387 pub roll_speed: f32,
388 /// Current world-space velocity in world units per second. Smoothed each
389 /// frame by [`player_move`] using an exponential lerp; do not set this
390 /// directly unless you want to override the current momentum.
391 pub velocity: Vec3,
392 /// Movement mode, copied from [`PlayerConfig::mode`] on spawn.
393 ///
394 /// Determines which branch of [`player_look`], [`player_move`], and
395 /// [`player_resolve_collision`] is executed each frame.
396 pub mode: PlayerMode,
397 /// Vertical velocity used in [`PlayerMode::Grounded`] mode.
398 ///
399 /// Gravity accumulates here each frame; a jump impulse sets it to
400 /// [`PlayerMode::Grounded::jump_speed`]. Reset to `0.0` when the player
401 /// lands (collision pushes upward). Unused in [`PlayerMode::FreeFlightSixDof`].
402 pub vertical_velocity: f32,
403 /// Whether the player was on solid ground at the end of the last frame.
404 ///
405 /// Set to `true` by [`player_resolve_collision`] when a voxel collision
406 /// produces an upward push; cleared to `false` at the start of each
407 /// collision pass. Gating jumps on this flag prevents infinite jumping.
408 /// Unused in [`PlayerMode::FreeFlightSixDof`].
409 pub on_ground: bool,
410 /// Absolute landing speed (m/s) recorded when the player just touched ground.
411 ///
412 /// Set by [`player_resolve_collision`] on the first landing frame;
413 /// zero at all other times. Read by [`player_fall_damage`] to compute
414 /// and apply damage. Only meaningful in [`PlayerMode::Grounded`].
415 pub(crate) impact_speed: f32,
416 /// Accumulated seconds since the last footstep sound was emitted.
417 ///
418 /// Managed by [`player_footstep_system`]. Reset to `0.0` after each
419 /// footstep; only meaningful in [`PlayerMode::Grounded`].
420 pub(crate) footstep_timer: f32,
421 /// Whether the initial chunk load has completed.
422 ///
423 /// Set to `false` on spawn; flipped to `true` in `player_resolve_collision`
424 /// once the chunk at the player's feet is registered in [`ChunkManager`].
425 /// While `false`, gravity is suppressed so the player does not fall through
426 /// un-loaded terrain during world generation.
427 pub(crate) world_loaded: bool,
428 /// `true` until the player's first landing after spawn (or respawn).
429 ///
430 /// Skips fall-damage on that landing so a spawn point slightly above the
431 /// terrain surface does not instantly kill the player. Cleared on first
432 /// contact with solid ground.
433 pub(crate) spawn_immune: bool,
434 /// Whether the player is currently sprinting.
435 ///
436 /// `true` when `Shift` is held in [`PlayerMode::Grounded`] with
437 /// [`Player::on_ground`] `true`, and [`Player::crouching`] is `false`.
438 /// Crouch takes priority: if both are held this is `false`.
439 /// Always `false` in [`PlayerMode::FreeFlightSixDof`].
440 pub sprinting: bool,
441 /// Whether the player is currently crouching.
442 ///
443 /// `true` when `Ctrl` is held in [`PlayerMode::Grounded`] mode.
444 /// Reduces the effective capsule half-height to [`CROUCH_HALF_HEIGHT`]
445 /// and movement speed to 40% of base speed.
446 /// Always `false` in [`PlayerMode::FreeFlightSixDof`].
447 pub crouching: bool,
448 /// Duration in seconds for a single snap-roll step animation (one hop to
449 /// the next world-aligned up candidate).
450 /// Only used when `roll_mode == RollMode::Snap`. **Default: `0.5`.**
451 pub snap_roll_duration: f32,
452 /// Easing curve for snap-roll animations.
453 /// Only used when `roll_mode == RollMode::Snap`.
454 pub snap_roll_easing: SnapRollEasing,
455 /// Active snap-roll animation state (runtime-only, not persisted).
456 pub(crate) snap_anim: Option<SnapRollAnim>,
457 /// Current anchor axis for [`PlayerMode::FreeFlightAnchored`] look: always one of the
458 /// 6 signed world axes. Yaw orbits this axis; pitch is clamped to ±89°
459 /// from the plane perpendicular to it. Initialized on spawn to the signed
460 /// world axis nearest the spawn orientation's up. Unused in
461 /// [`PlayerMode::FreeFlightSixDof`].
462 pub anchor_up: Vec3,
463 /// Source signed world axis of an in-flight anchor switch, committed to
464 /// [`Player::anchor_up`] when the animation finishes (runtime-only).
465 pub(crate) pending_anchor: Option<Vec3>,
466}
467
468impl Default for Player {
469 fn default() -> Self {
470 Self {
471 speed: 4.0,
472 sensitivity: 1.0,
473 roll_speed: 1.5,
474 velocity: Vec3::ZERO,
475 mode: PlayerMode::default(),
476 vertical_velocity: 0.0,
477 on_ground: false,
478 impact_speed: 0.0,
479 footstep_timer: 0.0,
480 world_loaded: false,
481 spawn_immune: true,
482 sprinting: false,
483 crouching: false,
484 snap_roll_duration: 0.5,
485 snap_roll_easing: SnapRollEasing::EaseOutCubic,
486 snap_anim: None,
487 anchor_up: Vec3::Y,
488 pending_anchor: None,
489 }
490 }
491}
492
493// ─── Configuration resource ───────────────────────────────────────────────────
494
495/// Startup configuration for [`spawn_player`].
496///
497/// Insert this resource before [`PlayerPlugin`] (or before the `Startup`
498/// schedule runs) to override any default. Fields are consumed once by
499/// [`spawn_player`]; changing the resource after spawn has no effect.
500///
501/// # Example
502///
503/// ```rust,no_run
504/// use bevy::prelude::*;
505/// use voxel_framework::player::PlayerConfig;
506///
507/// App::new()
508/// .insert_resource(PlayerConfig {
509/// spawn_position: Vec3::new(0.0, 50.0, 150.0),
510/// speed: 8.0,
511/// fov_degrees: 80.0,
512/// ..Default::default()
513/// });
514/// ```
515///
516/// # Default values
517///
518/// | Field | Default |
519/// |-----------------|---------------------------|
520/// | `spawn_position`| `(0.0, 0.0, 30.0)` |
521/// | `speed` | `4.0` wu/s |
522/// | `sensitivity` | `1.0` (unitless multiplier) |
523/// | `roll_speed` | `1.5` rad/s |
524/// | `look_at` | `Vec3::ZERO` |
525/// | `fov_degrees` | `90.0` |
526#[derive(Resource, Debug, Clone)]
527pub struct PlayerConfig {
528 /// World-space position at which the player entity is spawned.
529 pub spawn_position: Vec3,
530 /// Maximum flight speed in world units per second. Copied into
531 /// [`Player::speed`] on spawn.
532 pub speed: f32,
533 /// Mouse sensitivity multiplier (dimensionless). Copied into
534 /// [`Player::sensitivity`] on spawn. `1.0` = default "Minecraft-like" feel;
535 /// see `MOUSE_SCALE` for the underlying rad/px rate.
536 pub sensitivity: f32,
537 /// Roll angular speed in radians per second. Copied into
538 /// [`Player::roll_speed`] on spawn.
539 pub roll_speed: f32,
540 /// World-space point the camera looks toward immediately after spawning.
541 /// Only affects the initial orientation; the player can look anywhere
542 /// afterwards via mouse input.
543 pub look_at: Vec3,
544 /// Vertical field-of-view in degrees. Valid range: `50.0`–`120.0`.
545 /// Converted to radians and stored in the [`PerspectiveProjection`] on
546 /// spawn; runtime changes must be made directly on the [`Projection`]
547 /// component (e.g., via the Settings menu).
548 pub fov_degrees: f32,
549 /// Movement model used by the player systems.
550 ///
551 /// Defaults to [`PlayerMode::FreeFlightSixDof`] for backwards compatibility.
552 /// Set to [`PlayerMode::Grounded`] for gravity-based gameplay.
553 pub mode: PlayerMode,
554 /// Duration in seconds for a single snap-roll step animation (one hop to
555 /// the next world-aligned up candidate).
556 /// Copied into [`Player::snap_roll_duration`] on spawn. **Default: `0.5`.**
557 pub snap_roll_duration_secs: f32,
558 /// Easing curve for snap-roll animations.
559 /// Copied into [`Player::snap_roll_easing`] on spawn.
560 pub snap_roll_easing: SnapRollEasing,
561}
562
563impl Default for PlayerConfig {
564 fn default() -> Self {
565 Self {
566 spawn_position: Vec3::new(0.0, 0.0, 30.0),
567 speed: 4.0,
568 sensitivity: 1.0,
569 roll_speed: 1.5,
570 look_at: Vec3::ZERO,
571 fov_degrees: 90.0,
572 mode: PlayerMode::default(),
573 snap_roll_duration_secs: 0.5,
574 snap_roll_easing: SnapRollEasing::EaseOutCubic,
575 }
576 }
577}
578
579// ─── Systems ──────────────────────────────────────────────────────────────────
580
581/// Spawns the player camera entity configured by [`PlayerConfig`].
582///
583/// This system is **idempotent**: if a [`Player`] entity already exists in the
584/// world it returns immediately without spawning a second one. This makes it
585/// safe to register on `Startup` even when transitioning through `AppState`
586/// variants that re-enter the startup flow.
587///
588/// Leaves the cursor free. A focused left click through [`player_cursor_system`]
589/// activates native player input; pointer capture never grants keyboard focus.
590pub fn spawn_player(
591 mut commands: Commands,
592 config: Res<PlayerConfig>,
593 existing: Query<(), With<Player>>,
594 mut health: ResMut<PlayerHealth>,
595) {
596 if !existing.is_empty() {
597 return;
598 }
599
600 // Sync spawn_position with the configured spawn so respawn lands in the right place.
601 health.spawn_position = config.spawn_position;
602
603 let spawn = config.spawn_position;
604 let look_at = config.look_at;
605 let fov = config.fov_degrees.to_radians();
606 let mode = config.mode.clone();
607
608 // Build the transform first so the anchor axis can be derived from the
609 // actual spawn orientation.
610 let transform = Transform::from_translation(spawn).looking_at(look_at, Vec3::Y);
611
612 commands.spawn((
613 Player {
614 speed: config.speed,
615 sensitivity: config.sensitivity,
616 roll_speed: config.roll_speed,
617 velocity: Vec3::ZERO,
618 mode,
619 vertical_velocity: 0.0,
620 on_ground: false,
621 impact_speed: 0.0,
622 footstep_timer: 0.0,
623 world_loaded: false,
624 spawn_immune: true,
625 sprinting: false,
626 crouching: false,
627 snap_roll_duration: config.snap_roll_duration_secs,
628 snap_roll_easing: config.snap_roll_easing,
629 snap_anim: None,
630 anchor_up: nearest_world_axis(*transform.up()),
631 pending_anchor: None,
632 },
633 Camera3d::default(),
634 Projection::Perspective(PerspectiveProjection { fov, ..default() }),
635 transform,
636 ));
637}
638
639// ─── Snap roll helpers ──────────────────────────────────────────────────────
640
641pub(crate) fn apply_easing(t: f32, easing: SnapRollEasing) -> f32 {
642 match easing {
643 SnapRollEasing::EaseOutCubic => 1.0 - (1.0 - t).powi(3),
644 SnapRollEasing::EaseOutQuart => 1.0 - (1.0 - t).powi(4),
645 SnapRollEasing::Smoothstep => t * t * (3.0 - 2.0 * t),
646 SnapRollEasing::Linear => t,
647 }
648}
649
650/// The 6 signed world axes in canonical order.
651///
652/// The order is load-bearing: it is the candidate iteration order of
653/// [`world_lattice_candidates`] and the deterministic tie-break sequence of
654/// [`nearest_world_axis`] (first-in-order wins).
655pub(crate) const AXES: [Vec3; 6] = [
656 Vec3::X,
657 Vec3::NEG_X,
658 Vec3::Y,
659 Vec3::NEG_Y,
660 Vec3::Z,
661 Vec3::NEG_Z,
662];
663
664/// Like [`world_lattice_angles`] but returns `(angle δ, SOURCE signed world
665/// axis)` per surviving candidate.
666///
667/// The candidate set is the 6 signed world axes ([`AXES`]) projected onto
668/// the plane perpendicular to `local_z` and normalized. Axes whose projection
669/// has length² < [`SNAP_MIN_PROJ_SQ`] are excluded — an axis within 45° of
670/// the roll axis is "the one you are looking along" and would yield a
671/// perceptually arbitrary up stop (at least 4 candidates always survive).
672/// Each angle is `δ = atan2(cross(up, c) · local_z, up · c)` — the
673/// [`Transform::rotate_local_z`] convention, so δ feeds it unmodified.
674pub(crate) fn world_lattice_candidates(local_z: Vec3, up: Vec3) -> Vec<(f32, Vec3)> {
675 let mut candidates = Vec::with_capacity(6);
676 for axis in AXES {
677 let proj = axis - axis.dot(local_z) * local_z;
678 if proj.length_squared() < SNAP_MIN_PROJ_SQ {
679 continue;
680 }
681 let c = proj.normalize();
682 candidates.push((up.cross(c).dot(local_z).atan2(up.dot(c)), axis));
683 }
684 candidates
685}
686
687/// Signed roll angles δ ∈ (−π, π] from `up` to each surviving world-axis
688/// candidate around the roll axis `local_z` (Bevy's BACK vector).
689///
690/// Thin wrapper over [`world_lattice_candidates`] that drops each candidate's
691/// source axis — see that function for the lattice rule.
692pub(crate) fn world_lattice_angles(local_z: Vec3, up: Vec3) -> Vec<f32> {
693 world_lattice_candidates(local_z, up)
694 .into_iter()
695 .map(|(a, _)| a)
696 .collect()
697}
698
699/// Next lattice step in press direction `dir` (+1 = Q / CCW, −1 = E / CW).
700///
701/// dir > 0 → min over `{δ > SNAP_EPS_ON ? δ : δ + TAU}`;
702/// dir < 0 → max over `{δ < −SNAP_EPS_ON ? δ : δ − TAU}`.
703/// Candidates within [`SNAP_EPS_ON`] of the reference up wrap a full turn
704/// (EPS_ON rule), so the result is always a nonzero signed angle.
705pub(crate) fn next_lattice_step(angles: &[f32], dir: i32) -> f32 {
706 use std::f32::consts::TAU;
707 if dir > 0 {
708 angles
709 .iter()
710 .map(|&d| if d > SNAP_EPS_ON { d } else { d + TAU })
711 .fold(f32::INFINITY, f32::min)
712 } else {
713 angles
714 .iter()
715 .map(|&d| if d < -SNAP_EPS_ON { d } else { d - TAU })
716 .fold(f32::NEG_INFINITY, f32::max)
717 }
718}
719
720/// Mirror of [`next_lattice_step`] carrying each candidate's source axis:
721/// same [`SNAP_EPS_ON`] wrap, min (dir > 0) / max (dir < 0) by wrapped angle.
722/// Returns the wrapped angle together with the winning candidate's SOURCE
723/// signed world axis.
724///
725/// The caller guarantees a non-empty slice (the [`SNAP_MIN_PROJ_SQ`]
726/// ≥4-candidate invariant); panics otherwise rather than returning garbage.
727pub(crate) fn next_lattice_candidate(cands: &[(f32, Vec3)], dir: i32) -> (f32, Vec3) {
728 use std::f32::consts::TAU;
729 assert!(
730 !cands.is_empty(),
731 "next_lattice_candidate: empty candidate slice — SNAP_MIN_PROJ_SQ \
732 guarantees at least 4 lattice candidates"
733 );
734 if dir > 0 {
735 cands
736 .iter()
737 .map(|&(d, axis)| (if d > SNAP_EPS_ON { d } else { d + TAU }, axis))
738 .min_by(|a, b| a.0.total_cmp(&b.0))
739 .unwrap()
740 } else {
741 cands
742 .iter()
743 .map(|&(d, axis)| (if d < -SNAP_EPS_ON { d } else { d - TAU }, axis))
744 .max_by(|a, b| a.0.total_cmp(&b.0))
745 .unwrap()
746 }
747}
748
749/// Builds (or retargets) a snap-roll animation toward the next world-aligned
750/// up candidate in press direction `dir`.
751///
752/// `local_z` / `up` are `*transform.local_z()` / `*transform.up()` at press
753/// time. Every press resolves through one primitive — "next candidate in
754/// direction `dir` from a reference up" ([`world_lattice_angles`] +
755/// [`next_lattice_step`]):
756///
757/// - **Fresh press** — reference = `up`; the animation starts at `0.0`
758/// toward the first step.
759/// - **Same direction mid-animation** — reference = the in-flight target up
760/// (`up` advanced by the not-yet-applied residual; exact because
761/// `up ⊥ local_z`); retargets one candidate further, resuming from the
762/// currently applied angle.
763/// - **Opposite direction mid-animation** — reference = `up`; reverses to
764/// the nearest candidate behind, resuming from the currently applied angle.
765///
766/// The target is fixed here at press time and never re-resolved mid-flight.
767/// Angles stay relative: [`advance_snap`] applies only differences via
768/// `rotate_local_z`, so the animation lands exactly on the world candidate
769/// computed from `local_z` / `up`.
770pub(crate) fn start_or_retarget_snap(
771 existing: Option<SnapRollAnim>,
772 local_z: Vec3,
773 up: Vec3,
774 dir: i32,
775 duration: f32,
776 easing: SnapRollEasing,
777) -> SnapRollAnim {
778 match existing {
779 None => {
780 let step = next_lattice_step(&world_lattice_angles(local_z, up), dir);
781 SnapRollAnim {
782 start_angle: 0.0,
783 target_angle: step,
784 elapsed: 0.0,
785 duration,
786 easing,
787 current_applied: 0.0,
788 }
789 }
790 Some(anim) => {
791 let same_dir = (dir > 0 && anim.target_angle > anim.start_angle)
792 || (dir < 0 && anim.target_angle < anim.start_angle);
793
794 if same_dir {
795 // Reference = in-flight target up: advance `up` by the
796 // not-yet-applied residual, then extend one candidate further.
797 let residual = anim.target_angle - anim.current_applied;
798 let ref_up = Quat::from_axis_angle(local_z, residual) * up;
799 let step = next_lattice_step(&world_lattice_angles(local_z, ref_up), dir);
800 SnapRollAnim {
801 start_angle: anim.current_applied,
802 target_angle: anim.target_angle + step,
803 elapsed: 0.0,
804 duration,
805 easing,
806 current_applied: anim.current_applied,
807 }
808 } else {
809 // Opposite direction: nearest candidate behind current up.
810 let step = next_lattice_step(&world_lattice_angles(local_z, up), dir);
811 SnapRollAnim {
812 start_angle: anim.current_applied,
813 target_angle: anim.current_applied + step,
814 elapsed: 0.0,
815 duration,
816 easing,
817 current_applied: anim.current_applied,
818 }
819 }
820 }
821 }
822}
823
824/// The reference up [`start_or_retarget_snap`] resolves candidates from,
825/// replicated as a pure helper so the Anchored arm can compute the SOURCE
826/// axis of the exact candidate the animation will land on:
827///
828/// - Same direction mid-animation → `up` advanced by the not-yet-applied
829/// residual (`Quat::from_axis_angle(local_z, target − applied) * up`).
830/// - Fresh press or opposite direction → `up` unchanged.
831pub(crate) fn snap_reference_up(
832 existing: Option<SnapRollAnim>,
833 local_z: Vec3,
834 up: Vec3,
835 dir: i32,
836) -> Vec3 {
837 match existing {
838 Some(anim) => {
839 let same_dir = (dir > 0 && anim.target_angle > anim.start_angle)
840 || (dir < 0 && anim.target_angle < anim.start_angle);
841 if same_dir {
842 let residual = anim.target_angle - anim.current_applied;
843 Quat::from_axis_angle(local_z, residual) * up
844 } else {
845 up
846 }
847 }
848 None => up,
849 }
850}
851
852/// Clamps a pitch delta so `asin(forward · anchor_up)` stays within ±89°.
853///
854/// `pitch = asin(clamp(forward · anchor_up, −1, 1))`; returns
855/// `clamp(pitch + pitch_d, ±89°) − pitch`. The clamp-then-subtract form gives
856/// exact truncation at the poles for free: at the limit, outward deltas
857/// return 0 while inward deltas pass through. Pure and NaN-free (the dot is
858/// clamped to asin's domain).
859pub(crate) fn clamp_pitch_delta(forward: Vec3, anchor_up: Vec3, pitch_d: f32) -> f32 {
860 let limit = 89_f32.to_radians();
861 let pitch = forward.dot(anchor_up).clamp(-1.0, 1.0).asin();
862 (pitch + pitch_d).clamp(-limit, limit) - pitch
863}
864
865/// Signed world axis with the maximum dot product against `v`.
866///
867/// Iterates [`AXES`] in canonical order keeping the max with strict `>`, so
868/// ties break deterministically toward the first axis in the order
869/// `[X, NEG_X, Y, NEG_Y, Z, NEG_Z]`. Used to initialize
870/// [`Player::anchor_up`] at spawn.
871pub(crate) fn nearest_world_axis(v: Vec3) -> Vec3 {
872 let mut best = AXES[0];
873 let mut best_dot = v.dot(AXES[0]);
874 for axis in AXES.into_iter().skip(1) {
875 let d = v.dot(axis);
876 if d > best_dot {
877 best = axis;
878 best_dot = d;
879 }
880 }
881 best
882}
883
884pub(crate) fn advance_snap(anim: &mut SnapRollAnim, dt: f32) -> (f32, bool) {
885 anim.elapsed += dt;
886 let t = (anim.elapsed / anim.duration).clamp(0.0, 1.0);
887 let eased = apply_easing(t, anim.easing);
888 let total = anim.start_angle + (anim.target_angle - anim.start_angle) * eased;
889 let delta = total - anim.current_applied;
890 anim.current_applied = total;
891 let finished = anim.elapsed >= anim.duration;
892 if finished {
893 // Snap exactly to target to avoid FP residue
894 let correction = anim.target_angle - anim.current_applied;
895 anim.current_applied = anim.target_angle;
896 return (delta + correction, true);
897 }
898 (delta, false)
899}
900
901/// Updates the player orientation from mouse movement and Q/E roll keys.
902///
903/// Implements **true 6DOF rotation** with no pitch clamp. Each axis rotates
904/// around the entity's *local* frame:
905///
906/// - Mouse X → `rotate_local_y` (yaw relative to current up)
907/// - Mouse Y → `rotate_local_x` (pitch relative to current right)
908/// - Q / E → `rotate_local_z` (roll at [`Player::roll_speed`] rad/s)
909///
910/// Rotating in local space means all three axes compose correctly regardless
911/// of the accumulated orientation — the player can pitch past vertical, roll
912/// upside-down, and continue steering intuitively without gimbal lock.
913///
914/// All [`MouseMotion`] events for the frame are accumulated into a single
915/// delta before applying rotation, preventing inter-frame jitter at high
916/// polling rates.
917pub fn player_look(
918 mut query: Query<(&mut Player, &mut Transform)>,
919 mut mouse_motion: MessageReader<MouseMotion>,
920 keys: Res<ButtonInput<KeyCode>>,
921 time: Res<Time>,
922 windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>,
923) {
924 if !player_input_active(windows) {
925 mouse_motion.clear();
926 return;
927 }
928 let Ok((mut player, mut transform)) = query.single_mut() else {
929 return;
930 };
931
932 // Accumulate mouse delta for this frame.
933 let mut delta = Vec2::ZERO;
934 for event in mouse_motion.read() {
935 delta += event.delta;
936 }
937
938 match &player.mode {
939 PlayerMode::FreeFlightSixDof { roll_mode } => {
940 if delta != Vec2::ZERO {
941 let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
942 let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
943 // Rotate around LOCAL axes — preserves 6DOF orientation.
944 transform.rotate_local_y(yaw_d);
945 transform.rotate_local_x(pitch_d);
946 }
947
948 // Q / E roll.
949 match roll_mode {
950 RollMode::Continuous => {
951 let mut roll = 0.0_f32;
952 if keys.pressed(KeyCode::KeyQ) {
953 roll += 1.0;
954 }
955 if keys.pressed(KeyCode::KeyE) {
956 roll -= 1.0;
957 }
958 if roll != 0.0 {
959 transform.rotate_local_z(roll * player.roll_speed * time.delta_secs());
960 }
961 }
962 RollMode::Snap => {
963 if keys.just_pressed(KeyCode::KeyQ) {
964 player.snap_anim = Some(start_or_retarget_snap(
965 player.snap_anim,
966 *transform.local_z(),
967 *transform.up(),
968 1,
969 player.snap_roll_duration,
970 player.snap_roll_easing,
971 ));
972 }
973 if keys.just_pressed(KeyCode::KeyE) {
974 player.snap_anim = Some(start_or_retarget_snap(
975 player.snap_anim,
976 *transform.local_z(),
977 *transform.up(),
978 -1,
979 player.snap_roll_duration,
980 player.snap_roll_easing,
981 ));
982 }
983 if let Some(ref mut anim) = player.snap_anim {
984 let (delta, finished) = advance_snap(anim, time.delta_secs());
985 transform.rotate_local_z(delta);
986 if finished {
987 player.snap_anim = None;
988 }
989 }
990 }
991 }
992 }
993 PlayerMode::FreeFlightAnchored => {
994 if delta != Vec2::ZERO {
995 let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
996 let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
997 // Yaw: WORLD-space rotation around the anchor axis. While a
998 // switch animation runs this is still the OLD anchor —
999 // pending_anchor is only committed on finish.
1000 transform.rotate(Quat::from_axis_angle(player.anchor_up, yaw_d));
1001 // Pitch: local-X rotation, clamped so the elevation against
1002 // the anchor stays within ±89°.
1003 let clamped = clamp_pitch_delta(*transform.forward(), player.anchor_up, pitch_d);
1004 transform.rotate_local_x(clamped);
1005 }
1006
1007 // Q / E: switch the anchor to the next lattice candidate
1008 // (RollMode is ignored in Anchored look).
1009 if keys.just_pressed(KeyCode::KeyQ) {
1010 let local_z = *transform.local_z();
1011 let up = *transform.up();
1012 let ref_up = snap_reference_up(player.snap_anim, local_z, up, 1);
1013 let (_, axis) =
1014 next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
1015 player.pending_anchor = Some(axis);
1016 player.snap_anim = Some(start_or_retarget_snap(
1017 player.snap_anim,
1018 local_z,
1019 up,
1020 1,
1021 player.snap_roll_duration,
1022 player.snap_roll_easing,
1023 ));
1024 }
1025 if keys.just_pressed(KeyCode::KeyE) {
1026 let local_z = *transform.local_z();
1027 let up = *transform.up();
1028 let ref_up = snap_reference_up(player.snap_anim, local_z, up, -1);
1029 let (_, axis) =
1030 next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), -1);
1031 player.pending_anchor = Some(axis);
1032 player.snap_anim = Some(start_or_retarget_snap(
1033 player.snap_anim,
1034 local_z,
1035 up,
1036 -1,
1037 player.snap_roll_duration,
1038 player.snap_roll_easing,
1039 ));
1040 }
1041 if let Some(ref mut anim) = player.snap_anim {
1042 let (delta, finished) = advance_snap(anim, time.delta_secs());
1043 transform.rotate_local_z(delta);
1044 if finished {
1045 // Commit the pure signed world axis, then renormalize
1046 // the frame: look_to preserves forward and snaps
1047 // screen-up onto the new anchor's projection, absorbing
1048 // any roll accumulated vs. the new axis mid-animation.
1049 if let Some(anchor) = player.pending_anchor.take() {
1050 player.anchor_up = anchor;
1051 }
1052 let fwd = *transform.forward();
1053 transform.look_to(fwd, player.anchor_up);
1054 player.snap_anim = None;
1055 }
1056 }
1057 }
1058 PlayerMode::Grounded { .. } => {
1059 if delta != Vec2::ZERO {
1060 let yaw_d = -delta.x * MOUSE_SCALE * player.sensitivity;
1061 let pitch_d = -delta.y * MOUSE_SCALE * player.sensitivity;
1062
1063 // Yaw: rotate around WORLD Y so the player stays upright.
1064 transform.rotate_y(yaw_d);
1065
1066 // Pitch: decompose current rotation, apply clamped pitch.
1067 let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
1068 let new_pitch = (pitch + pitch_d).clamp(-89_f32.to_radians(), 89_f32.to_radians());
1069 transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, new_pitch, 0.0);
1070 }
1071 // No roll in grounded mode.
1072 }
1073 }
1074}
1075
1076/// Translates the player based on keyboard input and updates [`ViewerPosition`].
1077///
1078/// Movement axes are derived from the current entity rotation, so all six
1079/// directions (forward, back, left, right, up, down) are always relative to
1080/// wherever the player is currently looking — including after roll and pitch.
1081///
1082/// **Velocity smoothing** uses exponential lerp clamped to `[0, 1]`:
1083///
1084/// ```text
1085/// factor = if moving { ACCEL } else { DECEL }
1086/// velocity = lerp(velocity, target, (factor * dt).min(1.0))
1087/// ```
1088///
1089/// This is frame-rate-independent for reasonable frame times and produces a
1090/// snappy start with a natural coast-to-stop deceleration.
1091///
1092/// After translating the entity, the system writes the new world position to
1093/// [`ViewerPosition`] so the chunk streaming system can load/unload chunks
1094/// around the player without querying the player transform directly.
1095pub fn player_move<V: VoxelType>(
1096 mut query: Query<(&mut Player, &mut Transform)>,
1097 keys: Res<ButtonInput<KeyCode>>,
1098 time: Res<Time>,
1099 mut viewer: ResMut<ViewerPosition>,
1100 manager: Res<ChunkManager>,
1101 chunks: Query<&Chunk<V>>,
1102 mut crouch_res: ResMut<PlayerCrouching>,
1103 applied: Option<Res<effects::AppliedEffectModifiers>>,
1104 windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>,
1105) {
1106 let Ok((mut player, mut transform)) = query.single_mut() else {
1107 return;
1108 };
1109
1110 if !player_input_active(windows) {
1111 player.velocity = Vec3::ZERO;
1112 return;
1113 }
1114 let dt = time.delta_secs();
1115
1116 match player.mode.clone() {
1117 PlayerMode::FreeFlightSixDof { .. } | PlayerMode::FreeFlightAnchored => {
1118 // Sprint/crouch are not applicable in FreeFlight.
1119 player.sprinting = false;
1120 player.crouching = false;
1121 crouch_res.0 = false;
1122
1123 // Local-space axes — full 6DOF.
1124 let forward = transform.rotation * Vec3::NEG_Z;
1125 let right = transform.rotation * Vec3::X;
1126 let up = transform.rotation * Vec3::Y;
1127
1128 let mut direction = Vec3::ZERO;
1129 if keys.pressed(KeyCode::KeyW) {
1130 direction += forward;
1131 }
1132 if keys.pressed(KeyCode::KeyS) {
1133 direction -= forward;
1134 }
1135 if keys.pressed(KeyCode::KeyA) {
1136 direction -= right;
1137 }
1138 if keys.pressed(KeyCode::KeyD) {
1139 direction += right;
1140 }
1141 if keys.pressed(KeyCode::Space) {
1142 direction += up;
1143 }
1144 if keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight) {
1145 direction -= up;
1146 }
1147
1148 let target = if direction != Vec3::ZERO {
1149 direction.normalize() * player.speed
1150 } else {
1151 Vec3::ZERO
1152 };
1153
1154 let factor = if direction != Vec3::ZERO {
1155 ACCEL
1156 } else {
1157 DECEL
1158 };
1159 player.velocity = player.velocity.lerp(target, (factor * dt).min(1.0));
1160 transform.translation += player.velocity * dt;
1161 }
1162 PlayerMode::Grounded {
1163 gravity,
1164 jump_speed,
1165 } => {
1166 // Horizontal movement on XZ using yaw-only orientation.
1167 let yaw = transform.rotation.to_euler(EulerRot::YXZ).0;
1168 let forward = Vec3::new(-yaw.sin(), 0.0, -yaw.cos());
1169 let right = Vec3::new(yaw.cos(), 0.0, -yaw.sin());
1170
1171 let mut h_dir = Vec3::ZERO;
1172 if keys.pressed(KeyCode::KeyW) {
1173 h_dir += forward;
1174 }
1175 if keys.pressed(KeyCode::KeyS) {
1176 h_dir -= forward;
1177 }
1178 if keys.pressed(KeyCode::KeyA) {
1179 h_dir -= right;
1180 }
1181 if keys.pressed(KeyCode::KeyD) {
1182 h_dir += right;
1183 }
1184
1185 // Sprint (Shift) and crouch (Ctrl) speed multipliers.
1186 // Crouch takes priority over sprint if both are held.
1187 // Sprint only activates when on solid ground (no air-sprinting).
1188 let crouching =
1189 keys.pressed(KeyCode::ControlLeft) || keys.pressed(KeyCode::ControlRight);
1190 let sprinting = !crouching
1191 && player.on_ground
1192 && (keys.pressed(KeyCode::ShiftLeft) || keys.pressed(KeyCode::ShiftRight));
1193 player.crouching = crouching;
1194 player.sprinting = sprinting;
1195 crouch_res.0 = crouching;
1196 let speed_mult = if crouching {
1197 0.5
1198 } else if sprinting {
1199 SPRINT_MULTIPLIER
1200 } else {
1201 1.0
1202 };
1203
1204 // Sample the block under the player's feet to get movement modifiers.
1205 let foot_pos = transform.translation - Vec3::Y * (PLAYER_HALF_HEIGHT + 0.3);
1206 let modifier = get_voxel_at::<V>(foot_pos, &manager, &chunks)
1207 .map(|v| v.movement_modifier())
1208 .unwrap_or_default();
1209
1210 let effect_speed = applied.as_deref().map(|a| a.0.speed_mult).unwrap_or(1.0);
1211 let h_target = if h_dir != Vec3::ZERO {
1212 h_dir.normalize() * player.speed * speed_mult * modifier.speed_mult * effect_speed
1213 } else {
1214 Vec3::ZERO
1215 };
1216
1217 let effective_decel = DECEL * modifier.friction_mult;
1218 let factor = if h_dir != Vec3::ZERO {
1219 ACCEL
1220 } else {
1221 effective_decel
1222 };
1223 player.velocity = player.velocity.lerp(h_target, (factor * dt).min(1.0));
1224
1225 // Freeze gravity until the initial chunk load completes so the
1226 // player does not fall through un-loaded terrain on startup.
1227 if !player.world_loaded {
1228 player.vertical_velocity = 0.0;
1229 transform.translation += player.velocity * dt;
1230 viewer.position = transform.translation;
1231 return;
1232 }
1233
1234 // Jump impulse (only when on the ground; disabled while crouching).
1235 if keys.just_pressed(KeyCode::Space) && player.on_ground && !crouching {
1236 let effect_jump = applied.as_deref().map(|a| a.0.jump_mult).unwrap_or(1.0);
1237 player.vertical_velocity = jump_speed * modifier.jump_mult * effect_jump;
1238 }
1239
1240 // Apply gravity.
1241 player.vertical_velocity -= gravity * modifier.gravity_mult * dt;
1242
1243 // Water buoyancy: if the player's center voxel is transparent (e.g.
1244 // water), apply a gentle upward push each frame to make them float
1245 // toward the surface. The movement_modifier already reduces gravity
1246 // via gravity_mult; buoyancy adds a positive upward impulse.
1247 let center_voxel = get_voxel_at::<V>(transform.translation, &manager, &chunks);
1248 if center_voxel.map(|v| v.alpha() < 1.0).unwrap_or(false) {
1249 player.vertical_velocity += jump_speed * 0.3 * dt;
1250 }
1251
1252 // Translate: horizontal from smoothed velocity + vertical from gravity.
1253 transform.translation += player.velocity * dt;
1254 transform.translation.y += player.vertical_velocity * dt;
1255 }
1256 }
1257
1258 // Keep the streaming origin at the player position.
1259 viewer.position = transform.translation;
1260}
1261
1262/// Resolves capsule-vs-voxel AABB collisions and repositions the player.
1263///
1264/// The collision shape is a capsule whose spine runs along the player's **local
1265/// Y axis** between `±PLAYER_HALF_HEIGHT`. Because the spine follows the
1266/// entity rotation, roll and pitch do not break collision detection — the
1267/// capsule tilts with the player.
1268///
1269/// **Algorithm (per chunk, per solid voxel in the AABB):**
1270///
1271/// 1. Compute the axis-aligned bounding box of the capsule in chunk-local space.
1272/// 2. Clamp the AABB to the chunk bounds to skip out-of-range voxels.
1273/// 3. For each solid voxel in the range, call `push_capsule_out` which:
1274/// a. Finds the closest point on the capsule spine to the voxel AABB center.
1275/// b. Treats that point as a sphere center of radius [`PLAYER_RADIUS`].
1276/// c. Computes the minimum separation vector from the sphere to the voxel AABB.
1277/// d. Accumulates the push into the running position.
1278///
1279/// The final corrected position is written back to the player transform. This
1280/// system should always run **after** [`player_move`] in the same frame.
1281pub fn player_resolve_collision<V: VoxelType>(
1282 mut player_q: Query<(&mut Player, &mut Transform)>,
1283 chunk_q: Query<(&Chunk<V>, &Transform), Without<Player>>,
1284 manager: Res<ChunkManager>,
1285) {
1286 let Ok((mut player, mut player_tf)) = player_q.single_mut() else {
1287 return;
1288 };
1289
1290 // Grounded mode tracks whether the player is standing on solid ground.
1291 let is_grounded = matches!(player.mode, PlayerMode::Grounded { .. });
1292 if is_grounded {
1293 player.on_ground = false;
1294 player.impact_speed = 0.0; // reset each frame; set below on landing
1295 }
1296
1297 // Use reduced capsule height when crouching so the player fits through
1298 // 1-block-tall gaps. In FreeFlight mode crouching is always false.
1299 let half_height = if player.crouching {
1300 CROUCH_HALF_HEIGHT
1301 } else {
1302 PLAYER_HALF_HEIGHT
1303 };
1304
1305 // Enable gravity only once the chunk containing the player's feet is
1306 // registered in ChunkManager — meaning the generator has actually produced
1307 // terrain data for that chunk. Checking a distant chunk being present
1308 // (chunk_q.is_empty) is not sufficient: it fires too early.
1309 if !player.world_loaded {
1310 let feet = player_tf.translation - Vec3::Y * half_height;
1311 let coord = crate::chunk::world_to_chunk_coord(feet);
1312 if manager.is_loaded(coord) {
1313 player.world_loaded = true;
1314 }
1315 }
1316
1317 let mut pos = player_tf.translation;
1318 // FreeFlight: capsule spine follows entity rotation (true 6DOF).
1319 // Grounded: spine is always world-vertical (Vec3::Y) so the capsule stands upright.
1320 let up = if is_grounded {
1321 Vec3::Y
1322 } else {
1323 player_tf.rotation * Vec3::Y
1324 };
1325
1326 let extent = half_height + PLAYER_RADIUS;
1327 let voxel_size = VOXEL_SIZE;
1328
1329 for (chunk, chunk_tf) in &chunk_q {
1330 let chunk_pos = chunk_tf.translation;
1331 let local = pos - chunk_pos;
1332
1333 // AABB of voxels that could possibly overlap the capsule.
1334 let min_vox = IVec3::new(
1335 ((local.x - extent) / voxel_size).floor() as i32,
1336 ((local.y - extent) / voxel_size).floor() as i32,
1337 ((local.z - extent) / voxel_size).floor() as i32,
1338 );
1339 let max_vox = IVec3::new(
1340 ((local.x + extent) / voxel_size).ceil() as i32,
1341 ((local.y + extent) / voxel_size).ceil() as i32,
1342 ((local.z + extent) / voxel_size).ceil() as i32,
1343 );
1344
1345 // Clamp to chunk bounds for the loop — is_solid_at returns false for
1346 // out-of-range coords, but skipping them avoids pointless iterations.
1347 let lo = min_vox.max(IVec3::ZERO);
1348 let hi = max_vox.min(IVec3::splat(CHUNK_SIZE as i32 - 1));
1349
1350 for vx in lo.x..=hi.x {
1351 for vy in lo.y..=hi.y {
1352 for vz in lo.z..=hi.z {
1353 if !chunk.is_solid_at(vx as usize, vy as usize, vz as usize) {
1354 continue;
1355 }
1356 let new_pos = push_capsule_out(pos, up, half_height, chunk_pos, vx, vy, vz);
1357
1358 // In grounded mode detect landing: a positive Y correction
1359 // means the player was pushed upward off a solid surface.
1360 if is_grounded && new_pos.y > pos.y + 0.001 {
1361 if !player.on_ground {
1362 // First contact this frame — record impact speed for fall damage.
1363 player.impact_speed = player.vertical_velocity.abs();
1364 }
1365 player.on_ground = true;
1366 player.vertical_velocity = 0.0;
1367 }
1368
1369 pos = new_pos;
1370 }
1371 }
1372 }
1373 }
1374
1375 player_tf.translation = pos;
1376}
1377
1378// ─── Cursor grab ──────────────────────────────────────────────────────────────
1379
1380/// Manages cursor lock state and window close on Escape.
1381///
1382/// This system implements a two-stage Escape behavior common in first-person
1383/// games:
1384///
1385/// | Trigger | Cursor state before | Effect |
1386/// |---------|---------------------|--------|
1387/// | Left click | Free (`None`) | Locks cursor, hides it |
1388/// | Escape | Locked | Releases cursor, shows it |
1389/// | Escape | Free | Despawns the window entity (closes the app) |
1390///
1391/// Do **not** add this system when using [`PauseMenuPlugin`](crate::ui::PauseMenuPlugin),
1392/// which provides its own cursor management and a richer Escape flow
1393/// (Playing → Paused → Playing).
1394pub fn player_cursor_system(
1395 mut commands: Commands,
1396 mouse: Res<ButtonInput<MouseButton>>,
1397 keys: Res<ButtonInput<KeyCode>>,
1398 mut windows: Query<(Entity, &Window, &mut CursorOptions), With<PrimaryWindow>>,
1399) {
1400 for (entity, window, mut cursor) in windows.iter_mut() {
1401 if !window.focused {
1402 if cursor.grab_mode != CursorGrabMode::None || !cursor.visible {
1403 cursor.grab_mode = CursorGrabMode::None;
1404 cursor.visible = true;
1405 }
1406 continue;
1407 }
1408 if mouse.just_pressed(MouseButton::Left)
1409 && cursor.grab_mode == bevy::window::CursorGrabMode::None
1410 {
1411 cursor.grab_mode = bevy::window::CursorGrabMode::Locked;
1412 cursor.visible = false;
1413 }
1414
1415 if keys.just_pressed(KeyCode::Escape) {
1416 if cursor.grab_mode != bevy::window::CursorGrabMode::None {
1417 cursor.grab_mode = bevy::window::CursorGrabMode::None;
1418 cursor.visible = true;
1419 } else {
1420 commands.entity(entity).despawn();
1421 }
1422 }
1423 }
1424}
1425
1426/// Whether the primary window owns player input (focused and cursor captured).
1427/// No primary window preserves synthetic input for headless simulations.
1428///
1429/// Useful as a run condition for other gameplay input systems. Keep
1430/// [`player_look`] scheduled: it discards inactive mouse deltas itself.
1431/// This checks Bevy's current window state, not OS activation or grab success.
1432pub fn player_input_active(windows: Query<(&Window, &CursorOptions), With<PrimaryWindow>>) -> bool {
1433 match windows.single() {
1434 Ok((window, cursor)) => window.focused && cursor.grab_mode != CursorGrabMode::None,
1435 Err(_) => windows.is_empty(),
1436 }
1437}
1438
1439/// Applies fall damage when the player lands after a significant drop.
1440///
1441/// Reads `Player::impact_speed` set by [`player_resolve_collision`] and
1442/// computes damage as `(impact_speed - fall_safe_speed).max(0) * 2.0`. When
1443/// health reaches zero the player is teleported to [`PlayerHealth::spawn_position`]
1444/// and a [`PlayerDied`] message is sent.
1445///
1446/// Run this system **after** [`player_resolve_collision`].
1447pub fn player_fall_damage(
1448 mut player_q: Query<(&mut Player, &mut Transform)>,
1449 mut health: ResMut<PlayerHealth>,
1450 mut damaged_writer: MessageWriter<PlayerDamaged>,
1451 mut died_writer: MessageWriter<PlayerDied>,
1452) {
1453 let Ok((mut player, mut transform)) = player_q.single_mut() else {
1454 return;
1455 };
1456
1457 if player.impact_speed <= 0.0 {
1458 return;
1459 }
1460
1461 // First landing after spawn or respawn is immune to fall damage so the
1462 // player doesn't die just because the spawn point is a few blocks above
1463 // the terrain surface.
1464 if player.spawn_immune {
1465 player.spawn_immune = false;
1466 player.impact_speed = 0.0;
1467 return;
1468 }
1469
1470 let damage = (player.impact_speed - health.fall_safe_speed).max(0.0) * 2.0;
1471 player.impact_speed = 0.0;
1472
1473 if damage <= 0.0 {
1474 return;
1475 }
1476
1477 health.health = (health.health - damage).max(0.0);
1478 damaged_writer.write(PlayerDamaged { amount: damage });
1479
1480 if health.health <= 0.0 {
1481 health.health = health.max_health;
1482 transform.translation = health.spawn_position;
1483 // Reset velocity so the player doesn't inherit falling momentum after respawn.
1484 player.vertical_velocity = 0.0;
1485 player.velocity = Vec3::ZERO;
1486 player.world_loaded = false; // re-freeze gravity until feet chunk reloads
1487 player.spawn_immune = true; // grant immunity on the next landing too
1488 died_writer.write(PlayerDied);
1489 }
1490}
1491
1492/// Processes incoming damage messages and runs the death / respawn check.
1493///
1494/// Regen and poison are handled exclusively by
1495/// [`apply_health_effects`](crate::player::effects::apply_health_effects)
1496/// inside [`StatusEffectsPlugin`](crate::player::effects::StatusEffectsPlugin).
1497/// This system only reads [`AppliedEffectModifiers`](crate::player::effects::AppliedEffectModifiers) to apply damage resistance
1498/// to incoming [`PlayerDamaged`] events. `AppliedEffectModifiers` is optional —
1499/// the system degrades gracefully when no `StatusEffectsPlugin` is registered.
1500///
1501/// Run this system **every frame**, regardless of pause state.
1502pub fn health_system(
1503 applied: Option<Res<effects::AppliedEffectModifiers>>,
1504 mut health: ResMut<PlayerHealth>,
1505 mut damaged_reader: bevy::ecs::message::MessageReader<PlayerDamaged>,
1506 mut died_writer: MessageWriter<PlayerDied>,
1507) {
1508 // Process every pending damage event, reduced by damage resistance.
1509 for event in damaged_reader.read() {
1510 let resistance = applied
1511 .as_ref()
1512 .map(|a| a.0.damage_resistance)
1513 .unwrap_or(0.0);
1514 let actual = event.amount * (1.0 - resistance.clamp(0.0, 1.0));
1515 health.health = (health.health - actual).max(0.0);
1516 }
1517
1518 // Death check — instant respawn (position is handled by respawn_system).
1519 if health.health <= 0.0 {
1520 health.health = health.max_health;
1521 died_writer.write(PlayerDied);
1522 }
1523}
1524
1525/// Teleports the streaming origin to the spawn position on player death.
1526///
1527/// Listens for [`PlayerDied`] messages and updates [`ViewerPosition`] so the
1528/// chunk streaming system starts loading terrain around the respawn location
1529/// immediately. Physical entity teleportation is handled by
1530/// [`player_fall_damage`].
1531///
1532/// If no [`PlayerConfig`] resource is present, the player is teleported to
1533/// [`Vec3::ZERO`].
1534pub fn respawn_system(
1535 mut died_reader: bevy::ecs::message::MessageReader<PlayerDied>,
1536 mut viewer: ResMut<ViewerPosition>,
1537 config: Option<Res<PlayerConfig>>,
1538) {
1539 for _ in died_reader.read() {
1540 let spawn = config
1541 .as_ref()
1542 .map(|c| c.spawn_position)
1543 .unwrap_or(Vec3::ZERO);
1544 viewer.position = spawn;
1545 }
1546}
1547
1548// ─── Push helper ─────────────────────────────────────────────────────────────
1549
1550/// Returns the corrected capsule-center position after pushing out of a solid voxel.
1551///
1552/// The algorithm treats the capsule as a swept sphere along the spine segment
1553/// `[pos − up*half_height, pos + up*half_height]`:
1554///
1555/// 1. Find the point on the spine segment closest to the voxel AABB center
1556/// (clamped parametric projection, `t ∈ [0, 1]`).
1557/// 2. Treat that spine point as a sphere center `sphere_c` with radius
1558/// [`PLAYER_RADIUS`].
1559/// 3. Find the point on the voxel AABB closest to `sphere_c`.
1560/// 4. If the sphere overlaps the AABB (distance² < `PLAYER_RADIUS²`), compute
1561/// the minimum translation vector and apply it to `pos`.
1562///
1563/// A degenerate case (sphere center exactly inside the voxel) is handled by
1564/// pushing along the dominant axis of the relative offset to avoid a zero-
1565/// length normal.
1566fn push_capsule_out(
1567 pos: Vec3,
1568 up: Vec3,
1569 half_height: f32,
1570 chunk_pos: Vec3,
1571 vx: i32,
1572 vy: i32,
1573 vz: i32,
1574) -> Vec3 {
1575 let vmin = chunk_pos + Vec3::new(vx as f32, vy as f32, vz as f32) * VOXEL_SIZE;
1576 let vmax = vmin + Vec3::splat(VOXEL_SIZE);
1577
1578 // Capsule spine endpoints.
1579 let p0 = pos - up * half_height;
1580 let p1 = pos + up * half_height;
1581 let spine = p1 - p0;
1582
1583 // Closest point on spine to the voxel center.
1584 let vox_center = (vmin + vmax) * 0.5;
1585 let len_sq = spine.length_squared();
1586 let sphere_c = if len_sq > f32::EPSILON {
1587 let t = ((vox_center - p0).dot(spine) / len_sq).clamp(0.0, 1.0);
1588 p0 + spine * t
1589 } else {
1590 pos
1591 };
1592
1593 // Sphere-AABB collision.
1594 let closest = sphere_c.clamp(vmin, vmax);
1595 let diff = sphere_c - closest;
1596 let dist_sq = diff.length_squared();
1597
1598 if dist_sq >= PLAYER_RADIUS * PLAYER_RADIUS {
1599 return pos;
1600 }
1601
1602 let delta = if dist_sq > f32::EPSILON {
1603 let dist = dist_sq.sqrt();
1604 (diff / dist) * (PLAYER_RADIUS - dist)
1605 } else {
1606 // Degenerate: center exactly inside voxel — push along dominant axis.
1607 let rel = sphere_c - vox_center;
1608 let abs_rel = rel.abs();
1609 let half = VOXEL_SIZE * 0.5 + PLAYER_RADIUS;
1610 if abs_rel.x >= abs_rel.y && abs_rel.x >= abs_rel.z {
1611 Vec3::new(half * rel.x.signum() - rel.x, 0.0, 0.0)
1612 } else if abs_rel.y >= abs_rel.z {
1613 Vec3::new(0.0, half * rel.y.signum() - rel.y, 0.0)
1614 } else {
1615 Vec3::new(0.0, 0.0, half * rel.z.signum() - rel.z)
1616 }
1617 };
1618
1619 pos + delta
1620}
1621
1622/// Emits [`SfxRequest`] footstep sounds when the player walks on solid ground.
1623///
1624/// Samples the voxel directly below the player's feet and passes its byte
1625/// representation as [`SfxEvent::Footstep`] so games can map surface types to
1626/// different audio assets. The step interval scales with horizontal speed.
1627pub fn player_footstep_system<V: VoxelType>(
1628 mut query: Query<(&mut Player, &Transform)>,
1629 time: Res<Time>,
1630 manager: Res<ChunkManager>,
1631 chunks: Query<&Chunk<V>>,
1632 mut sfx: MessageWriter<SfxRequest>,
1633) {
1634 let Ok((mut player, transform)) = query.single_mut() else {
1635 return;
1636 };
1637
1638 if !matches!(player.mode, PlayerMode::Grounded { .. }) || !player.on_ground {
1639 return;
1640 }
1641
1642 let h_speed = Vec3::new(player.velocity.x, 0.0, player.velocity.z).length();
1643 if h_speed < 0.5 {
1644 player.footstep_timer = 0.0;
1645 return;
1646 }
1647
1648 // Step interval: shorter at higher speeds (clamped between 0.2–0.5s).
1649 let step_interval = (0.5 / h_speed).clamp(0.2, 0.5);
1650 player.footstep_timer += time.delta_secs();
1651
1652 if player.footstep_timer < step_interval {
1653 return;
1654 }
1655 player.footstep_timer = 0.0;
1656
1657 // Sample voxel just below the player's feet.
1658 let foot_pos = transform.translation - Vec3::Y * (PLAYER_HALF_HEIGHT + 0.3);
1659 let voxel_byte = get_voxel_at::<V>(foot_pos, &manager, &chunks)
1660 .map(|v| v.to_byte())
1661 .unwrap_or(0);
1662
1663 sfx.write(SfxRequest {
1664 event: SfxEvent::Footstep(voxel_byte),
1665 position: None,
1666 });
1667}
1668
1669// ─── Spawn persistence ────────────────────────────────────────────────────────
1670
1671/// Startup system that applies a persisted spawn position to [`PlayerConfig`]
1672/// and [`PlayerHealth`] before the player entity is spawned.
1673///
1674/// Reads the world data directory from [`WorldDataDir`] (set by
1675/// [`PlayerPlugin::with_world`]). Silent no-op if `player_data.json` does not
1676/// exist.
1677fn load_spawn_on_startup(
1678 mut config: ResMut<PlayerConfig>,
1679 mut health: ResMut<PlayerHealth>,
1680 world_data_dir: Res<WorldDataDir>,
1681) {
1682 let data_dir = world_data_dir.as_str();
1683 if let Some(pos) = persistence::load_spawn_position(data_dir) {
1684 config.spawn_position = pos;
1685 health.spawn_position = pos;
1686 } else {
1687 // First run: persist the configured default so subsequent runs reload it.
1688 persistence::save_spawn_position(config.spawn_position, data_dir);
1689 }
1690}
1691
1692/// System that saves [`PlayerHealth::spawn_position`] to disk on [`AppExit`].
1693///
1694/// This preserves a custom spawn set at runtime (e.g. sleeping in a bed)
1695/// across sessions. The [`PlayerConfig::spawn_position`] default is used as
1696/// fallback when no file exists.
1697fn save_spawn_on_exit(
1698 health: Res<PlayerHealth>,
1699 world_data_dir: Res<WorldDataDir>,
1700 mut exit_reader: bevy::ecs::message::MessageReader<AppExit>,
1701) {
1702 for _ in exit_reader.read() {
1703 persistence::save_spawn_position(health.spawn_position, world_data_dir.as_str());
1704 }
1705}
1706
1707// ─── Run condition ────────────────────────────────────────────────────────────
1708
1709/// Returns `true` when gameplay should be active.
1710///
1711/// If [`crate::ui::PauseMenuState`] is registered, returns `true`
1712/// only while in the `Playing` variant. If the state is not present (i.e.
1713/// [`crate::ui::PauseMenuPlugin`] was not added), always returns `true` so the
1714/// player systems run unconditionally.
1715fn gameplay_active(state: Option<Res<bevy::prelude::State<crate::ui::PauseMenuState>>>) -> bool {
1716 use crate::ui::PauseMenuState;
1717 state.map_or(true, |s| matches!(s.get(), PauseMenuState::Playing))
1718}
1719
1720// ─── Plugin ───────────────────────────────────────────────────────────────────
1721
1722/// Plugin that wires up the complete 6DOF player controller.
1723///
1724/// Registers [`PlayerConfig`] as an init resource, spawns the player camera
1725/// on `Startup`, and chains the three frame-update systems in the correct
1726/// dependency order every `Update`:
1727///
1728/// ```text
1729/// player_look → player_move → player_resolve_collision<V>
1730/// ```
1731///
1732/// [`player_cursor_system`] is added as a separate, un-chained `Update` system
1733/// so cursor events are processed independently of the movement pipeline.
1734///
1735/// All systems run **unconditionally** every frame. If your game requires
1736/// state-gated player control (e.g., pausing during a menu), skip this plugin
1737/// and register the systems manually:
1738///
1739/// ```rust,no_run
1740/// # use bevy::prelude::*;
1741/// # use voxel_framework::player::{spawn_player, player_look, player_move,
1742/// # player_resolve_collision};
1743/// # use voxel_framework::voxel::DefaultVoxel;
1744/// # #[derive(States, Default, Clone, PartialEq, Eq, Hash, Debug)]
1745/// # enum AppState { #[default] Playing }
1746/// App::new()
1747/// .add_systems(Startup, spawn_player)
1748/// .add_systems(Update,
1749/// (player_look, player_move::<DefaultVoxel>, player_resolve_collision::<DefaultVoxel>)
1750/// .chain()
1751/// .run_if(in_state(AppState::Playing)),
1752/// );
1753/// ```
1754///
1755/// The generic parameter `V` must match the [`VoxelType`] used by the loaded
1756/// [`Chunk`] entities so the collision system can read
1757/// solid-voxel data.
1758pub struct PlayerPlugin<V: VoxelType> {
1759 _marker: std::marker::PhantomData<V>,
1760 world_name: String,
1761}
1762
1763impl<V: VoxelType> PlayerPlugin<V> {
1764 /// Creates a `PlayerPlugin` using the default world name (`"world"`).
1765 pub fn new() -> Self {
1766 Self {
1767 _marker: std::marker::PhantomData,
1768 world_name: String::new(),
1769 }
1770 }
1771
1772 /// Creates a `PlayerPlugin` that stores player data under
1773 /// `./worlds/{world_name}/player_data.json`.
1774 pub fn with_world(world_name: impl Into<String>) -> Self {
1775 Self {
1776 _marker: std::marker::PhantomData,
1777 world_name: world_name.into(),
1778 }
1779 }
1780}
1781
1782impl<V: VoxelType> Default for PlayerPlugin<V> {
1783 fn default() -> Self {
1784 Self::new()
1785 }
1786}
1787
1788impl<V: VoxelType> Plugin for PlayerPlugin<V> {
1789 fn build(&self, app: &mut App) {
1790 let name = if self.world_name.is_empty() {
1791 "world"
1792 } else {
1793 &self.world_name
1794 };
1795 app.insert_resource(WorldDataDir::for_world(name));
1796 app.init_resource::<PlayerConfig>();
1797 app.init_resource::<PlayerHealth>();
1798 app.init_resource::<PlayerCrouching>();
1799 app.add_message::<PlayerDamaged>();
1800 app.add_message::<PlayerDied>();
1801 app.add_systems(Startup, (load_spawn_on_startup, spawn_player).chain());
1802 app.add_systems(
1803 Update,
1804 (
1805 player_look,
1806 player_move::<V>,
1807 player_resolve_collision::<V>,
1808 player_fall_damage,
1809 player_footstep_system::<V>,
1810 )
1811 .chain()
1812 .run_if(gameplay_active),
1813 );
1814 // health_system and respawn_system run unconditionally (not gated by pause).
1815 app.add_systems(Update, health_system);
1816 app.add_systems(Update, respawn_system);
1817 app.add_systems(
1818 Update,
1819 player_cursor_system
1820 .run_if(gameplay_active)
1821 .before(player_look),
1822 );
1823 app.add_systems(PostUpdate, save_spawn_on_exit);
1824 }
1825}
1826
1827// ─── Tests ────────────────────────────────────────────────────────────────────
1828
1829#[cfg(test)]
1830mod tests {
1831 use super::*;
1832
1833 #[test]
1834 fn player_default_values() {
1835 let p = Player::default();
1836 assert_eq!(p.speed, 4.0);
1837 assert_eq!(p.sensitivity, 1.0);
1838 assert_eq!(p.roll_speed, 1.5);
1839 assert_eq!(p.velocity, Vec3::ZERO);
1840 }
1841
1842 #[test]
1843 fn player_config_default_values() {
1844 let c = PlayerConfig::default();
1845 assert_eq!(c.speed, 4.0);
1846 assert_eq!(c.fov_degrees, 90.0);
1847 assert!(matches!(
1848 c.mode,
1849 PlayerMode::FreeFlightSixDof {
1850 roll_mode: RollMode::Continuous
1851 }
1852 ));
1853 assert!((c.snap_roll_duration_secs - 0.5).abs() < f32::EPSILON);
1854 assert_eq!(c.snap_roll_easing, SnapRollEasing::EaseOutCubic);
1855 }
1856
1857 #[test]
1858 fn snap_roll_completes_to_90deg() {
1859 let mut anim = start_or_retarget_snap(
1860 None,
1861 Vec3::Z,
1862 Vec3::Y,
1863 1,
1864 0.18,
1865 SnapRollEasing::EaseOutCubic,
1866 );
1867 let (delta, finished) = advance_snap(&mut anim, 0.18);
1868 assert!(finished);
1869 assert!(
1870 (delta - std::f32::consts::FRAC_PI_2).abs() < 1e-4,
1871 "Expected ~PI/2, got {delta}"
1872 );
1873 }
1874
1875 #[test]
1876 fn snap_roll_easing_monotonic() {
1877 let mut anim = start_or_retarget_snap(
1878 None,
1879 Vec3::Z,
1880 Vec3::Y,
1881 1,
1882 0.18,
1883 SnapRollEasing::EaseOutCubic,
1884 );
1885 let step = 0.045;
1886 let mut deltas = Vec::new();
1887 for _ in 0..4 {
1888 let (d, _) = advance_snap(&mut anim, step);
1889 assert!(d > 0.0, "Delta should be positive, got {d}");
1890 deltas.push(d);
1891 }
1892 let total: f32 = deltas.iter().sum();
1893 assert!(
1894 (total - std::f32::consts::FRAC_PI_2).abs() < 1e-3,
1895 "Sum should be ~PI/2, got {total}"
1896 );
1897 // Ease-out: deltas should be non-increasing (each <= previous)
1898 for i in 1..deltas.len() {
1899 assert!(
1900 deltas[i] <= deltas[i - 1] + 1e-6,
1901 "Easing not monotonically decreasing: {:?}",
1902 deltas
1903 );
1904 }
1905 }
1906
1907 #[test]
1908 fn snap_roll_same_direction_extends_target() {
1909 let mut anim = start_or_retarget_snap(
1910 None,
1911 Vec3::Z,
1912 Vec3::Y,
1913 1,
1914 0.18,
1915 SnapRollEasing::EaseOutCubic,
1916 );
1917 // Advance ~30%
1918 advance_snap(&mut anim, 0.054);
1919 let prev_applied = anim.current_applied;
1920 // The transform has rotated with the animation: up at press time
1921 // reflects the applied angle (world-aligned start).
1922 let up = Quat::from_axis_angle(Vec3::Z, anim.current_applied) * Vec3::Y;
1923 let new_anim = start_or_retarget_snap(
1924 Some(anim),
1925 Vec3::Z,
1926 up,
1927 1,
1928 0.18,
1929 SnapRollEasing::EaseOutCubic,
1930 );
1931 assert!((new_anim.start_angle - prev_applied).abs() < 1e-6);
1932 assert!(
1933 (new_anim.target_angle - std::f32::consts::PI).abs() < 1e-4,
1934 "Expected target ~PI (2x90°), got {}",
1935 new_anim.target_angle
1936 );
1937 }
1938
1939 #[test]
1940 fn snap_roll_opposite_direction_reverses_to_lattice() {
1941 let mut anim = start_or_retarget_snap(
1942 None,
1943 Vec3::Z,
1944 Vec3::Y,
1945 1,
1946 0.18,
1947 SnapRollEasing::EaseOutCubic,
1948 );
1949 // Advance ~30% (heading to PI/2 ≈ 1.571)
1950 advance_snap(&mut anim, 0.054);
1951 let current = anim.current_applied;
1952 assert!(current > 0.0 && current < std::f32::consts::FRAC_PI_2);
1953 // The transform has rotated with the animation: up at press time
1954 // reflects the applied angle (world-aligned start).
1955 let up = Quat::from_axis_angle(Vec3::Z, current) * Vec3::Y;
1956 let new_anim = start_or_retarget_snap(
1957 Some(anim),
1958 Vec3::Z,
1959 up,
1960 -1,
1961 0.18,
1962 SnapRollEasing::EaseOutCubic,
1963 );
1964 // Should target 0.0 (nearest lattice below current in negative direction)
1965 assert!(
1966 new_anim.target_angle.abs() < 1e-6,
1967 "Expected target ~0, got {}",
1968 new_anim.target_angle
1969 );
1970 }
1971
1972 #[test]
1973 fn continuous_mode_unchanged() {
1974 let player = Player::default();
1975 assert!(matches!(
1976 player.mode,
1977 PlayerMode::FreeFlightSixDof {
1978 roll_mode: RollMode::Continuous
1979 }
1980 ));
1981 assert!(player.snap_anim.is_none());
1982 }
1983
1984 #[test]
1985 fn snap_roll_config_copies_to_player() {
1986 let config = PlayerConfig {
1987 mode: PlayerMode::FreeFlightSixDof {
1988 roll_mode: RollMode::Snap,
1989 },
1990 snap_roll_duration_secs: 0.3,
1991 snap_roll_easing: SnapRollEasing::Smoothstep,
1992 ..default()
1993 };
1994 let player = Player {
1995 mode: config.mode.clone(),
1996 snap_roll_duration: config.snap_roll_duration_secs,
1997 snap_roll_easing: config.snap_roll_easing,
1998 ..default()
1999 };
2000 assert!(matches!(
2001 player.mode,
2002 PlayerMode::FreeFlightSixDof {
2003 roll_mode: RollMode::Snap
2004 }
2005 ));
2006 assert!((player.snap_roll_duration - 0.3).abs() < f32::EPSILON);
2007 assert_eq!(player.snap_roll_easing, SnapRollEasing::Smoothstep);
2008 }
2009
2010 #[test]
2011 fn snap_roll_start_from_none_is_independent() {
2012 let anim1 = start_or_retarget_snap(
2013 None,
2014 Vec3::Z,
2015 Vec3::Y,
2016 1,
2017 0.18,
2018 SnapRollEasing::EaseOutCubic,
2019 );
2020 let anim2 = start_or_retarget_snap(
2021 None,
2022 Vec3::Z,
2023 Vec3::Y,
2024 1,
2025 0.18,
2026 SnapRollEasing::EaseOutCubic,
2027 );
2028 assert!((anim1.target_angle - anim2.target_angle).abs() < f32::EPSILON);
2029 assert!((anim1.start_angle - anim2.start_angle).abs() < f32::EPSILON);
2030 }
2031
2032 #[test]
2033 fn lattice_axis_forward_yields_four_candidates_at_90deg() {
2034 // Looking straight down: local Z (back) parallel to world Y.
2035 let mut angles = world_lattice_angles(Vec3::Y, Vec3::Z);
2036 assert_eq!(angles.len(), 4, "Y axis pair must be excluded: {angles:?}");
2037 angles.sort_by(f32::total_cmp);
2038 for pair in angles.windows(2) {
2039 assert!(
2040 (pair[1] - pair[0] - std::f32::consts::FRAC_PI_2).abs() < 1e-5,
2041 "Candidates must be exactly 90° apart: {angles:?}"
2042 );
2043 }
2044 }
2045
2046 #[test]
2047 fn lattice_near_axis_forward_still_yields_four_candidates() {
2048 // Playtest regression: view drifted a few degrees off a world axis
2049 // must NOT resurrect the near-forward axis pair as junk candidates
2050 // (6 stops with two perceptually arbitrary ones). 45° dominance rule.
2051 let local_z = Quat::from_axis_angle(Vec3::X, 8_f32.to_radians()) * Vec3::Z;
2052 let up = Quat::from_axis_angle(local_z, 5_f32.to_radians())
2053 * (Vec3::Y - Vec3::Y.dot(local_z) * local_z).normalize();
2054
2055 let angles = world_lattice_angles(local_z, up);
2056 assert_eq!(
2057 angles.len(),
2058 4,
2059 "Near-axis view must exclude the ±Z pair, got {angles:?}"
2060 );
2061
2062 // Exact 45° edge-on view: both axis families sit at proj² ≈ 0.5.
2063 // Float rounding must never exclude both (≥4 invariant) — the 0.49
2064 // threshold keeps the tie inclusive, so all 6 survive.
2065 let boundary_z = Vec3::new(0.0, 1.0, 1.0).normalize();
2066 let boundary_up = (Vec3::Y - Vec3::Y.dot(boundary_z) * boundary_z).normalize();
2067 assert_eq!(
2068 world_lattice_angles(boundary_z, boundary_up).len(),
2069 6,
2070 "At exactly 45° both axis families are equally valid"
2071 );
2072 }
2073
2074 #[test]
2075 fn lattice_diagonal_forward_yields_six_candidates_cycling_2pi() {
2076 use std::f32::consts::{FRAC_PI_2, FRAC_PI_3, TAU};
2077 // Forward = (1,1,1)/√3, so local Z (back) is the opposite diagonal.
2078 let local_z = -Vec3::ONE.normalize();
2079 // Start exactly on a candidate: world X projected onto the roll plane.
2080 let start = (Vec3::X - Vec3::X.dot(local_z) * local_z).normalize();
2081
2082 let angles = world_lattice_angles(local_z, start);
2083 assert_eq!(
2084 angles.len(),
2085 6,
2086 "All 6 axes survive on a diagonal: {angles:?}"
2087 );
2088
2089 // Six Q presses walk the hexagon: each step ~60° (never 90°),
2090 // the total is a full turn, and we return to the start candidate.
2091 let mut up = start;
2092 let mut total = 0.0_f32;
2093 for _ in 0..6 {
2094 let step = next_lattice_step(&world_lattice_angles(local_z, up), 1);
2095 assert!(
2096 (step - FRAC_PI_3).abs() < 1e-3,
2097 "Expected ~60° step, got {step}"
2098 );
2099 assert!(
2100 (step - FRAC_PI_2).abs() > 0.1,
2101 "Step must not be 90°, got {step}"
2102 );
2103 total += step;
2104 up = Quat::from_axis_angle(local_z, step) * up;
2105 }
2106 assert!(
2107 (total - TAU).abs() < 1e-3,
2108 "Six presses must sum to 2π, got {total}"
2109 );
2110 assert!(
2111 up.dot(start) > 0.9999,
2112 "Cycle must return to start, got {up:?}"
2113 );
2114 }
2115
2116 #[test]
2117 fn lattice_drifted_up_travels_residual() {
2118 // Up rolled 10° off the Y candidate (CCW, rotate_local_z convention).
2119 let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
2120 let angles = world_lattice_angles(Vec3::Z, up);
2121
2122 let q = next_lattice_step(&angles, 1);
2123 let e = next_lattice_step(&angles, -1);
2124 assert!(
2125 (q - 80_f32.to_radians()).abs() < 1e-4,
2126 "Q must travel ≈+80°, got {q}"
2127 );
2128 assert!(
2129 (e + 10_f32.to_radians()).abs() < 1e-4,
2130 "E must travel ≈−10°, got {e}"
2131 );
2132
2133 // Both presses land within ε of a world candidate.
2134 let up_q = Quat::from_axis_angle(Vec3::Z, q) * up;
2135 let up_e = Quat::from_axis_angle(Vec3::Z, e) * up;
2136 assert!(
2137 up_q.dot(Vec3::NEG_X) > 0.9999,
2138 "Q must land on −X, got {up_q:?}"
2139 );
2140 assert!(
2141 up_e.dot(Vec3::Y) > 0.9999,
2142 "E must land on +Y, got {up_e:?}"
2143 );
2144 }
2145
2146 #[test]
2147 fn lattice_eps_on_skips_exact_candidate() {
2148 // Up exactly on a candidate: the press must travel a full step, not ~0.
2149 let angles = world_lattice_angles(Vec3::Z, Vec3::Y);
2150 let q = next_lattice_step(&angles, 1);
2151 let e = next_lattice_step(&angles, -1);
2152 assert!(
2153 (q - std::f32::consts::FRAC_PI_2).abs() < 1e-5,
2154 "Q from an exact candidate must be +90°, got {q}"
2155 );
2156 assert!(
2157 (e + std::f32::consts::FRAC_PI_2).abs() < 1e-5,
2158 "E from an exact candidate must be −90°, got {e}"
2159 );
2160 }
2161
2162 #[test]
2163 fn snap_retarget_drifted_frame_lands_on_candidates() {
2164 let local_z = Vec3::Z;
2165 // Start 10° off the Y candidate: fresh Q targets the −X candidate (+80°).
2166 let up0 = Quat::from_axis_angle(local_z, 10_f32.to_radians()) * Vec3::Y;
2167
2168 // Same-direction press mid-flight extends to the NEXT candidate (−Y).
2169 let mut anim =
2170 start_or_retarget_snap(None, local_z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
2171 advance_snap(&mut anim, 0.054);
2172 let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2173 let extended = start_or_retarget_snap(
2174 Some(anim),
2175 local_z,
2176 up_mid,
2177 1,
2178 0.18,
2179 SnapRollEasing::EaseOutCubic,
2180 );
2181 let up_ext = Quat::from_axis_angle(local_z, extended.target_angle) * up0;
2182 assert!(
2183 up_ext.dot(Vec3::NEG_Y) > 0.9999,
2184 "Extend must land on −Y, got {up_ext:?}"
2185 );
2186
2187 // Opposite press mid-flight reverses to the candidate behind (+Y).
2188 let mut anim =
2189 start_or_retarget_snap(None, local_z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
2190 advance_snap(&mut anim, 0.054);
2191 let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2192 let reversed = start_or_retarget_snap(
2193 Some(anim),
2194 local_z,
2195 up_mid,
2196 -1,
2197 0.18,
2198 SnapRollEasing::EaseOutCubic,
2199 );
2200 let up_rev = Quat::from_axis_angle(local_z, reversed.target_angle) * up0;
2201 assert!(
2202 up_rev.dot(Vec3::Y) > 0.9999,
2203 "Reverse must land on +Y, got {up_rev:?}"
2204 );
2205 }
2206
2207 #[test]
2208 fn push_capsule_no_collision() {
2209 // Voxel at origin, player far away — should not move.
2210 let pos = Vec3::new(10.0, 10.0, 10.0);
2211 let result = push_capsule_out(pos, Vec3::Y, PLAYER_HALF_HEIGHT, Vec3::ZERO, 0, 0, 0);
2212 assert_eq!(result, pos);
2213 }
2214
2215 #[test]
2216 fn push_capsule_resolves_overlap() {
2217 // Player center directly on top of a voxel — must be pushed out.
2218 let pos = Vec3::new(0.5, 0.5, 0.5); // inside voxel [0,0,0]
2219 let result = push_capsule_out(pos, Vec3::Y, PLAYER_HALF_HEIGHT, Vec3::ZERO, 0, 0, 0);
2220 // After push, capsule sphere should clear the voxel.
2221 let vox_center = Vec3::splat(0.5);
2222 let closest = result.clamp(Vec3::ZERO, Vec3::ONE);
2223 let dist = (result - closest).length();
2224 assert!(
2225 dist >= PLAYER_RADIUS - 0.001,
2226 "dist={dist} must be >= PLAYER_RADIUS={PLAYER_RADIUS}"
2227 );
2228 let _ = vox_center; // silence unused warning
2229 }
2230
2231 // ─── Anchored look: pitch clamp ──────────────────────────────────────────
2232
2233 #[test]
2234 fn clamp_pitch_under_limit_passes_through() {
2235 // Level forward (pitch 0 vs +Y anchor): moderate deltas are untouched.
2236 let d = clamp_pitch_delta(Vec3::NEG_Z, Vec3::Y, 30_f32.to_radians());
2237 assert!((d - 30_f32.to_radians()).abs() < 1e-5, "got {d}");
2238 let d = clamp_pitch_delta(Vec3::NEG_Z, Vec3::Y, -30_f32.to_radians());
2239 assert!((d + 30_f32.to_radians()).abs() < 1e-5, "got {d}");
2240 }
2241
2242 #[test]
2243 fn clamp_pitch_crossing_limit_truncates() {
2244 // From +80° elevation a +20° request truncates to +9° (lands at +89°).
2245 let f_hi = Vec3::new(0.0, 80_f32.to_radians().sin(), -(80_f32.to_radians().cos()));
2246 let d = clamp_pitch_delta(f_hi, Vec3::Y, 20_f32.to_radians());
2247 assert!(
2248 (d - 9_f32.to_radians()).abs() < 1e-4,
2249 "expected ~+9°, got {d}"
2250 );
2251
2252 // Mirror: from −80° a −20° request truncates to −9° (lands at −89°).
2253 let f_lo = Vec3::new(
2254 0.0,
2255 -(80_f32.to_radians().sin()),
2256 -(80_f32.to_radians().cos()),
2257 );
2258 let d = clamp_pitch_delta(f_lo, Vec3::Y, -20_f32.to_radians());
2259 assert!(
2260 (d + 9_f32.to_radians()).abs() < 1e-4,
2261 "expected ~−9°, got {d}"
2262 );
2263 }
2264
2265 #[test]
2266 fn clamp_pitch_at_limit_blocks_outward_allows_inward() {
2267 // Exactly at the +89° pole: outward is blocked, inward passes through.
2268 let f = Vec3::new(0.0, 89_f32.to_radians().sin(), -(89_f32.to_radians().cos()));
2269 let outward = clamp_pitch_delta(f, Vec3::Y, 5_f32.to_radians());
2270 assert!(
2271 outward.abs() < 1e-4,
2272 "outward delta at the pole must be ~0, got {outward}"
2273 );
2274 let inward = clamp_pitch_delta(f, Vec3::Y, -5_f32.to_radians());
2275 assert!(
2276 (inward + 5_f32.to_radians()).abs() < 1e-4,
2277 "inward delta must pass through, got {inward}"
2278 );
2279 }
2280
2281 // ─── Anchored look: lattice candidates ───────────────────────────────────
2282
2283 #[test]
2284 fn candidates_axis_forward_have_source_axes() {
2285 use std::f32::consts::FRAC_PI_2;
2286 // Axial view (local Z = world Z, up = Y): the ±Z pair is filtered, the
2287 // four survivors carry their source axes with the expected angles.
2288 let cands = world_lattice_candidates(Vec3::Z, Vec3::Y);
2289 assert_eq!(cands.len(), 4, "±Z must be excluded: {cands:?}");
2290 let angle_of = |axis: Vec3| {
2291 cands
2292 .iter()
2293 .find(|(_, a)| *a == axis)
2294 .unwrap_or_else(|| panic!("axis {axis:?} missing from {cands:?}"))
2295 .0
2296 };
2297 assert!(
2298 (angle_of(Vec3::X) + FRAC_PI_2).abs() < 1e-5,
2299 "X must sit at −π/2"
2300 );
2301 assert!(
2302 (angle_of(Vec3::NEG_X) - FRAC_PI_2).abs() < 1e-5,
2303 "−X must sit at +π/2"
2304 );
2305 assert!(angle_of(Vec3::Y).abs() < 1e-5, "Y must sit at 0");
2306 assert!(
2307 (angle_of(Vec3::NEG_Y).abs() - std::f32::consts::PI).abs() < 1e-5,
2308 "−Y must sit at ±π"
2309 );
2310 }
2311
2312 #[test]
2313 fn candidates_diagonal_forward_yield_six_axes() {
2314 // Diagonal view: every signed world axis survives, each exactly once.
2315 let local_z = -Vec3::ONE.normalize();
2316 let up = (Vec3::X - Vec3::X.dot(local_z) * local_z).normalize();
2317 let cands = world_lattice_candidates(local_z, up);
2318 assert_eq!(
2319 cands.len(),
2320 6,
2321 "all 6 axes survive on a diagonal: {cands:?}"
2322 );
2323 for axis in AXES {
2324 assert_eq!(
2325 cands.iter().filter(|(_, a)| *a == axis).count(),
2326 1,
2327 "axis {axis:?} must appear exactly once: {cands:?}"
2328 );
2329 }
2330 }
2331
2332 #[test]
2333 fn lattice_angles_equal_candidate_angles() {
2334 // The wrapper must be observably identical to the candidate angles.
2335 let diag_z = -Vec3::ONE.normalize();
2336 let diag_up = (Vec3::X - Vec3::X.dot(diag_z) * diag_z).normalize();
2337 for (local_z, up) in [(Vec3::Z, Vec3::Y), (diag_z, diag_up)] {
2338 let angles = world_lattice_angles(local_z, up);
2339 let cands = world_lattice_candidates(local_z, up);
2340 assert_eq!(angles.len(), cands.len());
2341 for (a, (c, _)) in angles.iter().zip(cands.iter()) {
2342 assert_eq!(a, c, "wrapper angle {a} != candidate angle {c}");
2343 }
2344 }
2345 }
2346
2347 // ─── Anchored look: candidate stepping ───────────────────────────────────
2348
2349 #[test]
2350 fn next_lattice_candidate_matches_next_lattice_step() {
2351 // Drifted up (10° off Y): the axis-carrying mirror must agree with the
2352 // locked next_lattice_step in both directions.
2353 let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
2354 let cands = world_lattice_candidates(Vec3::Z, up);
2355 let angles = world_lattice_angles(Vec3::Z, up);
2356 for dir in [1, -1] {
2357 let (cand_angle, _) = next_lattice_candidate(&cands, dir);
2358 let step = next_lattice_step(&angles, dir);
2359 assert_eq!(cand_angle, step, "dir {dir}: {cand_angle} != {step}");
2360 }
2361 }
2362
2363 #[test]
2364 fn next_candidate_q_yields_neg_x_e_yields_x() {
2365 use std::f32::consts::FRAC_PI_2;
2366 // From (local_z = Z, up = Y): Q travels +90° to the −X candidate,
2367 // E travels −90° to the +X candidate.
2368 let cands = world_lattice_candidates(Vec3::Z, Vec3::Y);
2369 let (q_angle, q_axis) = next_lattice_candidate(&cands, 1);
2370 assert!(
2371 (q_angle - FRAC_PI_2).abs() < 1e-5,
2372 "Q must travel +π/2, got {q_angle}"
2373 );
2374 assert_eq!(q_axis, Vec3::NEG_X);
2375 let (e_angle, e_axis) = next_lattice_candidate(&cands, -1);
2376 assert!(
2377 (e_angle + FRAC_PI_2).abs() < 1e-5,
2378 "E must travel −π/2, got {e_angle}"
2379 );
2380 assert_eq!(e_axis, Vec3::X);
2381 }
2382
2383 // ─── Anchored look: reference up and anchor commit ───────────────────────
2384
2385 #[test]
2386 fn snap_reference_up_fresh_and_opposite_use_up() {
2387 let up = Quat::from_axis_angle(Vec3::Z, 10_f32.to_radians()) * Vec3::Y;
2388 // Fresh press: no animation → reference is the current up.
2389 assert_eq!(snap_reference_up(None, Vec3::Z, up, 1), up);
2390 // Opposite-direction press mid-animation → reference is still up.
2391 let mut anim =
2392 start_or_retarget_snap(None, Vec3::Z, up, 1, 0.18, SnapRollEasing::EaseOutCubic);
2393 advance_snap(&mut anim, 0.054);
2394 assert_eq!(snap_reference_up(Some(anim), Vec3::Z, up, -1), up);
2395 }
2396
2397 #[test]
2398 fn snap_reference_up_same_dir_advances_residual() {
2399 let up0 = Vec3::Y;
2400 let mut anim =
2401 start_or_retarget_snap(None, Vec3::Z, up0, 1, 0.18, SnapRollEasing::EaseOutCubic);
2402 advance_snap(&mut anim, 0.054);
2403 // The transform rotated with the animation: up now reflects the
2404 // applied angle. Same-dir reference = up advanced by the residual,
2405 // i.e. the in-flight target up.
2406 let up_mid = Quat::from_axis_angle(Vec3::Z, anim.current_applied) * up0;
2407 let ref_up = snap_reference_up(Some(anim), Vec3::Z, up_mid, 1);
2408 let expected =
2409 Quat::from_axis_angle(Vec3::Z, anim.target_angle - anim.current_applied) * up_mid;
2410 assert!(
2411 ref_up.dot(expected) > 0.9999,
2412 "ref {ref_up:?} != target up {expected:?}"
2413 );
2414 // For this fresh anim the in-flight target is the −X candidate.
2415 assert!(
2416 ref_up.dot(Vec3::NEG_X) > 0.9999,
2417 "expected ~−X, got {ref_up:?}"
2418 );
2419 }
2420
2421 #[test]
2422 fn anchor_commit_matches_pending_projection() {
2423 let local_z = Vec3::Z;
2424 let dur = 0.18;
2425 let ease = SnapRollEasing::EaseOutCubic;
2426 let up0 = Quat::from_axis_angle(local_z, 10_f32.to_radians()) * Vec3::Y;
2427 let proj = |axis: Vec3| (axis - axis.dot(local_z) * local_z).normalize();
2428
2429 // Fresh Q: pending axis −X; the animation must land on its projection.
2430 let ref_up = snap_reference_up(None, local_z, up0, 1);
2431 let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
2432 assert_eq!(axis, Vec3::NEG_X);
2433 let anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
2434 let landed = Quat::from_axis_angle(local_z, anim.target_angle) * up0;
2435 assert!(
2436 landed.dot(proj(axis)) > 0.9999,
2437 "fresh: {landed:?} != proj({axis:?})"
2438 );
2439
2440 // Extend (same dir mid-anim): pending axis −Y, one candidate further.
2441 let mut anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
2442 advance_snap(&mut anim, 0.054);
2443 let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2444 let ref_up = snap_reference_up(Some(anim), local_z, up_mid, 1);
2445 let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), 1);
2446 assert_eq!(axis, Vec3::NEG_Y);
2447 let extended = start_or_retarget_snap(Some(anim), local_z, up_mid, 1, dur, ease);
2448 let landed = Quat::from_axis_angle(local_z, extended.target_angle) * up0;
2449 assert!(
2450 landed.dot(proj(axis)) > 0.9999,
2451 "extend: {landed:?} != proj({axis:?})"
2452 );
2453
2454 // Reverse (opposite dir mid-anim): pending axis +Y, behind current up.
2455 let mut anim = start_or_retarget_snap(None, local_z, up0, 1, dur, ease);
2456 advance_snap(&mut anim, 0.054);
2457 let up_mid = Quat::from_axis_angle(local_z, anim.current_applied) * up0;
2458 let ref_up = snap_reference_up(Some(anim), local_z, up_mid, -1);
2459 let (_, axis) = next_lattice_candidate(&world_lattice_candidates(local_z, ref_up), -1);
2460 assert_eq!(axis, Vec3::Y);
2461 let reversed = start_or_retarget_snap(Some(anim), local_z, up_mid, -1, dur, ease);
2462 let landed = Quat::from_axis_angle(local_z, reversed.target_angle) * up0;
2463 assert!(
2464 landed.dot(proj(axis)) > 0.9999,
2465 "reverse: {landed:?} != proj({axis:?})"
2466 );
2467 }
2468
2469 // ─── Anchored look: spawn anchor and defaults ────────────────────────────
2470
2471 #[test]
2472 fn nearest_world_axis_snaps_biased_vectors() {
2473 assert_eq!(nearest_world_axis(Vec3::new(0.9, 0.1, 0.2)), Vec3::X);
2474 assert_eq!(nearest_world_axis(Vec3::new(-2.0, 0.5, 0.5)), Vec3::NEG_X);
2475 assert_eq!(nearest_world_axis(Vec3::new(0.1, -1.5, 0.3)), Vec3::NEG_Y);
2476 assert_eq!(nearest_world_axis(Vec3::new(-0.1, 0.2, 0.95)), Vec3::Z);
2477 assert_eq!(nearest_world_axis(Vec3::new(0.2, 0.3, -0.9)), Vec3::NEG_Z);
2478 }
2479
2480 #[test]
2481 fn nearest_world_axis_tie_uses_axes_order() {
2482 // Strict `>` keeps the first max in AXES order [X, −X, Y, −Y, Z, −Z].
2483 assert_eq!(nearest_world_axis(Vec3::new(1.0, 1.0, 0.0)), Vec3::X);
2484 assert_eq!(nearest_world_axis(Vec3::new(0.0, 1.0, 1.0)), Vec3::Y);
2485 assert_eq!(nearest_world_axis(Vec3::new(-1.0, -1.0, -1.0)), Vec3::NEG_X);
2486 }
2487
2488 #[test]
2489 fn player_mode_defaults_to_sixdof() {
2490 let p = Player::default();
2491 assert!(matches!(
2492 p.mode,
2493 PlayerMode::FreeFlightSixDof {
2494 roll_mode: RollMode::Continuous
2495 }
2496 ));
2497 assert_eq!(p.anchor_up, Vec3::Y);
2498 assert!(p.pending_anchor.is_none());
2499 assert!(matches!(
2500 PlayerConfig::default().mode,
2501 PlayerMode::FreeFlightSixDof {
2502 roll_mode: RollMode::Continuous
2503 }
2504 ));
2505 }
2506
2507 #[test]
2508 fn anchored_mode_config_copies_to_player() {
2509 // Non-default value must propagate config → component.
2510 let config = PlayerConfig {
2511 mode: PlayerMode::FreeFlightAnchored,
2512 ..default()
2513 };
2514 let player = Player {
2515 mode: config.mode.clone(),
2516 ..default()
2517 };
2518 assert!(matches!(player.mode, PlayerMode::FreeFlightAnchored));
2519 }
2520
2521 // ---- Frame-loop integration tests -------------------------------------
2522 //
2523 // Three Anchored behaviors are frame-loop properties, not pure functions:
2524 // a level horizon under diagonal input, mouse-look staying on the OLD
2525 // anchor while a switch animates, and `RollMode::Continuous` being inert.
2526 // These drive `player_look` through a headless `App`.
2527
2528 /// Builds a headless app that runs `player_look` over one Anchored player
2529 /// starting from the identity transform (forward −Z, up +Y, right +X).
2530 fn anchored_app() -> (App, Entity) {
2531 let mut app = App::new();
2532 app.add_message::<MouseMotion>();
2533 app.insert_resource(ButtonInput::<KeyCode>::default());
2534 app.insert_resource(Time::<()>::default());
2535 app.add_systems(Update, player_look);
2536 let entity = app
2537 .world_mut()
2538 .spawn((
2539 Player {
2540 mode: PlayerMode::FreeFlightAnchored,
2541 ..default()
2542 },
2543 Transform::default(),
2544 ))
2545 .id();
2546 (app, entity)
2547 }
2548
2549 #[test]
2550 fn focus_loss_releases_capture_and_ignores_unfocused_click_and_escape() {
2551 use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
2552 let mut app = App::new();
2553 app.init_resource::<ButtonInput<KeyCode>>()
2554 .init_resource::<ButtonInput<MouseButton>>()
2555 .add_systems(Update, player_cursor_system);
2556 let window = app
2557 .world_mut()
2558 .spawn((
2559 Window {
2560 focused: false,
2561 ..default()
2562 },
2563 PrimaryWindow,
2564 CursorOptions {
2565 grab_mode: CursorGrabMode::Locked,
2566 visible: false,
2567 ..default()
2568 },
2569 ))
2570 .id();
2571 app.world_mut()
2572 .resource_mut::<ButtonInput<KeyCode>>()
2573 .press(KeyCode::Escape);
2574 app.world_mut()
2575 .resource_mut::<ButtonInput<MouseButton>>()
2576 .press(MouseButton::Left);
2577 app.update();
2578 let cursor = app
2579 .world()
2580 .get::<CursorOptions>(window)
2581 .expect("unfocused Escape must not close the window");
2582 assert_eq!(cursor.grab_mode, CursorGrabMode::None);
2583 assert!(cursor.visible);
2584 app.world_mut()
2585 .resource_mut::<ButtonInput<KeyCode>>()
2586 .reset_all();
2587 app.world_mut()
2588 .resource_mut::<ButtonInput<MouseButton>>()
2589 .reset_all();
2590 app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
2591 app.update();
2592 assert_eq!(
2593 app.world().get::<CursorOptions>(window).unwrap().grab_mode,
2594 CursorGrabMode::None
2595 );
2596 app.world_mut()
2597 .resource_mut::<ButtonInput<MouseButton>>()
2598 .press(MouseButton::Left);
2599 app.update();
2600 assert_eq!(
2601 app.world().get::<CursorOptions>(window).unwrap().grab_mode,
2602 CursorGrabMode::Locked
2603 );
2604 }
2605
2606 #[test]
2607 fn inactive_primary_window_discards_look_without_replaying_it() {
2608 use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
2609 let (mut app, player) = anchored_app();
2610 let window = app
2611 .world_mut()
2612 .spawn((
2613 Window {
2614 focused: false,
2615 ..default()
2616 },
2617 PrimaryWindow,
2618 ))
2619 .id();
2620 step(&mut app, Vec2::new(100.0, 20.0), &[KeyCode::KeyQ], 0.1);
2621 assert_eq!(
2622 app.world().get::<Transform>(player).unwrap().rotation,
2623 Quat::IDENTITY
2624 );
2625 assert!(
2626 app.world()
2627 .get::<Player>(player)
2628 .unwrap()
2629 .snap_anim
2630 .is_none()
2631 );
2632 app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
2633 app.world_mut()
2634 .get_mut::<CursorOptions>(window)
2635 .unwrap()
2636 .grab_mode = CursorGrabMode::Locked;
2637 step(&mut app, Vec2::ZERO, &[], 0.1);
2638 assert_eq!(
2639 app.world().get::<Transform>(player).unwrap().rotation,
2640 Quat::IDENTITY
2641 );
2642 step(&mut app, Vec2::new(10.0, 0.0), &[], 0.1);
2643 assert_ne!(
2644 app.world().get::<Transform>(player).unwrap().rotation,
2645 Quat::IDENTITY
2646 );
2647 }
2648
2649 #[test]
2650 fn spawning_player_leaves_cursor_free_until_focused_click() {
2651 use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
2652 let mut app = App::new();
2653 app.init_resource::<PlayerConfig>()
2654 .init_resource::<PlayerHealth>()
2655 .add_systems(Startup, spawn_player);
2656 let window = app
2657 .world_mut()
2658 .spawn((Window::default(), PrimaryWindow))
2659 .id();
2660 app.update();
2661 let cursor = app.world().get::<CursorOptions>(window).unwrap();
2662 assert_eq!(cursor.grab_mode, CursorGrabMode::None);
2663 assert!(cursor.visible);
2664 }
2665
2666 #[test]
2667 fn inactive_movement_clears_velocity_and_preserves_position() {
2668 use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
2669 let mut app = App::new();
2670 app.init_resource::<ButtonInput<KeyCode>>()
2671 .init_resource::<Time>()
2672 .init_resource::<ViewerPosition>()
2673 .init_resource::<ChunkManager>()
2674 .init_resource::<PlayerCrouching>()
2675 .add_systems(Update, player_move::<crate::voxel::DefaultVoxel>);
2676 let window = app
2677 .world_mut()
2678 .spawn((
2679 Window {
2680 focused: false,
2681 ..default()
2682 },
2683 PrimaryWindow,
2684 CursorOptions {
2685 grab_mode: CursorGrabMode::Locked,
2686 ..default()
2687 },
2688 ))
2689 .id();
2690 let player = app
2691 .world_mut()
2692 .spawn((
2693 Player {
2694 velocity: Vec3::Z,
2695 ..default()
2696 },
2697 Transform::default(),
2698 ))
2699 .id();
2700 app.world_mut()
2701 .resource_mut::<Time>()
2702 .advance_by(std::time::Duration::from_millis(100));
2703 app.world_mut()
2704 .resource_mut::<ButtonInput<KeyCode>>()
2705 .press(KeyCode::KeyW);
2706 app.update();
2707 assert_eq!(
2708 app.world().get::<Transform>(player).unwrap().translation,
2709 Vec3::ZERO
2710 );
2711 assert_eq!(
2712 app.world().get::<Player>(player).unwrap().velocity,
2713 Vec3::ZERO
2714 );
2715 app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
2716 app.world_mut()
2717 .get_mut::<CursorOptions>(window)
2718 .unwrap()
2719 .grab_mode = CursorGrabMode::None;
2720 app.update();
2721 assert_eq!(
2722 app.world().get::<Transform>(player).unwrap().translation,
2723 Vec3::ZERO
2724 );
2725 app.world_mut()
2726 .get_mut::<CursorOptions>(window)
2727 .unwrap()
2728 .grab_mode = CursorGrabMode::Locked;
2729 app.update();
2730 assert!(app.world().get::<Transform>(player).unwrap().translation.z < 0.0);
2731 }
2732
2733 /// Advances one frame: sets `dt`, applies the exact held-key set (freshly
2734 /// added keys register as `just_pressed`, persisting keys do not), injects
2735 /// mouse motion, then runs the schedule.
2736 fn step(app: &mut App, mouse: Vec2, held: &[KeyCode], dt: f32) {
2737 app.world_mut()
2738 .resource_mut::<Time>()
2739 .advance_by(std::time::Duration::from_secs_f32(dt));
2740 {
2741 let mut input = app.world_mut().resource_mut::<ButtonInput<KeyCode>>();
2742 input.clear(); // drop last frame's just_pressed / just_released
2743 let stale: Vec<KeyCode> = input
2744 .get_pressed()
2745 .copied()
2746 .filter(|k| !held.contains(k))
2747 .collect();
2748 for k in stale {
2749 input.release(k);
2750 }
2751 for k in held {
2752 input.press(*k);
2753 } // re-press keeps held keys out of just_pressed
2754 }
2755 if mouse != Vec2::ZERO {
2756 app.world_mut().write_message(MouseMotion { delta: mouse });
2757 }
2758 app.update();
2759 }
2760
2761 fn forward_of(app: &App, entity: Entity) -> Vec3 {
2762 *app.world()
2763 .entity(entity)
2764 .get::<Transform>()
2765 .unwrap()
2766 .forward()
2767 }
2768
2769 #[test]
2770 fn anchored_diagonal_input_keeps_horizon_level() {
2771 let (mut app, e) = anchored_app();
2772 // Strong diagonal input for enough frames to push pitch into the clamp.
2773 for _ in 0..15 {
2774 step(&mut app, Vec2::new(60.0, -80.0), &[], 0.016);
2775 let right = *app.world().entity(e).get::<Transform>().unwrap().right();
2776 // World-yaw around Y ∘ local-X pitch never rolls the frame: the
2777 // camera's right vector stays in the horizontal plane.
2778 assert!(
2779 right.dot(Vec3::Y).abs() < 1e-4,
2780 "horizon rolled: right·Y = {}",
2781 right.dot(Vec3::Y)
2782 );
2783 }
2784 // The ±89° clamp both engaged (we pushed past 88°) and held (never over).
2785 let elevation = forward_of(&app, e).dot(Vec3::Y).abs();
2786 assert!(
2787 elevation >= 88_f32.to_radians().sin(),
2788 "clamp never engaged: |forward·Y| = {elevation}"
2789 );
2790 assert!(
2791 elevation <= 89_f32.to_radians().sin() + 1e-4,
2792 "pitch exceeded ±89°: |forward·Y| = {elevation}"
2793 );
2794 }
2795
2796 #[test]
2797 fn anchored_switch_yaw_uses_old_anchor() {
2798 let (mut app, e) = anchored_app();
2799 // Frame 1: tap Q to begin a switch. The default 0.5s duration keeps it
2800 // running across the next frame (2 × 0.1s = 0.2s < 0.5s).
2801 step(&mut app, Vec2::ZERO, &[KeyCode::KeyQ], 0.1);
2802 {
2803 let p = app.world().entity(e).get::<Player>().unwrap();
2804 assert!(p.snap_anim.is_some(), "Q should start a switch animation");
2805 assert!(p.pending_anchor.is_some(), "pending anchor should be set");
2806 assert_eq!(p.anchor_up, Vec3::Y, "anchor must not commit mid-animation");
2807 }
2808 let before = forward_of(&app, e);
2809 // Frame 2: release Q, yaw with the mouse while the switch still runs.
2810 step(&mut app, Vec2::new(50.0, 0.0), &[], 0.1);
2811 let p = app.world().entity(e).get::<Player>().unwrap();
2812 assert!(p.snap_anim.is_some(), "animation should still be running");
2813 assert_eq!(
2814 p.anchor_up,
2815 Vec3::Y,
2816 "yaw must not commit the pending anchor"
2817 );
2818 let after = forward_of(&app, e);
2819 // Yaw ran around the OLD anchor (world Y): a rotation about Y preserves
2820 // forward·Y, and the pending axis is non-Y, so a wrong anchor would
2821 // tilt forward out of the horizontal plane.
2822 assert!(
2823 after.dot(Vec3::Y).abs() < 1e-5,
2824 "yaw left the Y-plane → wrong anchor"
2825 );
2826 assert!(
2827 (after - before).length() > 1e-3,
2828 "yaw had no visible effect"
2829 );
2830 }
2831
2832 #[test]
2833 fn anchored_q_switches_anchor() {
2834 let (mut app, e) = anchored_app();
2835 // In SixDof this would roll the frame every tick; in Anchored, Q must
2836 // instead begin an animated anchor switch — RollMode is inert.
2837 step(&mut app, Vec2::ZERO, &[KeyCode::KeyQ], 0.1);
2838 let p = app.world().entity(e).get::<Player>().unwrap();
2839 assert!(
2840 p.snap_anim.is_some() && p.pending_anchor.is_some(),
2841 "Continuous roll_mode must be inert in Anchored — Q takes the switch path"
2842 );
2843 }
2844}