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