Skip to main content

voxel_framework/ui/
pause_menu.rs

1//! Optional pause menu with a settings submenu for FOV and SFX volume.
2//!
3//! This module implements a self-contained pause flow driven by the
4//! [`PauseMenuState`] state machine. Add [`PauseMenuPlugin`] to wire it up;
5//! then gate your own gameplay systems on [`PauseMenuState::Playing`] so they
6//! freeze automatically when the player pauses.
7//!
8//! # State machine
9//!
10//! ```text
11//!                  Escape
12//! ┌─────────┐ ──────────────► ┌────────┐
13//! │ Playing │                 │ Paused │ ◄─────────────────┐
14//! └─────────┘ ◄────────────── └────────┘                   │
15//!                Resume btn /       │ Settings btn          │
16//!                Escape             ▼                       │
17//!                             ┌──────────┐  ← Back btn     │
18//!                             │ Settings │ ────────────────►┘
19//!                             └──────────┘
20//! ```
21//!
22//! **Cursor management:** entering `Paused` releases the primary window's
23//! cursor (`CursorGrabMode::None`, visible). Returning to `Playing` re-locks
24//! it (`CursorGrabMode::Locked`, hidden) when the window is focused.
25//!
26//! This plugin does not capture the cursor on the first click or release it
27//! when the window loses focus. Add
28//! [`PlayerPlugin`](crate::player::PlayerPlugin), or
29//! [`player_cursor_system`](crate::player::player_cursor_system) on its own,
30//! for that: when this plugin is installed the cursor system leaves Escape to
31//! the pause menu, so the two work together.
32//!
33//! # Integration
34//!
35//! [`PlayerPlugin`](crate::player::PlayerPlugin) pauses with the menu on its
36//! own. Gate your other gameplay systems on [`PauseMenuState::Playing`]:
37//!
38//! ```rust,no_run
39//! use bevy::prelude::*;
40//! use voxel_framework::prelude::*;
41//! use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
42//!
43//! fn my_gameplay_system() {}
44//!
45//! App::new()
46//!     .add_plugins(DefaultPlugins)
47//!     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
48//!     .add_plugins(PauseMenuPlugin)
49//!     .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
50//!     .add_systems(Update, my_gameplay_system.run_if(in_state(PauseMenuState::Playing)));
51//! ```
52
53use bevy::asset::embedded_asset;
54use bevy::prelude::*;
55
56use crate::audio::{SfxConfig, SfxEvent, SfxRequest};
57use crate::player::{Player, PlayerConfig};
58use crate::settings::{RENDER_DISTANCE_STEP, RENDER_DISTANCE_UNLOAD_MARGIN};
59use crate::world::{ChunkManager, WorldConfig};
60
61/// Asset path of the NotoSans font embedded into the framework binary.
62///
63/// The `embedded://` scheme is registered by the Bevy `EmbeddedAssetPlugin`
64/// (part of `AssetPlugin` / `DefaultPlugins`). The path format is
65/// `embedded://{crate_name}/{path relative to the crate's `src/` dir}`, where
66/// the crate name uses underscores. See [`PauseMenuPlugin`] for how this font
67/// becomes the default value of [`PauseMenuConfig::font`].
68pub const EMBEDDED_NOTO_SANS_PATH: &str = "embedded://voxel_framework/ui/NotoSans-Regular.ttf";
69
70/// Asset path of the NotoSansSymbols2 font embedded into the framework binary.
71///
72/// Used exclusively to render symbol glyphs (e.g. `◀`, `▶`) that are absent
73/// from the subset of NotoSans shipped at [`EMBEDDED_NOTO_SANS_PATH`]. The
74/// `embedded://` scheme is registered by the Bevy `EmbeddedAssetPlugin` (part
75/// of `AssetPlugin` / `DefaultPlugins`).
76pub const EMBEDDED_NOTO_SYMBOLS_PATH: &str =
77    "embedded://voxel_framework/ui/NotoSansSymbols2-Regular.ttf";
78
79// ─── State ────────────────────────────────────────────────────────────────────
80
81/// Bevy state enum that drives the pause menu lifecycle.
82///
83/// [`PauseMenuPlugin`] registers this as a Bevy `State` and transitions between
84/// variants automatically. Your own systems should use `run_if(in_state(…))`
85/// to participate in the pause flow.
86///
87/// # Variant transitions
88///
89/// | From | Trigger | To |
90/// |------|---------|-----|
91/// | `Playing` | Escape key | `Paused` |
92/// | `Paused` | Resume button or Escape | `Playing` |
93/// | `Paused` | Settings button | `Settings` |
94/// | `Settings` | Back button | `Paused` |
95///
96/// # Gating gameplay systems
97///
98/// ```rust,no_run
99/// # use bevy::prelude::*;
100/// # use voxel_framework::ui::PauseMenuState;
101/// # fn my_gameplay_system() {}
102/// App::new()
103///     .add_systems(Update,
104///         my_gameplay_system.run_if(in_state(PauseMenuState::Playing)),
105///     );
106/// ```
107#[derive(States, Debug, Clone, PartialEq, Eq, Hash, Default)]
108pub enum PauseMenuState {
109    /// The game is running normally. Player input is active and the pause
110    /// menu is not visible. This is the default starting state.
111    #[default]
112    Playing,
113    /// The game is paused. The pause menu overlay is displayed and gameplay
114    /// systems gated on `Playing` are inactive. The cursor is free.
115    Paused,
116    /// The settings submenu is open. The pause menu overlay is replaced by the
117    /// settings panel. FOV and SFX volume can be adjusted here.
118    Settings,
119}
120
121// ─── Theme ────────────────────────────────────────────────────────────────────
122
123/// Colors of one kind of menu button, per interaction state.
124///
125/// Used by [`PauseMenuTheme::button`] and
126/// [`PauseMenuTheme::secondary_button`]. The default is the dark blue-grey
127/// button with white text that the pause menu has always drawn.
128///
129/// | Field     | Default                         |
130/// |-----------|---------------------------------|
131/// | `normal`  | `Color::srgb(0.15, 0.15, 0.20)` |
132/// | `hovered` | `Color::srgb(0.25, 0.25, 0.35)` |
133/// | `pressed` | `Color::srgb(0.35, 0.35, 0.50)` |
134/// | `text`    | `Color::WHITE`                  |
135#[derive(Debug, Clone, Copy, PartialEq)]
136pub struct ButtonColors {
137    /// Background while the pointer is elsewhere.
138    pub normal: Color,
139    /// Background while the pointer is over the button.
140    pub hovered: Color,
141    /// Background while the button is held down.
142    pub pressed: Color,
143    /// Color of the button's label. It does not change with the interaction
144    /// state.
145    pub text: Color,
146}
147
148impl ButtonColors {
149    /// Background color for an interaction state: `normal` for
150    /// [`Interaction::None`], `hovered` for [`Interaction::Hovered`] and
151    /// `pressed` for [`Interaction::Pressed`].
152    pub fn background(&self, interaction: Interaction) -> Color {
153        match interaction {
154            Interaction::None => self.normal,
155            Interaction::Hovered => self.hovered,
156            Interaction::Pressed => self.pressed,
157        }
158    }
159}
160
161impl Default for ButtonColors {
162    fn default() -> Self {
163        Self {
164            normal: Color::srgb(0.15, 0.15, 0.20),
165            hovered: Color::srgb(0.25, 0.25, 0.35),
166            pressed: Color::srgb(0.35, 0.35, 0.50),
167            text: Color::WHITE,
168        }
169    }
170}
171
172/// Colors and panel layout of the pause menu and its settings submenu.
173///
174/// Insert this resource to restyle the menus drawn by [`PauseMenuPlugin`];
175/// the plugin initializes it with [`Default`] when the game has not inserted
176/// one, and never replaces one that is already there. The default reproduces
177/// the look the menu had before this resource existed: white text and dark
178/// buttons straight on a dimmed scene, with an invisible panel that is as
179/// large as its content.
180///
181/// Both menus share the same structure: a full-screen overlay
182/// ([`overlay`](Self::overlay)) that dims the scene, and a centered panel
183/// ([`panel`](Self::panel), [`panel_width`](Self::panel_width),
184/// [`panel_padding`](Self::panel_padding)) that holds the title and the
185/// controls. Fonts stay in [`PauseMenuConfig`].
186///
187/// The theme is read when a menu is opened and when a button changes
188/// interaction state. Changing it while a menu is open restyles the buttons
189/// as they are next hovered or pressed and everything else the next time the
190/// menu is opened.
191///
192/// Build it with struct-update syntax (`..Default::default()`) so that fields
193/// added later do not break your code.
194///
195/// # Default values
196///
197/// | Field              | Default                             |
198/// |--------------------|-------------------------------------|
199/// | `overlay`          | `Color::srgba(0.0, 0.0, 0.0, 0.78)` |
200/// | `panel`            | `Color::NONE` (invisible)           |
201/// | `header`           | `Color::WHITE`                      |
202/// | `text`             | `Color::WHITE`                      |
203/// | `label`            | `Color::srgb(0.8, 0.8, 0.8)`        |
204/// | `button`           | default [`ButtonColors`]            |
205/// | `secondary_button` | default [`ButtonColors`]            |
206/// | `corner_radius`    | `0.0`                               |
207/// | `panel_width`      | `Val::Auto` (fits its content)      |
208/// | `panel_padding`    | `UiRect::ZERO`                      |
209///
210/// # Example
211///
212/// A light card with dark text over a dimmed scene:
213///
214/// ```rust,no_run
215/// use bevy::prelude::*;
216/// use voxel_framework::prelude::*;
217///
218/// App::new()
219///     .add_plugins(DefaultPlugins)
220///     .insert_resource(PauseMenuTheme {
221///         overlay: Color::srgba(0.0, 0.0, 0.0, 0.5),
222///         panel: Color::srgb(0.95, 0.95, 0.92),
223///         header: Color::srgb(0.1, 0.1, 0.1),
224///         text: Color::srgb(0.1, 0.1, 0.1),
225///         label: Color::srgb(0.3, 0.3, 0.3),
226///         button: ButtonColors {
227///             normal: Color::srgb(0.2, 0.2, 0.2),
228///             hovered: Color::srgb(0.3, 0.3, 0.3),
229///             pressed: Color::srgb(0.1, 0.1, 0.1),
230///             text: Color::WHITE,
231///         },
232///         secondary_button: ButtonColors {
233///             normal: Color::srgb(0.8, 0.8, 0.78),
234///             hovered: Color::srgb(0.7, 0.7, 0.68),
235///             pressed: Color::srgb(0.6, 0.6, 0.58),
236///             text: Color::srgb(0.1, 0.1, 0.1),
237///         },
238///         corner_radius: 8.0,
239///         panel_width: Val::Px(520.0),
240///         panel_padding: UiRect::all(Val::Px(32.0)),
241///         ..Default::default()
242///     })
243///     .add_plugins(PauseMenuPlugin)
244///     .run();
245/// ```
246#[derive(Resource, Debug, Clone, PartialEq)]
247pub struct PauseMenuTheme {
248    /// Color of the full-screen overlay behind the panel. Its alpha decides
249    /// how much the scene is dimmed.
250    pub overlay: Color,
251    /// Background of the centered panel (the "card") that holds the title and
252    /// the controls. `Color::NONE` by default, so the controls appear
253    /// directly on the overlay.
254    pub panel: Color,
255    /// Color of the menu title (`PAUSED`, `SETTINGS`).
256    pub header: Color,
257    /// Color of the current value shown between the two arrow buttons of
258    /// each settings row.
259    pub text: Color,
260    /// Color of the name at the start of each settings row (`Field of View`,
261    /// `SFX Volume`, …).
262    pub label: Color,
263    /// Colors of the primary buttons: `Resume` in the pause menu and `Back`
264    /// in the settings submenu.
265    pub button: ButtonColors,
266    /// Colors of every other button: `Settings` and `Quit` in the pause menu
267    /// and the arrow buttons of the settings rows.
268    pub secondary_button: ButtonColors,
269    /// Corner radius, in logical pixels, of the panel and of every button.
270    /// `0.0` gives square corners.
271    pub corner_radius: f32,
272    /// Width of the panel. `Val::Auto` makes it as wide as its content: 280
273    /// logical pixels in the pause menu and about 400 in the settings submenu.
274    /// The content does not shrink, so a narrower value lets it overflow.
275    pub panel_width: Val,
276    /// Space between the edges of the panel and its content.
277    pub panel_padding: UiRect,
278}
279
280impl Default for PauseMenuTheme {
281    fn default() -> Self {
282        Self {
283            overlay: Color::srgba(0.0, 0.0, 0.0, 0.78),
284            panel: Color::NONE,
285            header: Color::WHITE,
286            text: Color::WHITE,
287            label: Color::srgb(0.8, 0.8, 0.8),
288            button: ButtonColors::default(),
289            secondary_button: ButtonColors::default(),
290            corner_radius: 0.0,
291            panel_width: Val::Auto,
292            panel_padding: UiRect::ZERO,
293        }
294    }
295}
296
297/// The theme to draw with: the game's resource, or the default look when the
298/// resource is absent (systems run without [`PauseMenuPlugin`]).
299fn current_theme(theme: Option<Res<PauseMenuTheme>>) -> PauseMenuTheme {
300    theme.as_deref().cloned().unwrap_or_default()
301}
302
303/// A menu button action that knows which [`ButtonColors`] of the theme it is
304/// drawn with.
305trait ThemedButton {
306    fn colors(&self, theme: &PauseMenuTheme) -> ButtonColors;
307}
308
309// ─── Markers ─────────────────────────────────────────────────────────────────
310
311#[derive(Component)]
312struct PauseMenuRoot;
313#[derive(Component)]
314struct SettingsMenuRoot;
315/// The centered panel of either menu; child of the overlay root.
316#[derive(Component)]
317struct PauseMenuPanel;
318#[derive(Component)]
319struct FovLabel;
320#[derive(Component)]
321struct VolumeLabel;
322#[derive(Component)]
323struct RenderDistLabel;
324#[derive(Component)]
325struct SensitivityLabel;
326
327#[derive(Component)]
328enum PauseButton {
329    Resume,
330    Settings,
331    Quit,
332}
333
334#[derive(Component)]
335enum SettingsButton {
336    FovInc,
337    FovDec,
338    VolumeInc,
339    VolumeDec,
340    RenderDistInc,
341    RenderDistDec,
342    SensitivityInc,
343    SensitivityDec,
344    Back,
345}
346
347impl ThemedButton for PauseButton {
348    fn colors(&self, theme: &PauseMenuTheme) -> ButtonColors {
349        match self {
350            PauseButton::Resume => theme.button,
351            PauseButton::Settings | PauseButton::Quit => theme.secondary_button,
352        }
353    }
354}
355
356impl ThemedButton for SettingsButton {
357    fn colors(&self, theme: &PauseMenuTheme) -> ButtonColors {
358        match self {
359            SettingsButton::Back => theme.button,
360            _ => theme.secondary_button,
361        }
362    }
363}
364
365// ─── Messages ─────────────────────────────────────────────────────────────────
366
367/// Emitted when the player clicks Back in the Settings submenu.
368///
369/// [`crate::settings::SettingsPlugin`] writes the current settings (FOV,
370/// volume, render distance, sensitivity) to disk when it arrives. Without
371/// that plugin the host game listens for this message and persists them with
372/// [`crate::settings::PersistedSettings`].
373#[derive(Message, Debug, Clone)]
374pub struct SaveSettingsRequest;
375
376// ─── Config ───────────────────────────────────────────────────────────────────
377
378/// Font configuration for [`PauseMenuPlugin`]. Colors and panel layout are in
379/// [`PauseMenuTheme`].
380///
381/// Insert this resource before adding [`PauseMenuPlugin`] to supply a custom
382/// font. If omitted, [`PauseMenuPlugin`] populates `font` with the framework's
383/// embedded [NotoSans](https://fonts.google.com/noto/specimen/Noto+Sans)
384/// regular TTF — a unicode-capable font that renders the settings submenu's
385/// arrow glyphs (`←`, `◀`, `▶`) without tofu.
386///
387/// # Example
388///
389/// ```rust,no_run
390/// use bevy::prelude::*;
391/// use voxel_framework::ui::PauseMenuConfig;
392///
393/// fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
394///     commands.insert_resource(PauseMenuConfig {
395///         font: asset_server.load("fonts/MyFont.ttf"),
396///         symbol_font: asset_server.load("fonts/MyFont.ttf"),
397///     });
398/// }
399/// ```
400#[derive(Resource, Clone)]
401pub struct PauseMenuConfig {
402    /// Font handle used for every text element in both the pause menu and the
403    /// settings submenu (title, button labels, slider values).
404    ///
405    /// Defaults to [`Handle::default()`] at construction time. [`PauseMenuPlugin`]
406    /// replaces the default handle with the embedded NotoSans font during
407    /// `Startup` (see `EMBEDDED_NOTO_SANS_PATH`) so games inherit a legible
408    /// unicode-capable font without loading any asset themselves. To override,
409    /// insert [`PauseMenuConfig`] with a custom `font` handle before the menu is
410    /// first spawned.
411    pub font: Handle<Font>,
412    /// Font handle used for symbol-only glyphs that are absent from the main
413    /// [`font`](Self::font) subset — specifically the `◀` and `▶` triangle
414    /// glyphs used on the settings slider inc/dec buttons.
415    ///
416    /// Defaults to [`Handle::default()`] at construction time. [`PauseMenuPlugin`]
417    /// replaces the default handle with the embedded NotoSansSymbols2 font
418    /// during `Startup` (see `EMBEDDED_NOTO_SYMBOLS_PATH`). To override,
419    /// insert [`PauseMenuConfig`] with a custom `symbol_font` handle before the
420    /// menu is first spawned.
421    pub symbol_font: Handle<Font>,
422}
423
424impl Default for PauseMenuConfig {
425    fn default() -> Self {
426        Self {
427            font: Handle::default(),
428            symbol_font: Handle::default(),
429        }
430    }
431}
432
433// ─── Plugin ───────────────────────────────────────────────────────────────────
434
435/// Plugin that adds a full-screen pause menu with a settings submenu.
436///
437/// Registers [`PauseMenuState`] and wires all transitions, UI spawning, and
438/// cursor management. The settings submenu exposes real-time controls for FOV
439/// (±5° per click, clamped to `50°`–`120°`) and SFX volume (±10% per click,
440/// clamped to `0%`–`100%`).
441///
442/// Colors and panel layout come from the [`PauseMenuTheme`] resource; fonts
443/// from [`PauseMenuConfig`].
444///
445/// Handles cursor releasing and locking as part of the `Playing ↔ Paused`
446/// transition. First-click capture and focus-loss release come from
447/// [`player_cursor_system`](crate::player::player_cursor_system), which
448/// [`PlayerPlugin`](crate::player::PlayerPlugin) registers and which defers
449/// Escape to this plugin when both are present.
450///
451/// # Simple usage
452///
453/// ```rust,no_run
454/// use bevy::prelude::*;
455/// use voxel_framework::prelude::*;
456/// use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
457///
458/// App::new()
459///     .add_plugins(DefaultPlugins)
460///     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
461///     .add_plugins(PauseMenuPlugin)
462///     .run();
463/// ```
464///
465/// # With hand-registered player systems
466///
467/// Include [`player_cursor_system`](crate::player::player_cursor_system) so the
468/// first click captures the cursor and focus loss releases it:
469///
470/// ```rust,no_run
471/// use bevy::prelude::*;
472/// use voxel_framework::prelude::*;
473/// use voxel_framework::player::{spawn_player, player_cursor_system, player_look,
474///     player_move, player_resolve_collision};
475/// use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
476///
477/// App::new()
478///     .add_plugins(DefaultPlugins)
479///     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
480///     .add_plugins(PauseMenuPlugin)
481///     .add_systems(Startup, spawn_player)
482///     .add_systems(Update,
483///         (player_cursor_system, player_look, player_move::<DefaultVoxel>,
484///             player_resolve_collision::<DefaultVoxel>)
485///             .chain()
486///             .run_if(in_state(PauseMenuState::Playing)),
487///     );
488/// ```
489pub struct PauseMenuPlugin;
490
491impl Plugin for PauseMenuPlugin {
492    fn build(&self, app: &mut App) {
493        // Embed the NotoSans TTF into the framework binary. The resulting asset
494        // is reachable from any `AssetServer::load(...)` call via the
495        // `embedded://` scheme — see [`EMBEDDED_NOTO_SANS_PATH`].
496        embedded_asset!(app, "NotoSans-Regular.ttf");
497        embedded_asset!(app, "NotoSansSymbols2-Regular.ttf");
498
499        app.init_resource::<PauseMenuConfig>();
500        app.init_resource::<PauseMenuTheme>();
501        app.init_state::<PauseMenuState>();
502        app.add_message::<SaveSettingsRequest>();
503
504        // Populate `PauseMenuConfig::font` with the embedded NotoSans handle
505        // when the user hasn't supplied their own font. Runs once on `Startup`,
506        // which fires before any `OnEnter(Paused)` transition can spawn the
507        // menu, so the handle is always ready by the time the menu is built.
508        app.add_systems(Startup, load_default_font);
509
510        // Playing — toggle on Escape
511        app.add_systems(
512            Update,
513            toggle_pause.run_if(in_state(PauseMenuState::Playing)),
514        );
515
516        // Paused
517        app.add_systems(
518            OnEnter(PauseMenuState::Paused),
519            (spawn_pause_menu, release_cursor),
520        );
521        app.add_systems(OnExit(PauseMenuState::Paused), despawn_pause_menu);
522        app.add_systems(
523            Update,
524            (handle_pause_buttons, escape_to_resume).run_if(in_state(PauseMenuState::Paused)),
525        );
526
527        // Settings
528        app.add_systems(OnEnter(PauseMenuState::Settings), spawn_settings_menu);
529        app.add_systems(OnExit(PauseMenuState::Settings), despawn_settings_menu);
530        app.add_systems(
531            Update,
532            handle_settings_buttons.run_if(in_state(PauseMenuState::Settings)),
533        );
534    }
535}
536
537// ─── Default font loader ──────────────────────────────────────────────────────
538
539/// Populates [`PauseMenuConfig::font`] with the embedded NotoSans font on
540/// startup if the game has not supplied a custom font.
541///
542/// `Default` can't access the [`AssetServer`], so we use a startup sentinel:
543/// when `font == Handle::default()` (the weak, uninitialised handle produced
544/// by [`PauseMenuConfig::default()`]), we load the embedded font and overwrite
545/// the field. Games that insert their own [`PauseMenuConfig`] before this
546/// plugin — or before `Startup` runs — keep their custom handle untouched.
547fn load_default_font(mut cfg: ResMut<PauseMenuConfig>, asset_server: Res<AssetServer>) {
548    if cfg.font == Handle::default() {
549        cfg.font = asset_server.load(EMBEDDED_NOTO_SANS_PATH);
550    }
551    if cfg.symbol_font == Handle::default() {
552        cfg.symbol_font = asset_server.load(EMBEDDED_NOTO_SYMBOLS_PATH);
553    }
554}
555
556// ─── Cursor helpers ───────────────────────────────────────────────────────────
557
558/// Releases the cursor when entering [`PauseMenuState::Paused`].
559///
560/// Called via `OnEnter(Paused)`. Sets `CursorGrabMode::None` on the primary
561/// window and makes the cursor visible so the player can interact with the
562/// menu buttons.
563fn release_cursor(mut windows: PrimaryCursor) {
564    for (_, mut cursor) in &mut windows {
565        cursor.grab_mode = bevy::window::CursorGrabMode::None;
566        cursor.visible = true;
567    }
568}
569
570/// The primary window and its cursor options: the only cursor the pause menu
571/// manages.
572type PrimaryCursor<'w, 's> = Query<
573    'w,
574    's,
575    (&'static Window, &'static mut bevy::window::CursorOptions),
576    With<bevy::window::PrimaryWindow>,
577>;
578
579/// Re-locks the cursor when returning to [`PauseMenuState::Playing`].
580///
581/// Called as a plain function (not a system) from [`escape_to_resume`] and
582/// [`handle_pause_buttons`] so that cursor re-lock and state transition happen
583/// in the same frame without a one-frame gap.
584///
585/// An unfocused window is left alone: a window must be focused before its
586/// cursor is captured, and a click captures it later.
587fn lock_cursor(windows: &mut PrimaryCursor) {
588    for (window, mut cursor) in windows.iter_mut() {
589        if !window.focused {
590            continue;
591        }
592        cursor.grab_mode = bevy::window::CursorGrabMode::Locked;
593        cursor.visible = false;
594    }
595}
596
597// ─── Toggle pause ─────────────────────────────────────────────────────────────
598
599/// Transitions from `Playing` → `Paused` when Escape is pressed.
600///
601/// Runs only in [`PauseMenuState::Playing`]. Also fires a
602/// [`SfxEvent::PauseOpen`] sound request.
603fn toggle_pause(
604    keys: Res<ButtonInput<KeyCode>>,
605    mut next: ResMut<NextState<PauseMenuState>>,
606    mut sfx: MessageWriter<SfxRequest>,
607) {
608    if keys.just_pressed(KeyCode::Escape) {
609        next.set(PauseMenuState::Paused);
610        sfx.write(SfxRequest {
611            event: SfxEvent::PauseOpen,
612            position: None,
613        });
614    }
615}
616
617/// Transitions from `Paused` → `Playing` when Escape is pressed.
618///
619/// Runs only in [`PauseMenuState::Paused`]. Re-locks the cursor via
620/// [`lock_cursor`] in the same frame and fires [`SfxEvent::PauseClose`].
621fn escape_to_resume(
622    keys: Res<ButtonInput<KeyCode>>,
623    mut next: ResMut<NextState<PauseMenuState>>,
624    mut windows: PrimaryCursor,
625    mut sfx: MessageWriter<SfxRequest>,
626) {
627    if keys.just_pressed(KeyCode::Escape) {
628        next.set(PauseMenuState::Playing);
629        lock_cursor(&mut windows);
630        sfx.write(SfxRequest {
631            event: SfxEvent::PauseClose,
632            position: None,
633        });
634    }
635}
636
637// ─── Spawn helpers ────────────────────────────────────────────────────────────
638
639fn spawn_btn<C: Component + ThemedButton>(
640    parent: &mut ChildSpawnerCommands,
641    label: &str,
642    action: C,
643    width: f32,
644    height: f32,
645    font: Handle<Font>,
646    theme: &PauseMenuTheme,
647) {
648    let colors = action.colors(theme);
649    parent
650        .spawn((
651            action,
652            Button,
653            Node {
654                width: Val::Px(width),
655                height: Val::Px(height),
656                justify_content: JustifyContent::Center,
657                align_items: AlignItems::Center,
658                border_radius: BorderRadius::all(Val::Px(theme.corner_radius)),
659                ..default()
660            },
661            BackgroundColor(colors.normal),
662        ))
663        .with_children(|b| {
664            b.spawn((
665                Text::new(label),
666                TextFont {
667                    font,
668                    font_size: 20.0,
669                    ..default()
670                },
671                TextColor(colors.text),
672            ));
673        });
674}
675
676fn overlay_node(theme: &PauseMenuTheme) -> (Node, BackgroundColor) {
677    (
678        Node {
679            width: Val::Percent(100.0),
680            height: Val::Percent(100.0),
681            flex_direction: FlexDirection::Column,
682            justify_content: JustifyContent::Center,
683            align_items: AlignItems::Center,
684            row_gap: Val::Px(14.0),
685            ..default()
686        },
687        BackgroundColor(theme.overlay),
688    )
689}
690
691/// The centered panel that holds a menu's title and controls.
692///
693/// It lays its children out exactly as the overlay used to (centered column,
694/// 14 px gap), so with the default theme (no background, automatic width, no
695/// padding) the menu looks as it did when the overlay held them directly.
696fn panel_node(theme: &PauseMenuTheme) -> (PauseMenuPanel, Node, BackgroundColor) {
697    (
698        PauseMenuPanel,
699        Node {
700            width: theme.panel_width,
701            padding: theme.panel_padding,
702            flex_direction: FlexDirection::Column,
703            justify_content: JustifyContent::Center,
704            align_items: AlignItems::Center,
705            row_gap: Val::Px(14.0),
706            border_radius: BorderRadius::all(Val::Px(theme.corner_radius)),
707            ..default()
708        },
709        BackgroundColor(theme.panel),
710    )
711}
712
713// ─── Pause menu ───────────────────────────────────────────────────────────────
714
715/// Spawns the pause menu overlay when entering [`PauseMenuState::Paused`].
716///
717/// Builds a full-screen semi-transparent overlay with a centered panel that
718/// holds the title and three buttons: Resume, Settings, and Quit. Colors and
719/// panel layout come from [`PauseMenuTheme`]. Runs via `OnEnter(Paused)`.
720fn spawn_pause_menu(
721    mut commands: Commands,
722    config: Res<PauseMenuConfig>,
723    theme: Option<Res<PauseMenuTheme>>,
724) {
725    let theme = current_theme(theme);
726    let (node, bg) = overlay_node(&theme);
727    commands
728        .spawn((PauseMenuRoot, node, bg))
729        .with_children(|overlay| {
730            overlay.spawn(panel_node(&theme)).with_children(|p| {
731                p.spawn((
732                    Text::new("PAUSED"),
733                    TextFont {
734                        font: config.font.clone(),
735                        font_size: 52.0,
736                        ..default()
737                    },
738                    TextColor(theme.header),
739                    Node {
740                        margin: UiRect::bottom(Val::Px(28.0)),
741                        ..default()
742                    },
743                ));
744                spawn_btn(
745                    p,
746                    "Resume",
747                    PauseButton::Resume,
748                    280.0,
749                    52.0,
750                    config.font.clone(),
751                    &theme,
752                );
753                spawn_btn(
754                    p,
755                    "Settings",
756                    PauseButton::Settings,
757                    280.0,
758                    52.0,
759                    config.font.clone(),
760                    &theme,
761                );
762                spawn_btn(
763                    p,
764                    "Quit",
765                    PauseButton::Quit,
766                    280.0,
767                    52.0,
768                    config.font.clone(),
769                    &theme,
770                );
771            });
772        });
773}
774
775/// Despawns the pause menu overlay when leaving [`PauseMenuState::Paused`].
776///
777/// Runs via `OnExit(Paused)`, which fires for both `Paused → Playing` and
778/// `Paused → Settings` transitions.
779fn despawn_pause_menu(mut commands: Commands, q: Query<Entity, With<PauseMenuRoot>>) {
780    for e in &q {
781        commands.entity(e).despawn();
782    }
783}
784
785/// Handles hover/press styling and click actions for pause menu buttons.
786///
787/// Runs every frame in [`PauseMenuState::Paused`]. Updates button background
788/// colors on hover and press from [`PauseMenuTheme`], then on `Pressed`
789/// dispatches: Resume → `Playing` (re-locks cursor), Settings → `Settings`,
790/// Quit → [`AppExit`].
791fn handle_pause_buttons(
792    mut q: Query<
793        (&Interaction, &mut BackgroundColor, &PauseButton),
794        (Changed<Interaction>, With<Button>),
795    >,
796    mut next: ResMut<NextState<PauseMenuState>>,
797    mut windows: PrimaryCursor,
798    mut app_exit: MessageWriter<AppExit>,
799    mut sfx: MessageWriter<SfxRequest>,
800    theme: Option<Res<PauseMenuTheme>>,
801) {
802    let theme = current_theme(theme);
803    for (interaction, mut bg, action) in &mut q {
804        *bg = BackgroundColor(action.colors(&theme).background(*interaction));
805        if *interaction != Interaction::Pressed {
806            continue;
807        }
808        match action {
809            PauseButton::Resume => {
810                next.set(PauseMenuState::Playing);
811                lock_cursor(&mut windows);
812                sfx.write(SfxRequest {
813                    event: SfxEvent::PauseClose,
814                    position: None,
815                });
816            }
817            PauseButton::Settings => next.set(PauseMenuState::Settings),
818            PauseButton::Quit => {
819                app_exit.write(AppExit::Success);
820            }
821        }
822    }
823}
824
825// ─── Settings menu ────────────────────────────────────────────────────────────
826
827/// Spawns the settings overlay when entering [`PauseMenuState::Settings`].
828///
829/// Reads the current FOV from the [`Camera3d`] projection, the current SFX
830/// volume from [`SfxConfig`], the render distance from [`WorldConfig`], and the
831/// mouse sensitivity from [`PlayerConfig`] to initialise the slider labels.
832/// Runs via `OnEnter(Settings)`.
833fn spawn_settings_menu(
834    mut commands: Commands,
835    sfx_config: Res<SfxConfig>,
836    world_config: Option<Res<WorldConfig>>,
837    player_config: Option<Res<PlayerConfig>>,
838    camera_q: Query<&Projection, With<Camera3d>>,
839    config: Res<PauseMenuConfig>,
840    theme: Option<Res<PauseMenuTheme>>,
841) {
842    let fov_deg = camera_q
843        .single()
844        .ok()
845        .and_then(|p| {
846            if let Projection::Perspective(pp) = p {
847                Some(pp.fov.to_degrees())
848            } else {
849                None
850            }
851        })
852        .unwrap_or(90.0);
853    let volume_pct = sfx_config.volume * 100.0;
854    let render_dist_chunks = world_config
855        .as_ref()
856        .map(|wc| ((wc.load_distance / RENDER_DISTANCE_STEP).round() as i32).clamp(4, 32))
857        .unwrap_or(10);
858    // Round to nearest even
859    let render_dist_chunks = if render_dist_chunks % 2 == 0 {
860        render_dist_chunks
861    } else {
862        render_dist_chunks + 1
863    };
864    let sensitivity_pct = player_config
865        .as_ref()
866        .map(|pc| ((pc.sensitivity * 100.0).round() as i32).clamp(10, 100))
867        .unwrap_or(100);
868
869    let theme = current_theme(theme);
870    let (node, bg) = overlay_node(&theme);
871    commands
872        .spawn((SettingsMenuRoot, node, bg))
873        .with_children(|overlay| {
874            overlay.spawn(panel_node(&theme)).with_children(|p| {
875                p.spawn((
876                    Text::new("SETTINGS"),
877                    TextFont {
878                        font: config.font.clone(),
879                        font_size: 42.0,
880                        ..default()
881                    },
882                    TextColor(theme.header),
883                    Node {
884                        margin: UiRect::bottom(Val::Px(20.0)),
885                        ..default()
886                    },
887                ));
888
889                spawn_slider_row(
890                    p,
891                    "Field of View",
892                    format!("{fov_deg:.0}°"),
893                    FovLabel,
894                    SettingsButton::FovDec,
895                    SettingsButton::FovInc,
896                    config.font.clone(),
897                    config.symbol_font.clone(),
898                    &theme,
899                );
900
901                spawn_slider_row(
902                    p,
903                    "SFX Volume",
904                    format!("{volume_pct:.0}%"),
905                    VolumeLabel,
906                    SettingsButton::VolumeDec,
907                    SettingsButton::VolumeInc,
908                    config.font.clone(),
909                    config.symbol_font.clone(),
910                    &theme,
911                );
912
913                spawn_slider_row(
914                    p,
915                    "Render Distance",
916                    format!("{render_dist_chunks} chunks"),
917                    RenderDistLabel,
918                    SettingsButton::RenderDistDec,
919                    SettingsButton::RenderDistInc,
920                    config.font.clone(),
921                    config.symbol_font.clone(),
922                    &theme,
923                );
924
925                spawn_slider_row(
926                    p,
927                    "Sensitivity",
928                    format!("{sensitivity_pct:.0}%"),
929                    SensitivityLabel,
930                    SettingsButton::SensitivityDec,
931                    SettingsButton::SensitivityInc,
932                    config.font.clone(),
933                    config.symbol_font.clone(),
934                    &theme,
935                );
936
937                p.spawn(Node {
938                    margin: UiRect::top(Val::Px(20.0)),
939                    ..default()
940                })
941                .with_children(|row| {
942                    spawn_btn(
943                        row,
944                        "< Back",
945                        SettingsButton::Back,
946                        200.0,
947                        50.0,
948                        config.font.clone(),
949                        &theme,
950                    );
951                });
952            });
953        });
954}
955
956#[allow(clippy::too_many_arguments)]
957fn spawn_slider_row<L: Component, D: Component + ThemedButton, I: Component + ThemedButton>(
958    parent: &mut ChildSpawnerCommands,
959    label: &str,
960    value: String,
961    value_marker: L,
962    dec: D,
963    inc: I,
964    font: Handle<Font>,
965    symbol_font: Handle<Font>,
966    theme: &PauseMenuTheme,
967) {
968    parent
969        .spawn(Node {
970            flex_direction: FlexDirection::Row,
971            align_items: AlignItems::Center,
972            column_gap: Val::Px(12.0),
973            ..default()
974        })
975        .with_children(|row| {
976            row.spawn((
977                Text::new(label),
978                TextFont {
979                    font: font.clone(),
980                    font_size: 20.0,
981                    ..default()
982                },
983                TextColor(theme.label),
984                Node {
985                    width: Val::Px(200.0),
986                    ..default()
987                },
988            ));
989            spawn_btn(row, "\u{25C0}", dec, 44.0, 44.0, symbol_font.clone(), theme);
990            row.spawn((
991                value_marker,
992                Text::new(value),
993                TextFont {
994                    font: font.clone(),
995                    font_size: 22.0,
996                    ..default()
997                },
998                TextColor(theme.text),
999                Node {
1000                    width: Val::Px(80.0),
1001                    justify_content: JustifyContent::Center,
1002                    ..default()
1003                },
1004            ));
1005            spawn_btn(row, "\u{25B6}", inc, 44.0, 44.0, symbol_font, theme);
1006        });
1007}
1008
1009/// Despawns the settings overlay when leaving [`PauseMenuState::Settings`].
1010///
1011/// Runs via `OnExit(Settings)`. The only exit transition is `Settings → Paused`
1012/// via the Back button.
1013fn despawn_settings_menu(mut commands: Commands, q: Query<Entity, With<SettingsMenuRoot>>) {
1014    for e in &q {
1015        commands.entity(e).despawn();
1016    }
1017}
1018
1019/// Handles hover/press styling and click actions for settings menu buttons.
1020///
1021/// Runs every frame in [`PauseMenuState::Settings`]. Updates button background
1022/// colors from [`PauseMenuTheme`] and adjusts values on press:
1023/// - `FovInc` / `FovDec`: changes FOV by ±5° (clamped `50°`–`120°`) and updates
1024///   [`FovLabel`] text, the [`Camera3d`] perspective projection and
1025///   [`PlayerConfig::fov_degrees`].
1026/// - `VolumeInc` / `VolumeDec`: changes [`SfxConfig::volume`] by ±0.1 (clamped
1027///   `0.0`–`1.0`) and updates [`VolumeLabel`] text.
1028/// - `RenderDistInc` / `RenderDistDec`: changes [`WorldConfig::load_distance`] by
1029///   ±2 chunks (clamped `4`–`32`) and updates [`RenderDistLabel`] text and
1030///   [`ChunkManager`] distances.
1031/// - `SensitivityInc` / `SensitivityDec`: changes [`PlayerConfig::sensitivity`] by
1032///   ±1% (clamped `10`–`100`), applies it to every live [`Player`] so mouse
1033///   look changes immediately, and updates [`SensitivityLabel`] text.
1034/// - `Back`: emits [`SaveSettingsRequest`] and transitions to [`PauseMenuState::Paused`].
1035#[allow(clippy::too_many_arguments)]
1036fn handle_settings_buttons(
1037    mut q: Query<
1038        (&Interaction, &mut BackgroundColor, &SettingsButton),
1039        (Changed<Interaction>, With<Button>),
1040    >,
1041    mut sfx_config: ResMut<SfxConfig>,
1042    mut world_config: Option<ResMut<WorldConfig>>,
1043    mut chunk_manager: Option<ResMut<ChunkManager>>,
1044    mut player_config: Option<ResMut<PlayerConfig>>,
1045    mut next: ResMut<NextState<PauseMenuState>>,
1046    mut fov_label: Query<
1047        &mut Text,
1048        (
1049            With<FovLabel>,
1050            Without<VolumeLabel>,
1051            Without<RenderDistLabel>,
1052            Without<SensitivityLabel>,
1053        ),
1054    >,
1055    mut vol_label: Query<
1056        &mut Text,
1057        (
1058            With<VolumeLabel>,
1059            Without<FovLabel>,
1060            Without<RenderDistLabel>,
1061            Without<SensitivityLabel>,
1062        ),
1063    >,
1064    mut rdist_label: Query<
1065        &mut Text,
1066        (
1067            With<RenderDistLabel>,
1068            Without<FovLabel>,
1069            Without<VolumeLabel>,
1070            Without<SensitivityLabel>,
1071        ),
1072    >,
1073    mut sens_label: Query<
1074        &mut Text,
1075        (
1076            With<SensitivityLabel>,
1077            Without<FovLabel>,
1078            Without<VolumeLabel>,
1079            Without<RenderDistLabel>,
1080        ),
1081    >,
1082    mut camera_q: Query<&mut Projection, With<Camera3d>>,
1083    mut players: Query<&mut Player>,
1084    mut save_writer: MessageWriter<SaveSettingsRequest>,
1085    theme: Option<Res<PauseMenuTheme>>,
1086) {
1087    let theme = current_theme(theme);
1088    for (interaction, mut bg, action) in &mut q {
1089        *bg = BackgroundColor(action.colors(&theme).background(*interaction));
1090        if *interaction != Interaction::Pressed {
1091            continue;
1092        }
1093
1094        match action {
1095            SettingsButton::FovInc | SettingsButton::FovDec => {
1096                if let Ok(mut proj) = camera_q.single_mut() {
1097                    if let Projection::Perspective(ref mut pp) = *proj {
1098                        let new_fov = step_fov_degrees(
1099                            pp.fov.to_degrees(),
1100                            matches!(action, SettingsButton::FovInc),
1101                        );
1102                        pp.fov = new_fov.to_radians();
1103                        // Keep the configured value in step with the camera,
1104                        // so it is the one place to read the field of view.
1105                        if let Some(ref mut pc) = player_config {
1106                            pc.fov_degrees = new_fov;
1107                        }
1108                        if let Ok(mut t) = fov_label.single_mut() {
1109                            **t = format!("{new_fov:.0}°");
1110                        }
1111                    }
1112                }
1113            }
1114            SettingsButton::VolumeInc | SettingsButton::VolumeDec => {
1115                sfx_config.volume = step_volume(
1116                    sfx_config.volume,
1117                    matches!(action, SettingsButton::VolumeInc),
1118                );
1119                let pct = sfx_config.volume * 100.0;
1120                if let Ok(mut t) = vol_label.single_mut() {
1121                    **t = format!("{pct:.0}%");
1122                }
1123            }
1124            SettingsButton::RenderDistInc | SettingsButton::RenderDistDec => {
1125                if let Some(ref mut wc) = world_config {
1126                    let new_chunks = step_render_distance_chunks(
1127                        wc.load_distance,
1128                        matches!(action, SettingsButton::RenderDistInc),
1129                    );
1130                    wc.load_distance = new_chunks as f32 * RENDER_DISTANCE_STEP;
1131                    wc.unload_distance = wc.load_distance + RENDER_DISTANCE_UNLOAD_MARGIN;
1132                    if let Some(ref mut cm) = chunk_manager {
1133                        cm.load_distance = wc.load_distance;
1134                        cm.unload_distance = wc.unload_distance;
1135                    }
1136                    if let Ok(mut t) = rdist_label.single_mut() {
1137                        **t = format!("{new_chunks} chunks");
1138                    }
1139                }
1140            }
1141            SettingsButton::SensitivityInc | SettingsButton::SensitivityDec => {
1142                if let Some(ref mut pc) = player_config {
1143                    let new_pct = step_sensitivity_pct(
1144                        pc.sensitivity,
1145                        matches!(action, SettingsButton::SensitivityInc),
1146                    );
1147                    pc.sensitivity = new_pct as f32 / 100.0;
1148                    // `Player::sensitivity` is copied from the config at spawn
1149                    // and is what mouse look reads, so update live players too;
1150                    // otherwise the change only applied after a restart.
1151                    for mut player in &mut players {
1152                        player.sensitivity = pc.sensitivity;
1153                    }
1154                    if let Ok(mut t) = sens_label.single_mut() {
1155                        **t = format!("{new_pct:.0}%");
1156                    }
1157                }
1158            }
1159            SettingsButton::Back => {
1160                save_writer.write(SaveSettingsRequest);
1161                next.set(PauseMenuState::Paused);
1162            }
1163        }
1164    }
1165}
1166
1167// ─── Slider steps ─────────────────────────────────────────────────────────────
1168//
1169// Pure helpers behind the settings buttons, kept separate from the Bevy system
1170// so the rules (step size, limits, rounding) are unit-testable.
1171
1172/// Next field of view in degrees: ±5°, clamped to `50`–`120`.
1173fn step_fov_degrees(current_deg: f32, increase: bool) -> f32 {
1174    let delta = if increase { 5.0 } else { -5.0 };
1175    (current_deg + delta).clamp(50.0, 120.0)
1176}
1177
1178/// Next SFX volume: ±0.1, clamped to `0.0`–`1.0`.
1179fn step_volume(current: f32, increase: bool) -> f32 {
1180    let delta = if increase { 0.1 } else { -0.1 };
1181    (current + delta).clamp(0.0, 1.0)
1182}
1183
1184/// Next render distance in chunks: the current `load_distance` is rounded to
1185/// whole chunks, clamped to `4`–`32` and bumped to even, then moved ±2 chunks
1186/// and clamped again.
1187fn step_render_distance_chunks(load_distance: f32, increase: bool) -> i32 {
1188    let current = ((load_distance / RENDER_DISTANCE_STEP).round() as i32).clamp(4, 32);
1189    let current = if current % 2 == 0 {
1190        current
1191    } else {
1192        current + 1
1193    };
1194    let delta = if increase { 2 } else { -2 };
1195    (current + delta).clamp(4, 32)
1196}
1197
1198/// Next mouse sensitivity in percent: ±1%, clamped to `10`–`100`.
1199fn step_sensitivity_pct(sensitivity: f32, increase: bool) -> i32 {
1200    let current_pct = (sensitivity * 100.0).round() as i32;
1201    let delta = if increase { 1 } else { -1 };
1202    (current_pct + delta).clamp(10, 100)
1203}
1204
1205// ─── Tests ────────────────────────────────────────────────────────────────────
1206
1207#[cfg(test)]
1208mod tests {
1209    use super::*;
1210    use bevy::ecs::message::Messages;
1211    use bevy::ecs::system::RunSystemOnce;
1212
1213    use crate::player::player_cursor_system;
1214    use bevy::state::app::StatesPlugin;
1215    use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
1216
1217    /// Headless app with the pause transitions wired as [`PauseMenuPlugin`]
1218    /// does (minus UI and assets) plus the player's cursor system, and a
1219    /// focused primary window with a free cursor.
1220    fn pause_cursor_app() -> (App, Entity) {
1221        let mut app = App::new();
1222        app.add_plugins(StatesPlugin);
1223        app.init_state::<PauseMenuState>();
1224        app.add_message::<SfxRequest>();
1225        app.init_resource::<ButtonInput<KeyCode>>();
1226        app.init_resource::<ButtonInput<MouseButton>>();
1227        app.add_systems(
1228            Update,
1229            (
1230                toggle_pause.run_if(in_state(PauseMenuState::Playing)),
1231                escape_to_resume.run_if(in_state(PauseMenuState::Paused)),
1232                player_cursor_system.run_if(in_state(PauseMenuState::Playing)),
1233            ),
1234        );
1235        app.add_systems(OnEnter(PauseMenuState::Paused), release_cursor);
1236        let window = app
1237            .world_mut()
1238            .spawn((
1239                Window {
1240                    focused: true,
1241                    ..default()
1242                },
1243                PrimaryWindow,
1244            ))
1245            .id();
1246        (app, window)
1247    }
1248
1249    /// Presses `key` for one frame, then runs a second frame so the state
1250    /// transition it requested is applied.
1251    fn tap(app: &mut App, key: KeyCode) {
1252        app.world_mut()
1253            .resource_mut::<ButtonInput<KeyCode>>()
1254            .press(key);
1255        app.update();
1256        app.world_mut()
1257            .resource_mut::<ButtonInput<KeyCode>>()
1258            .reset_all();
1259        app.update();
1260    }
1261
1262    fn click(app: &mut App) {
1263        app.world_mut()
1264            .resource_mut::<ButtonInput<MouseButton>>()
1265            .press(MouseButton::Left);
1266        app.update();
1267        app.world_mut()
1268            .resource_mut::<ButtonInput<MouseButton>>()
1269            .reset_all();
1270    }
1271
1272    fn pause_state(app: &App) -> PauseMenuState {
1273        app.world()
1274            .resource::<State<PauseMenuState>>()
1275            .get()
1276            .clone()
1277    }
1278
1279    fn grab(app: &App, window: Entity) -> CursorGrabMode {
1280        app.world()
1281            .get::<CursorOptions>(window)
1282            .expect("window should still exist")
1283            .grab_mode
1284    }
1285
1286    #[test]
1287    fn cursor_follows_pause_focus_and_click_with_the_player_cursor_system() {
1288        let (mut app, window) = pause_cursor_app();
1289
1290        // Escape before the first click opens the menu; it must not close the window.
1291        tap(&mut app, KeyCode::Escape);
1292        assert_eq!(pause_state(&app), PauseMenuState::Paused);
1293        assert_eq!(grab(&app, window), CursorGrabMode::None);
1294
1295        // Escape again resumes with the cursor captured.
1296        tap(&mut app, KeyCode::Escape);
1297        assert_eq!(pause_state(&app), PauseMenuState::Playing);
1298        assert_eq!(grab(&app, window), CursorGrabMode::Locked);
1299
1300        // Losing focus releases the cursor without pausing.
1301        app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
1302        app.update();
1303        assert_eq!(grab(&app, window), CursorGrabMode::None);
1304        assert_eq!(pause_state(&app), PauseMenuState::Playing);
1305
1306        // Regaining focus alone does not recapture; a click does.
1307        app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
1308        app.update();
1309        assert_eq!(grab(&app, window), CursorGrabMode::None);
1310        click(&mut app);
1311        assert_eq!(grab(&app, window), CursorGrabMode::Locked);
1312
1313        // Pausing from a captured cursor releases it for the menu.
1314        tap(&mut app, KeyCode::Escape);
1315        assert_eq!(pause_state(&app), PauseMenuState::Paused);
1316        assert_eq!(grab(&app, window), CursorGrabMode::None);
1317    }
1318
1319    #[test]
1320    fn resuming_does_not_capture_an_unfocused_window() {
1321        let (mut app, window) = pause_cursor_app();
1322        tap(&mut app, KeyCode::Escape);
1323        assert_eq!(pause_state(&app), PauseMenuState::Paused);
1324        app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
1325
1326        app.world_mut()
1327            .resource_mut::<ButtonInput<KeyCode>>()
1328            .press(KeyCode::Escape);
1329        app.update();
1330        // Checked before the next frame, where the player's cursor system
1331        // would release an unfocused capture anyway.
1332        assert_eq!(grab(&app, window), CursorGrabMode::None);
1333        app.world_mut()
1334            .resource_mut::<ButtonInput<KeyCode>>()
1335            .reset_all();
1336        app.update();
1337
1338        assert_eq!(pause_state(&app), PauseMenuState::Playing);
1339        assert_eq!(grab(&app, window), CursorGrabMode::None);
1340    }
1341
1342    #[test]
1343    fn pause_cursor_changes_only_touch_the_primary_window() {
1344        let (mut app, window) = pause_cursor_app();
1345        let secondary = app
1346            .world_mut()
1347            .spawn((
1348                Window {
1349                    focused: false,
1350                    ..default()
1351                },
1352                CursorOptions {
1353                    grab_mode: CursorGrabMode::Confined,
1354                    ..default()
1355                },
1356            ))
1357            .id();
1358
1359        tap(&mut app, KeyCode::Escape);
1360        tap(&mut app, KeyCode::Escape);
1361
1362        assert_eq!(grab(&app, window), CursorGrabMode::Locked);
1363        assert_eq!(grab(&app, secondary), CursorGrabMode::Confined);
1364    }
1365
1366    #[test]
1367    fn fov_steps_by_five_degrees_within_limits() {
1368        assert_eq!(step_fov_degrees(70.0, true), 75.0);
1369        assert_eq!(step_fov_degrees(70.0, false), 65.0);
1370        assert_eq!(step_fov_degrees(118.0, true), 120.0);
1371        assert_eq!(step_fov_degrees(52.0, false), 50.0);
1372    }
1373
1374    #[test]
1375    fn volume_steps_by_a_tenth_within_limits() {
1376        assert!((step_volume(0.5, true) - 0.6).abs() < 1e-6);
1377        assert!((step_volume(0.5, false) - 0.4).abs() < 1e-6);
1378        assert_eq!(step_volume(0.95, true), 1.0);
1379        assert_eq!(step_volume(0.05, false), 0.0);
1380    }
1381
1382    #[test]
1383    fn render_distance_steps_by_two_chunks_within_limits() {
1384        // Default load distance is 150 units ≈ 9.4 chunks → 9 → bumped to 10.
1385        assert_eq!(step_render_distance_chunks(150.0, true), 12);
1386        assert_eq!(step_render_distance_chunks(150.0, false), 8);
1387        assert_eq!(step_render_distance_chunks(8.0 * 16.0, true), 10);
1388        assert_eq!(step_render_distance_chunks(32.0 * 16.0, true), 32);
1389        assert_eq!(step_render_distance_chunks(4.0 * 16.0, false), 4);
1390        // Values outside the slider range are clamped first.
1391        assert_eq!(step_render_distance_chunks(1000.0 * 16.0, false), 30);
1392    }
1393
1394    #[test]
1395    fn sensitivity_steps_by_one_percent_within_limits() {
1396        assert_eq!(step_sensitivity_pct(1.0, false), 99);
1397        assert_eq!(step_sensitivity_pct(1.0, true), 100);
1398        assert_eq!(step_sensitivity_pct(0.5, true), 51);
1399        assert_eq!(step_sensitivity_pct(0.1, false), 10);
1400    }
1401
1402    /// World with the resources `handle_settings_buttons` needs and one
1403    /// pressed button.
1404    fn settings_world(pressed: SettingsButton) -> World {
1405        let mut world = World::new();
1406        world.insert_resource(SfxConfig::default());
1407        world.init_resource::<NextState<PauseMenuState>>();
1408        world.init_resource::<Messages<SaveSettingsRequest>>();
1409        world.spawn((
1410            Button,
1411            Interaction::Pressed,
1412            BackgroundColor(Color::NONE),
1413            pressed,
1414        ));
1415        world
1416    }
1417
1418    fn press(world: &mut World) {
1419        world
1420            .run_system_once(handle_settings_buttons)
1421            .expect("handle_settings_buttons should run");
1422    }
1423
1424    #[test]
1425    fn sensitivity_button_updates_config_and_live_players() {
1426        let mut world = settings_world(SettingsButton::SensitivityDec);
1427        world.insert_resource(PlayerConfig::default());
1428        let player = world.spawn(Player::default()).id();
1429        assert_eq!(world.get::<Player>(player).unwrap().sensitivity, 1.0);
1430
1431        press(&mut world);
1432
1433        assert!((world.resource::<PlayerConfig>().sensitivity - 0.99).abs() < 1e-6);
1434        assert!(
1435            (world.get::<Player>(player).unwrap().sensitivity - 0.99).abs() < 1e-6,
1436            "the live player must pick up the new sensitivity without a restart"
1437        );
1438    }
1439
1440    #[test]
1441    fn fov_button_updates_the_camera_and_the_player_config() {
1442        let mut world = settings_world(SettingsButton::FovInc);
1443        world.insert_resource(PlayerConfig {
1444            fov_degrees: 70.0,
1445            ..default()
1446        });
1447        let camera = world
1448            .spawn((
1449                Camera3d::default(),
1450                Projection::Perspective(PerspectiveProjection {
1451                    fov: 70.0_f32.to_radians(),
1452                    ..default()
1453                }),
1454            ))
1455            .id();
1456
1457        press(&mut world);
1458
1459        let Projection::Perspective(perspective) = world.get::<Projection>(camera).unwrap() else {
1460            panic!("perspective camera");
1461        };
1462        assert!((perspective.fov.to_degrees() - 75.0).abs() < 1e-3);
1463        assert!((world.resource::<PlayerConfig>().fov_degrees - 75.0).abs() < 1e-3);
1464    }
1465
1466    #[test]
1467    fn volume_button_updates_sfx_config() {
1468        let mut world = settings_world(SettingsButton::VolumeDec);
1469        let before = world.resource::<SfxConfig>().volume;
1470
1471        press(&mut world);
1472
1473        let after = world.resource::<SfxConfig>().volume;
1474        assert!((after - (before - 0.1).clamp(0.0, 1.0)).abs() < 1e-6);
1475    }
1476
1477    #[test]
1478    fn back_button_requests_save_and_returns_to_pause() {
1479        let mut world = settings_world(SettingsButton::Back);
1480
1481        press(&mut world);
1482
1483        let saves = world.resource::<Messages<SaveSettingsRequest>>();
1484        assert_eq!(saves.iter_current_update_messages().count(), 1);
1485        assert!(matches!(
1486            *world.resource::<NextState<PauseMenuState>>(),
1487            NextState::Pending(PauseMenuState::Paused)
1488        ));
1489    }
1490
1491    // ─── Theme ───────────────────────────────────────────────────────────────
1492
1493    const PRIMARY: ButtonColors = ButtonColors {
1494        normal: Color::srgb(0.10, 0.20, 0.30),
1495        hovered: Color::srgb(0.11, 0.21, 0.31),
1496        pressed: Color::srgb(0.12, 0.22, 0.32),
1497        text: Color::srgb(0.13, 0.23, 0.33),
1498    };
1499    const SECONDARY: ButtonColors = ButtonColors {
1500        normal: Color::srgb(0.40, 0.50, 0.60),
1501        hovered: Color::srgb(0.41, 0.51, 0.61),
1502        pressed: Color::srgb(0.42, 0.52, 0.62),
1503        text: Color::srgb(0.43, 0.53, 0.63),
1504    };
1505
1506    /// A theme in which every value differs from the default and from every
1507    /// other value, so a color in the wrong place fails a test.
1508    fn custom_theme() -> PauseMenuTheme {
1509        PauseMenuTheme {
1510            overlay: Color::srgba(0.9, 0.1, 0.1, 0.5),
1511            panel: Color::srgb(0.9, 0.9, 0.8),
1512            header: Color::srgb(0.1, 0.9, 0.1),
1513            text: Color::srgb(0.1, 0.1, 0.9),
1514            label: Color::srgb(0.9, 0.1, 0.9),
1515            button: PRIMARY,
1516            secondary_button: SECONDARY,
1517            corner_radius: 9.0,
1518            panel_width: Val::Px(520.0),
1519            panel_padding: UiRect::all(Val::Px(32.0)),
1520        }
1521    }
1522
1523    /// World with what the two spawn systems need, and optionally a theme.
1524    fn menu_world(theme: Option<PauseMenuTheme>) -> World {
1525        let mut world = World::new();
1526        world.insert_resource(PauseMenuConfig::default());
1527        world.insert_resource(SfxConfig::default());
1528        if let Some(theme) = theme {
1529            world.insert_resource(theme);
1530        }
1531        world
1532    }
1533
1534    fn open_pause_menu(world: &mut World) {
1535        world
1536            .run_system_once(spawn_pause_menu)
1537            .expect("spawn_pause_menu should run");
1538    }
1539
1540    fn open_settings_menu(world: &mut World) {
1541        world
1542            .run_system_once(spawn_settings_menu)
1543            .expect("spawn_settings_menu should run");
1544    }
1545
1546    /// Color of the only text entity whose content is `content`.
1547    fn text_color(world: &mut World, content: &str) -> Color {
1548        let mut query = world.query::<(&Text, &TextColor)>();
1549        let found: Vec<Color> = query
1550            .iter(world)
1551            .filter(|(text, _)| text.0 == content)
1552            .map(|(_, color)| color.0)
1553            .collect();
1554        assert_eq!(found.len(), 1, "expected exactly one text {content:?}");
1555        found[0]
1556    }
1557
1558    /// Background color of the overlay root marked `R`, and the root entity.
1559    fn overlay<R: Component>(world: &mut World) -> (Entity, Color) {
1560        let mut query = world.query_filtered::<(Entity, &BackgroundColor), With<R>>();
1561        let (root, bg) = query
1562            .single(world)
1563            .expect("the menu should have exactly one overlay root");
1564        (root, bg.0)
1565    }
1566
1567    /// Background color, node and parent of the menu's single panel.
1568    fn panel(world: &mut World) -> (Color, Node, Entity) {
1569        let mut query =
1570            world.query_filtered::<(&BackgroundColor, &Node, &ChildOf), With<PauseMenuPanel>>();
1571        let (bg, node, child_of) = query
1572            .single(world)
1573            .expect("the menu should have exactly one panel");
1574        (bg.0, node.clone(), child_of.parent())
1575    }
1576
1577    /// Background color and corner radius of every pause-menu button that
1578    /// `select` accepts.
1579    fn pause_buttons(
1580        world: &mut World,
1581        select: fn(&PauseButton) -> bool,
1582    ) -> Vec<(Color, BorderRadius)> {
1583        let mut query = world.query::<(&PauseButton, &BackgroundColor, &Node)>();
1584        query
1585            .iter(world)
1586            .filter(|(action, _, _)| select(action))
1587            .map(|(_, bg, node)| (bg.0, node.border_radius))
1588            .collect()
1589    }
1590
1591    /// Same as `pause_buttons` for the settings submenu.
1592    fn settings_buttons(
1593        world: &mut World,
1594        select: fn(&SettingsButton) -> bool,
1595    ) -> Vec<(Color, BorderRadius)> {
1596        let mut query = world.query::<(&SettingsButton, &BackgroundColor, &Node)>();
1597        query
1598            .iter(world)
1599            .filter(|(action, _, _)| select(action))
1600            .map(|(_, bg, node)| (bg.0, node.border_radius))
1601            .collect()
1602    }
1603
1604    #[test]
1605    fn default_theme_equals_the_previous_constants() {
1606        let buttons = ButtonColors::default();
1607        assert_eq!(buttons.normal, Color::srgb(0.15, 0.15, 0.20));
1608        assert_eq!(buttons.hovered, Color::srgb(0.25, 0.25, 0.35));
1609        assert_eq!(buttons.pressed, Color::srgb(0.35, 0.35, 0.50));
1610        assert_eq!(buttons.text, Color::WHITE);
1611
1612        let theme = PauseMenuTheme::default();
1613        assert_eq!(theme.overlay, Color::srgba(0.0, 0.0, 0.0, 0.78));
1614        assert_eq!(theme.panel, Color::NONE);
1615        assert_eq!(theme.header, Color::WHITE);
1616        assert_eq!(theme.text, Color::WHITE);
1617        assert_eq!(theme.label, Color::srgb(0.8, 0.8, 0.8));
1618        assert_eq!(theme.button, buttons);
1619        assert_eq!(theme.secondary_button, buttons);
1620        assert_eq!(theme.corner_radius, 0.0);
1621        assert_eq!(theme.panel_width, Val::Auto);
1622        assert_eq!(theme.panel_padding, UiRect::ZERO);
1623    }
1624
1625    #[test]
1626    fn button_colors_pick_the_background_for_each_interaction() {
1627        assert_eq!(PRIMARY.background(Interaction::None), PRIMARY.normal);
1628        assert_eq!(PRIMARY.background(Interaction::Hovered), PRIMARY.hovered);
1629        assert_eq!(PRIMARY.background(Interaction::Pressed), PRIMARY.pressed);
1630    }
1631
1632    #[test]
1633    fn pause_menu_without_a_theme_resource_keeps_the_previous_look() {
1634        let mut world = menu_world(None);
1635
1636        open_pause_menu(&mut world);
1637
1638        let (root, overlay_bg) = overlay::<PauseMenuRoot>(&mut world);
1639        assert_eq!(overlay_bg, Color::srgba(0.0, 0.0, 0.0, 0.78));
1640
1641        // The panel exists but cannot be seen and does not change the layout.
1642        let (panel_bg, panel_node, panel_parent) = panel(&mut world);
1643        assert_eq!(panel_parent, root);
1644        assert_eq!(panel_bg, Color::NONE);
1645        assert_eq!(panel_node.width, Val::Auto);
1646        assert_eq!(panel_node.padding, UiRect::ZERO);
1647        assert_eq!(panel_node.border_radius, BorderRadius::ZERO);
1648        assert_eq!(panel_node.row_gap, Val::Px(14.0));
1649        assert_eq!(panel_node.flex_direction, FlexDirection::Column);
1650        assert_eq!(panel_node.align_items, AlignItems::Center);
1651
1652        assert_eq!(text_color(&mut world, "PAUSED"), Color::WHITE);
1653        let buttons = pause_buttons(&mut world, |_| true);
1654        assert_eq!(buttons.len(), 3);
1655        for (bg, radius) in buttons {
1656            assert_eq!(bg, Color::srgb(0.15, 0.15, 0.20));
1657            assert_eq!(radius, BorderRadius::ZERO);
1658        }
1659        for label in ["Resume", "Settings", "Quit"] {
1660            assert_eq!(text_color(&mut world, label), Color::WHITE);
1661        }
1662    }
1663
1664    #[test]
1665    fn custom_theme_styles_the_pause_menu() {
1666        let theme = custom_theme();
1667        let mut world = menu_world(Some(theme.clone()));
1668
1669        open_pause_menu(&mut world);
1670
1671        let (root, overlay_bg) = overlay::<PauseMenuRoot>(&mut world);
1672        assert_eq!(overlay_bg, theme.overlay);
1673
1674        let (panel_bg, panel_node, panel_parent) = panel(&mut world);
1675        assert_eq!(panel_parent, root);
1676        assert_eq!(panel_bg, theme.panel);
1677        assert_eq!(panel_node.width, Val::Px(520.0));
1678        assert_eq!(panel_node.padding, UiRect::all(Val::Px(32.0)));
1679        assert_eq!(panel_node.border_radius, BorderRadius::all(Val::Px(9.0)));
1680
1681        assert_eq!(text_color(&mut world, "PAUSED"), theme.header);
1682
1683        let radius = BorderRadius::all(Val::Px(9.0));
1684        assert_eq!(
1685            pause_buttons(&mut world, |b| matches!(b, PauseButton::Resume)),
1686            vec![(PRIMARY.normal, radius)]
1687        );
1688        assert_eq!(
1689            pause_buttons(&mut world, |b| !matches!(b, PauseButton::Resume)),
1690            vec![(SECONDARY.normal, radius); 2]
1691        );
1692        assert_eq!(text_color(&mut world, "Resume"), PRIMARY.text);
1693        assert_eq!(text_color(&mut world, "Settings"), SECONDARY.text);
1694        assert_eq!(text_color(&mut world, "Quit"), SECONDARY.text);
1695    }
1696
1697    #[test]
1698    fn pause_menu_buttons_are_children_of_the_panel() {
1699        let mut world = menu_world(None);
1700
1701        open_pause_menu(&mut world);
1702
1703        let mut panels = world.query_filtered::<Entity, With<PauseMenuPanel>>();
1704        let panel_entity = panels.single(&world).expect("one panel");
1705        let mut buttons = world.query_filtered::<&ChildOf, With<PauseButton>>();
1706        let parents: Vec<Entity> = buttons.iter(&world).map(|c| c.parent()).collect();
1707        assert_eq!(parents, vec![panel_entity; 3]);
1708    }
1709
1710    #[test]
1711    fn settings_menu_without_a_theme_resource_keeps_the_previous_look() {
1712        let mut world = menu_world(None);
1713
1714        open_settings_menu(&mut world);
1715
1716        let (root, overlay_bg) = overlay::<SettingsMenuRoot>(&mut world);
1717        assert_eq!(overlay_bg, Color::srgba(0.0, 0.0, 0.0, 0.78));
1718        let (panel_bg, panel_node, panel_parent) = panel(&mut world);
1719        assert_eq!(panel_parent, root);
1720        assert_eq!(panel_bg, Color::NONE);
1721        assert_eq!(panel_node.width, Val::Auto);
1722        assert_eq!(panel_node.padding, UiRect::ZERO);
1723
1724        assert_eq!(text_color(&mut world, "SETTINGS"), Color::WHITE);
1725        assert_eq!(
1726            text_color(&mut world, "Field of View"),
1727            Color::srgb(0.8, 0.8, 0.8)
1728        );
1729        let mut values = world.query_filtered::<&TextColor, With<FovLabel>>();
1730        assert_eq!(
1731            values.single(&world).expect("one FOV value").0,
1732            Color::WHITE
1733        );
1734        let buttons = settings_buttons(&mut world, |_| true);
1735        assert_eq!(buttons.len(), 9);
1736        for (bg, radius) in buttons {
1737            assert_eq!(bg, Color::srgb(0.15, 0.15, 0.20));
1738            assert_eq!(radius, BorderRadius::ZERO);
1739        }
1740        assert_eq!(text_color(&mut world, "< Back"), Color::WHITE);
1741    }
1742
1743    #[test]
1744    fn custom_theme_styles_the_settings_menu() {
1745        let theme = custom_theme();
1746        let mut world = menu_world(Some(theme.clone()));
1747
1748        open_settings_menu(&mut world);
1749
1750        let (root, overlay_bg) = overlay::<SettingsMenuRoot>(&mut world);
1751        assert_eq!(overlay_bg, theme.overlay);
1752
1753        let (panel_bg, panel_node, panel_parent) = panel(&mut world);
1754        assert_eq!(panel_parent, root);
1755        assert_eq!(panel_bg, theme.panel);
1756        assert_eq!(panel_node.width, Val::Px(520.0));
1757        assert_eq!(panel_node.padding, UiRect::all(Val::Px(32.0)));
1758        assert_eq!(panel_node.border_radius, BorderRadius::all(Val::Px(9.0)));
1759
1760        assert_eq!(text_color(&mut world, "SETTINGS"), theme.header);
1761        for label in [
1762            "Field of View",
1763            "SFX Volume",
1764            "Render Distance",
1765            "Sensitivity",
1766        ] {
1767            assert_eq!(text_color(&mut world, label), theme.label);
1768        }
1769        let mut values = world.query_filtered::<&TextColor, With<FovLabel>>();
1770        assert_eq!(values.single(&world).expect("one FOV value").0, theme.text);
1771
1772        let radius = BorderRadius::all(Val::Px(9.0));
1773        assert_eq!(
1774            settings_buttons(&mut world, |b| matches!(b, SettingsButton::Back)),
1775            vec![(PRIMARY.normal, radius)]
1776        );
1777        assert_eq!(
1778            settings_buttons(&mut world, |b| !matches!(b, SettingsButton::Back)),
1779            vec![(SECONDARY.normal, radius); 8]
1780        );
1781        assert_eq!(text_color(&mut world, "< Back"), PRIMARY.text);
1782    }
1783
1784    /// World with what both button handlers need, and optionally a theme.
1785    fn handler_world(theme: Option<PauseMenuTheme>) -> World {
1786        let mut world = World::new();
1787        world.insert_resource(SfxConfig::default());
1788        world.init_resource::<NextState<PauseMenuState>>();
1789        world.init_resource::<Messages<SaveSettingsRequest>>();
1790        world.init_resource::<Messages<SfxRequest>>();
1791        world.init_resource::<Messages<AppExit>>();
1792        if let Some(theme) = theme {
1793            world.insert_resource(theme);
1794        }
1795        world
1796    }
1797
1798    /// Spawns a button in the given interaction state with a background no
1799    /// theme uses, so the handler must be what sets the asserted color.
1800    fn spawn_button<A: Component>(world: &mut World, action: A, state: Interaction) -> Entity {
1801        world
1802            .spawn((Button, state, BackgroundColor(Color::NONE), action))
1803            .id()
1804    }
1805
1806    fn background(world: &World, entity: Entity) -> Color {
1807        world
1808            .get::<BackgroundColor>(entity)
1809            .expect("button should exist")
1810            .0
1811    }
1812
1813    #[test]
1814    fn pause_buttons_take_theme_colors_per_interaction_state() {
1815        let mut world = handler_world(Some(custom_theme()));
1816        let primary_idle = spawn_button(&mut world, PauseButton::Resume, Interaction::None);
1817        let primary_hovered = spawn_button(&mut world, PauseButton::Resume, Interaction::Hovered);
1818        let primary_pressed = spawn_button(&mut world, PauseButton::Resume, Interaction::Pressed);
1819        let secondary_idle = spawn_button(&mut world, PauseButton::Settings, Interaction::None);
1820        let secondary_hovered = spawn_button(&mut world, PauseButton::Quit, Interaction::Hovered);
1821        let secondary_pressed =
1822            spawn_button(&mut world, PauseButton::Settings, Interaction::Pressed);
1823
1824        world
1825            .run_system_once(handle_pause_buttons)
1826            .expect("handle_pause_buttons should run");
1827
1828        assert_eq!(background(&world, primary_idle), PRIMARY.normal);
1829        assert_eq!(background(&world, primary_hovered), PRIMARY.hovered);
1830        assert_eq!(background(&world, primary_pressed), PRIMARY.pressed);
1831        assert_eq!(background(&world, secondary_idle), SECONDARY.normal);
1832        assert_eq!(background(&world, secondary_hovered), SECONDARY.hovered);
1833        assert_eq!(background(&world, secondary_pressed), SECONDARY.pressed);
1834    }
1835
1836    #[test]
1837    fn settings_buttons_take_theme_colors_per_interaction_state() {
1838        let mut world = handler_world(Some(custom_theme()));
1839        let primary_idle = spawn_button(&mut world, SettingsButton::Back, Interaction::None);
1840        let primary_hovered = spawn_button(&mut world, SettingsButton::Back, Interaction::Hovered);
1841        let primary_pressed = spawn_button(&mut world, SettingsButton::Back, Interaction::Pressed);
1842        let secondary_idle = spawn_button(&mut world, SettingsButton::FovInc, Interaction::None);
1843        let secondary_hovered =
1844            spawn_button(&mut world, SettingsButton::VolumeDec, Interaction::Hovered);
1845        let secondary_pressed =
1846            spawn_button(&mut world, SettingsButton::FovDec, Interaction::Pressed);
1847
1848        press(&mut world);
1849
1850        assert_eq!(background(&world, primary_idle), PRIMARY.normal);
1851        assert_eq!(background(&world, primary_hovered), PRIMARY.hovered);
1852        assert_eq!(background(&world, primary_pressed), PRIMARY.pressed);
1853        assert_eq!(background(&world, secondary_idle), SECONDARY.normal);
1854        assert_eq!(background(&world, secondary_hovered), SECONDARY.hovered);
1855        assert_eq!(background(&world, secondary_pressed), SECONDARY.pressed);
1856    }
1857
1858    #[test]
1859    fn buttons_without_a_theme_resource_use_the_previous_colors() {
1860        let mut world = handler_world(None);
1861        let pause_idle = spawn_button(&mut world, PauseButton::Settings, Interaction::None);
1862        let pause_hovered = spawn_button(&mut world, PauseButton::Resume, Interaction::Hovered);
1863        let pause_pressed = spawn_button(&mut world, PauseButton::Settings, Interaction::Pressed);
1864        let settings_idle = spawn_button(&mut world, SettingsButton::Back, Interaction::None);
1865        let settings_hovered =
1866            spawn_button(&mut world, SettingsButton::FovInc, Interaction::Hovered);
1867        let settings_pressed =
1868            spawn_button(&mut world, SettingsButton::FovDec, Interaction::Pressed);
1869
1870        world
1871            .run_system_once(handle_pause_buttons)
1872            .expect("handle_pause_buttons should run");
1873        press(&mut world);
1874
1875        for idle in [pause_idle, settings_idle] {
1876            assert_eq!(background(&world, idle), Color::srgb(0.15, 0.15, 0.20));
1877        }
1878        for hovered in [pause_hovered, settings_hovered] {
1879            assert_eq!(background(&world, hovered), Color::srgb(0.25, 0.25, 0.35));
1880        }
1881        for pressed in [pause_pressed, settings_pressed] {
1882            assert_eq!(background(&world, pressed), Color::srgb(0.35, 0.35, 0.50));
1883        }
1884    }
1885}