use bevy::asset::embedded_asset;
use bevy::prelude::*;
use crate::audio::{SfxConfig, SfxEvent, SfxRequest};
use crate::player::{Player, PlayerConfig};
use crate::world::{ChunkManager, WorldConfig};
pub const EMBEDDED_NOTO_SANS_PATH: &str = "embedded://voxel_framework/ui/NotoSans-Regular.ttf";
pub const EMBEDDED_NOTO_SYMBOLS_PATH: &str =
"embedded://voxel_framework/ui/NotoSansSymbols2-Regular.ttf";
#[derive(States, Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum PauseMenuState {
#[default]
Playing,
Paused,
Settings,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ButtonColors {
pub normal: Color,
pub hovered: Color,
pub pressed: Color,
pub text: Color,
}
impl ButtonColors {
pub fn background(&self, interaction: Interaction) -> Color {
match interaction {
Interaction::None => self.normal,
Interaction::Hovered => self.hovered,
Interaction::Pressed => self.pressed,
}
}
}
impl Default for ButtonColors {
fn default() -> Self {
Self {
normal: Color::srgb(0.15, 0.15, 0.20),
hovered: Color::srgb(0.25, 0.25, 0.35),
pressed: Color::srgb(0.35, 0.35, 0.50),
text: Color::WHITE,
}
}
}
#[derive(Resource, Debug, Clone, PartialEq)]
pub struct PauseMenuTheme {
pub overlay: Color,
pub panel: Color,
pub header: Color,
pub text: Color,
pub label: Color,
pub button: ButtonColors,
pub secondary_button: ButtonColors,
pub corner_radius: f32,
pub panel_width: Val,
pub panel_padding: UiRect,
}
impl Default for PauseMenuTheme {
fn default() -> Self {
Self {
overlay: Color::srgba(0.0, 0.0, 0.0, 0.78),
panel: Color::NONE,
header: Color::WHITE,
text: Color::WHITE,
label: Color::srgb(0.8, 0.8, 0.8),
button: ButtonColors::default(),
secondary_button: ButtonColors::default(),
corner_radius: 0.0,
panel_width: Val::Auto,
panel_padding: UiRect::ZERO,
}
}
}
fn current_theme(theme: Option<Res<PauseMenuTheme>>) -> PauseMenuTheme {
theme.as_deref().cloned().unwrap_or_default()
}
trait ThemedButton {
fn colors(&self, theme: &PauseMenuTheme) -> ButtonColors;
}
#[derive(Component)]
struct PauseMenuRoot;
#[derive(Component)]
struct SettingsMenuRoot;
#[derive(Component)]
struct PauseMenuPanel;
#[derive(Component)]
struct FovLabel;
#[derive(Component)]
struct VolumeLabel;
#[derive(Component)]
struct RenderDistLabel;
#[derive(Component)]
struct SensitivityLabel;
#[derive(Component)]
enum PauseButton {
Resume,
Settings,
Quit,
}
#[derive(Component)]
enum SettingsButton {
FovInc,
FovDec,
VolumeInc,
VolumeDec,
RenderDistInc,
RenderDistDec,
SensitivityInc,
SensitivityDec,
Back,
}
impl ThemedButton for PauseButton {
fn colors(&self, theme: &PauseMenuTheme) -> ButtonColors {
match self {
PauseButton::Resume => theme.button,
PauseButton::Settings | PauseButton::Quit => theme.secondary_button,
}
}
}
impl ThemedButton for SettingsButton {
fn colors(&self, theme: &PauseMenuTheme) -> ButtonColors {
match self {
SettingsButton::Back => theme.button,
_ => theme.secondary_button,
}
}
}
#[derive(Message, Debug, Clone)]
pub struct SaveSettingsRequest;
#[derive(Resource, Clone)]
pub struct PauseMenuConfig {
pub font: Handle<Font>,
pub symbol_font: Handle<Font>,
}
impl Default for PauseMenuConfig {
fn default() -> Self {
Self {
font: Handle::default(),
symbol_font: Handle::default(),
}
}
}
pub struct PauseMenuPlugin;
impl Plugin for PauseMenuPlugin {
fn build(&self, app: &mut App) {
embedded_asset!(app, "NotoSans-Regular.ttf");
embedded_asset!(app, "NotoSansSymbols2-Regular.ttf");
app.init_resource::<PauseMenuConfig>();
app.init_resource::<PauseMenuTheme>();
app.init_state::<PauseMenuState>();
app.add_message::<SaveSettingsRequest>();
app.add_systems(Startup, load_default_font);
app.add_systems(
Update,
toggle_pause.run_if(in_state(PauseMenuState::Playing)),
);
app.add_systems(
OnEnter(PauseMenuState::Paused),
(spawn_pause_menu, release_cursor),
);
app.add_systems(OnExit(PauseMenuState::Paused), despawn_pause_menu);
app.add_systems(
Update,
(handle_pause_buttons, escape_to_resume).run_if(in_state(PauseMenuState::Paused)),
);
app.add_systems(OnEnter(PauseMenuState::Settings), spawn_settings_menu);
app.add_systems(OnExit(PauseMenuState::Settings), despawn_settings_menu);
app.add_systems(
Update,
handle_settings_buttons.run_if(in_state(PauseMenuState::Settings)),
);
}
}
fn load_default_font(mut cfg: ResMut<PauseMenuConfig>, asset_server: Res<AssetServer>) {
if cfg.font == Handle::default() {
cfg.font = asset_server.load(EMBEDDED_NOTO_SANS_PATH);
}
if cfg.symbol_font == Handle::default() {
cfg.symbol_font = asset_server.load(EMBEDDED_NOTO_SYMBOLS_PATH);
}
}
fn release_cursor(mut windows: PrimaryCursor) {
for (_, mut cursor) in &mut windows {
cursor.grab_mode = bevy::window::CursorGrabMode::None;
cursor.visible = true;
}
}
type PrimaryCursor<'w, 's> = Query<
'w,
's,
(&'static Window, &'static mut bevy::window::CursorOptions),
With<bevy::window::PrimaryWindow>,
>;
fn lock_cursor(windows: &mut PrimaryCursor) {
for (window, mut cursor) in windows.iter_mut() {
if !window.focused {
continue;
}
cursor.grab_mode = bevy::window::CursorGrabMode::Locked;
cursor.visible = false;
}
}
fn toggle_pause(
keys: Res<ButtonInput<KeyCode>>,
mut next: ResMut<NextState<PauseMenuState>>,
mut sfx: MessageWriter<SfxRequest>,
) {
if keys.just_pressed(KeyCode::Escape) {
next.set(PauseMenuState::Paused);
sfx.write(SfxRequest {
event: SfxEvent::PauseOpen,
position: None,
});
}
}
fn escape_to_resume(
keys: Res<ButtonInput<KeyCode>>,
mut next: ResMut<NextState<PauseMenuState>>,
mut windows: PrimaryCursor,
mut sfx: MessageWriter<SfxRequest>,
) {
if keys.just_pressed(KeyCode::Escape) {
next.set(PauseMenuState::Playing);
lock_cursor(&mut windows);
sfx.write(SfxRequest {
event: SfxEvent::PauseClose,
position: None,
});
}
}
fn spawn_btn<C: Component + ThemedButton>(
parent: &mut ChildSpawnerCommands,
label: &str,
action: C,
width: f32,
height: f32,
font: Handle<Font>,
theme: &PauseMenuTheme,
) {
let colors = action.colors(theme);
parent
.spawn((
action,
Button,
Node {
width: Val::Px(width),
height: Val::Px(height),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
border_radius: BorderRadius::all(Val::Px(theme.corner_radius)),
..default()
},
BackgroundColor(colors.normal),
))
.with_children(|b| {
b.spawn((
Text::new(label),
TextFont {
font,
font_size: 20.0,
..default()
},
TextColor(colors.text),
));
});
}
fn overlay_node(theme: &PauseMenuTheme) -> (Node, BackgroundColor) {
(
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
row_gap: Val::Px(14.0),
..default()
},
BackgroundColor(theme.overlay),
)
}
fn panel_node(theme: &PauseMenuTheme) -> (PauseMenuPanel, Node, BackgroundColor) {
(
PauseMenuPanel,
Node {
width: theme.panel_width,
padding: theme.panel_padding,
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
row_gap: Val::Px(14.0),
border_radius: BorderRadius::all(Val::Px(theme.corner_radius)),
..default()
},
BackgroundColor(theme.panel),
)
}
fn spawn_pause_menu(
mut commands: Commands,
config: Res<PauseMenuConfig>,
theme: Option<Res<PauseMenuTheme>>,
) {
let theme = current_theme(theme);
let (node, bg) = overlay_node(&theme);
commands
.spawn((PauseMenuRoot, node, bg))
.with_children(|overlay| {
overlay.spawn(panel_node(&theme)).with_children(|p| {
p.spawn((
Text::new("PAUSED"),
TextFont {
font: config.font.clone(),
font_size: 52.0,
..default()
},
TextColor(theme.header),
Node {
margin: UiRect::bottom(Val::Px(28.0)),
..default()
},
));
spawn_btn(
p,
"Resume",
PauseButton::Resume,
280.0,
52.0,
config.font.clone(),
&theme,
);
spawn_btn(
p,
"Settings",
PauseButton::Settings,
280.0,
52.0,
config.font.clone(),
&theme,
);
spawn_btn(
p,
"Quit",
PauseButton::Quit,
280.0,
52.0,
config.font.clone(),
&theme,
);
});
});
}
fn despawn_pause_menu(mut commands: Commands, q: Query<Entity, With<PauseMenuRoot>>) {
for e in &q {
commands.entity(e).despawn();
}
}
fn handle_pause_buttons(
mut q: Query<
(&Interaction, &mut BackgroundColor, &PauseButton),
(Changed<Interaction>, With<Button>),
>,
mut next: ResMut<NextState<PauseMenuState>>,
mut windows: PrimaryCursor,
mut app_exit: MessageWriter<AppExit>,
mut sfx: MessageWriter<SfxRequest>,
theme: Option<Res<PauseMenuTheme>>,
) {
let theme = current_theme(theme);
for (interaction, mut bg, action) in &mut q {
*bg = BackgroundColor(action.colors(&theme).background(*interaction));
if *interaction != Interaction::Pressed {
continue;
}
match action {
PauseButton::Resume => {
next.set(PauseMenuState::Playing);
lock_cursor(&mut windows);
sfx.write(SfxRequest {
event: SfxEvent::PauseClose,
position: None,
});
}
PauseButton::Settings => next.set(PauseMenuState::Settings),
PauseButton::Quit => {
app_exit.write(AppExit::Success);
}
}
}
}
fn spawn_settings_menu(
mut commands: Commands,
sfx_config: Res<SfxConfig>,
world_config: Option<Res<WorldConfig>>,
player_config: Option<Res<PlayerConfig>>,
camera_q: Query<&Projection, With<Camera3d>>,
config: Res<PauseMenuConfig>,
theme: Option<Res<PauseMenuTheme>>,
) {
let fov_deg = camera_q
.single()
.ok()
.and_then(|p| {
if let Projection::Perspective(pp) = p {
Some(pp.fov.to_degrees())
} else {
None
}
})
.unwrap_or(90.0);
let volume_pct = sfx_config.volume * 100.0;
let render_dist_chunks = world_config
.as_ref()
.map(|wc| ((wc.load_distance / 16.0).round() as i32).clamp(4, 32) as i32)
.unwrap_or(10);
let render_dist_chunks = if render_dist_chunks % 2 == 0 {
render_dist_chunks
} else {
render_dist_chunks + 1
};
let sensitivity_pct = player_config
.as_ref()
.map(|pc| ((pc.sensitivity * 100.0).round() as i32).clamp(10, 100))
.unwrap_or(100);
let theme = current_theme(theme);
let (node, bg) = overlay_node(&theme);
commands
.spawn((SettingsMenuRoot, node, bg))
.with_children(|overlay| {
overlay.spawn(panel_node(&theme)).with_children(|p| {
p.spawn((
Text::new("SETTINGS"),
TextFont {
font: config.font.clone(),
font_size: 42.0,
..default()
},
TextColor(theme.header),
Node {
margin: UiRect::bottom(Val::Px(20.0)),
..default()
},
));
spawn_slider_row(
p,
"Field of View",
format!("{fov_deg:.0}°"),
FovLabel,
SettingsButton::FovDec,
SettingsButton::FovInc,
config.font.clone(),
config.symbol_font.clone(),
&theme,
);
spawn_slider_row(
p,
"SFX Volume",
format!("{volume_pct:.0}%"),
VolumeLabel,
SettingsButton::VolumeDec,
SettingsButton::VolumeInc,
config.font.clone(),
config.symbol_font.clone(),
&theme,
);
spawn_slider_row(
p,
"Render Distance",
format!("{render_dist_chunks} chunks"),
RenderDistLabel,
SettingsButton::RenderDistDec,
SettingsButton::RenderDistInc,
config.font.clone(),
config.symbol_font.clone(),
&theme,
);
spawn_slider_row(
p,
"Sensitivity",
format!("{sensitivity_pct:.0}%"),
SensitivityLabel,
SettingsButton::SensitivityDec,
SettingsButton::SensitivityInc,
config.font.clone(),
config.symbol_font.clone(),
&theme,
);
p.spawn(Node {
margin: UiRect::top(Val::Px(20.0)),
..default()
})
.with_children(|row| {
spawn_btn(
row,
"< Back",
SettingsButton::Back,
200.0,
50.0,
config.font.clone(),
&theme,
);
});
});
});
}
#[allow(clippy::too_many_arguments)]
fn spawn_slider_row<L: Component, D: Component + ThemedButton, I: Component + ThemedButton>(
parent: &mut ChildSpawnerCommands,
label: &str,
value: String,
value_marker: L,
dec: D,
inc: I,
font: Handle<Font>,
symbol_font: Handle<Font>,
theme: &PauseMenuTheme,
) {
parent
.spawn(Node {
flex_direction: FlexDirection::Row,
align_items: AlignItems::Center,
column_gap: Val::Px(12.0),
..default()
})
.with_children(|row| {
row.spawn((
Text::new(label),
TextFont {
font: font.clone(),
font_size: 20.0,
..default()
},
TextColor(theme.label),
Node {
width: Val::Px(200.0),
..default()
},
));
spawn_btn(row, "\u{25C0}", dec, 44.0, 44.0, symbol_font.clone(), theme);
row.spawn((
value_marker,
Text::new(value),
TextFont {
font: font.clone(),
font_size: 22.0,
..default()
},
TextColor(theme.text),
Node {
width: Val::Px(80.0),
justify_content: JustifyContent::Center,
..default()
},
));
spawn_btn(row, "\u{25B6}", inc, 44.0, 44.0, symbol_font, theme);
});
}
fn despawn_settings_menu(mut commands: Commands, q: Query<Entity, With<SettingsMenuRoot>>) {
for e in &q {
commands.entity(e).despawn();
}
}
#[allow(clippy::too_many_arguments)]
fn handle_settings_buttons(
mut q: Query<
(&Interaction, &mut BackgroundColor, &SettingsButton),
(Changed<Interaction>, With<Button>),
>,
mut sfx_config: ResMut<SfxConfig>,
mut world_config: Option<ResMut<WorldConfig>>,
mut chunk_manager: Option<ResMut<ChunkManager>>,
mut player_config: Option<ResMut<PlayerConfig>>,
mut next: ResMut<NextState<PauseMenuState>>,
mut fov_label: Query<
&mut Text,
(
With<FovLabel>,
Without<VolumeLabel>,
Without<RenderDistLabel>,
Without<SensitivityLabel>,
),
>,
mut vol_label: Query<
&mut Text,
(
With<VolumeLabel>,
Without<FovLabel>,
Without<RenderDistLabel>,
Without<SensitivityLabel>,
),
>,
mut rdist_label: Query<
&mut Text,
(
With<RenderDistLabel>,
Without<FovLabel>,
Without<VolumeLabel>,
Without<SensitivityLabel>,
),
>,
mut sens_label: Query<
&mut Text,
(
With<SensitivityLabel>,
Without<FovLabel>,
Without<VolumeLabel>,
Without<RenderDistLabel>,
),
>,
mut camera_q: Query<&mut Projection, With<Camera3d>>,
mut players: Query<&mut Player>,
mut save_writer: MessageWriter<SaveSettingsRequest>,
theme: Option<Res<PauseMenuTheme>>,
) {
let theme = current_theme(theme);
for (interaction, mut bg, action) in &mut q {
*bg = BackgroundColor(action.colors(&theme).background(*interaction));
if *interaction != Interaction::Pressed {
continue;
}
match action {
SettingsButton::FovInc | SettingsButton::FovDec => {
if let Ok(mut proj) = camera_q.single_mut() {
if let Projection::Perspective(ref mut pp) = *proj {
let new_fov = step_fov_degrees(
pp.fov.to_degrees(),
matches!(action, SettingsButton::FovInc),
);
pp.fov = new_fov.to_radians();
if let Ok(mut t) = fov_label.single_mut() {
**t = format!("{new_fov:.0}°");
}
}
}
}
SettingsButton::VolumeInc | SettingsButton::VolumeDec => {
sfx_config.volume = step_volume(
sfx_config.volume,
matches!(action, SettingsButton::VolumeInc),
);
let pct = sfx_config.volume * 100.0;
if let Ok(mut t) = vol_label.single_mut() {
**t = format!("{pct:.0}%");
}
}
SettingsButton::RenderDistInc | SettingsButton::RenderDistDec => {
if let Some(ref mut wc) = world_config {
let new_chunks = step_render_distance_chunks(
wc.load_distance,
matches!(action, SettingsButton::RenderDistInc),
);
wc.load_distance = new_chunks as f32 * 16.0;
wc.unload_distance = wc.load_distance + 32.0;
if let Some(ref mut cm) = chunk_manager {
cm.load_distance = wc.load_distance;
cm.unload_distance = wc.unload_distance;
}
if let Ok(mut t) = rdist_label.single_mut() {
**t = format!("{new_chunks} chunks");
}
}
}
SettingsButton::SensitivityInc | SettingsButton::SensitivityDec => {
if let Some(ref mut pc) = player_config {
let new_pct = step_sensitivity_pct(
pc.sensitivity,
matches!(action, SettingsButton::SensitivityInc),
);
pc.sensitivity = new_pct as f32 / 100.0;
for mut player in &mut players {
player.sensitivity = pc.sensitivity;
}
if let Ok(mut t) = sens_label.single_mut() {
**t = format!("{new_pct:.0}%");
}
}
}
SettingsButton::Back => {
save_writer.write(SaveSettingsRequest);
next.set(PauseMenuState::Paused);
}
}
}
}
fn step_fov_degrees(current_deg: f32, increase: bool) -> f32 {
let delta = if increase { 5.0 } else { -5.0 };
(current_deg + delta).clamp(50.0, 120.0)
}
fn step_volume(current: f32, increase: bool) -> f32 {
let delta = if increase { 0.1 } else { -0.1 };
(current + delta).clamp(0.0, 1.0)
}
fn step_render_distance_chunks(load_distance: f32, increase: bool) -> i32 {
let current = ((load_distance / 16.0).round() as i32).clamp(4, 32);
let current = if current % 2 == 0 {
current
} else {
current + 1
};
let delta = if increase { 2 } else { -2 };
(current + delta).clamp(4, 32)
}
fn step_sensitivity_pct(sensitivity: f32, increase: bool) -> i32 {
let current_pct = (sensitivity * 100.0).round() as i32;
let delta = if increase { 1 } else { -1 };
(current_pct + delta).clamp(10, 100)
}
#[cfg(test)]
mod tests {
use super::*;
use bevy::ecs::message::Messages;
use bevy::ecs::system::RunSystemOnce;
use crate::player::player_cursor_system;
use bevy::state::app::StatesPlugin;
use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
fn pause_cursor_app() -> (App, Entity) {
let mut app = App::new();
app.add_plugins(StatesPlugin);
app.init_state::<PauseMenuState>();
app.add_message::<SfxRequest>();
app.init_resource::<ButtonInput<KeyCode>>();
app.init_resource::<ButtonInput<MouseButton>>();
app.add_systems(
Update,
(
toggle_pause.run_if(in_state(PauseMenuState::Playing)),
escape_to_resume.run_if(in_state(PauseMenuState::Paused)),
player_cursor_system.run_if(in_state(PauseMenuState::Playing)),
),
);
app.add_systems(OnEnter(PauseMenuState::Paused), release_cursor);
let window = app
.world_mut()
.spawn((
Window {
focused: true,
..default()
},
PrimaryWindow,
))
.id();
(app, window)
}
fn tap(app: &mut App, key: KeyCode) {
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.press(key);
app.update();
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.reset_all();
app.update();
}
fn click(app: &mut App) {
app.world_mut()
.resource_mut::<ButtonInput<MouseButton>>()
.press(MouseButton::Left);
app.update();
app.world_mut()
.resource_mut::<ButtonInput<MouseButton>>()
.reset_all();
}
fn pause_state(app: &App) -> PauseMenuState {
app.world()
.resource::<State<PauseMenuState>>()
.get()
.clone()
}
fn grab(app: &App, window: Entity) -> CursorGrabMode {
app.world()
.get::<CursorOptions>(window)
.expect("window should still exist")
.grab_mode
}
#[test]
fn cursor_follows_pause_focus_and_click_with_the_player_cursor_system() {
let (mut app, window) = pause_cursor_app();
tap(&mut app, KeyCode::Escape);
assert_eq!(pause_state(&app), PauseMenuState::Paused);
assert_eq!(grab(&app, window), CursorGrabMode::None);
tap(&mut app, KeyCode::Escape);
assert_eq!(pause_state(&app), PauseMenuState::Playing);
assert_eq!(grab(&app, window), CursorGrabMode::Locked);
app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
app.update();
assert_eq!(grab(&app, window), CursorGrabMode::None);
assert_eq!(pause_state(&app), PauseMenuState::Playing);
app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
app.update();
assert_eq!(grab(&app, window), CursorGrabMode::None);
click(&mut app);
assert_eq!(grab(&app, window), CursorGrabMode::Locked);
tap(&mut app, KeyCode::Escape);
assert_eq!(pause_state(&app), PauseMenuState::Paused);
assert_eq!(grab(&app, window), CursorGrabMode::None);
}
#[test]
fn resuming_does_not_capture_an_unfocused_window() {
let (mut app, window) = pause_cursor_app();
tap(&mut app, KeyCode::Escape);
assert_eq!(pause_state(&app), PauseMenuState::Paused);
app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.press(KeyCode::Escape);
app.update();
assert_eq!(grab(&app, window), CursorGrabMode::None);
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.reset_all();
app.update();
assert_eq!(pause_state(&app), PauseMenuState::Playing);
assert_eq!(grab(&app, window), CursorGrabMode::None);
}
#[test]
fn pause_cursor_changes_only_touch_the_primary_window() {
let (mut app, window) = pause_cursor_app();
let secondary = app
.world_mut()
.spawn((
Window {
focused: false,
..default()
},
CursorOptions {
grab_mode: CursorGrabMode::Confined,
..default()
},
))
.id();
tap(&mut app, KeyCode::Escape);
tap(&mut app, KeyCode::Escape);
assert_eq!(grab(&app, window), CursorGrabMode::Locked);
assert_eq!(grab(&app, secondary), CursorGrabMode::Confined);
}
#[test]
fn fov_steps_by_five_degrees_within_limits() {
assert_eq!(step_fov_degrees(70.0, true), 75.0);
assert_eq!(step_fov_degrees(70.0, false), 65.0);
assert_eq!(step_fov_degrees(118.0, true), 120.0);
assert_eq!(step_fov_degrees(52.0, false), 50.0);
}
#[test]
fn volume_steps_by_a_tenth_within_limits() {
assert!((step_volume(0.5, true) - 0.6).abs() < 1e-6);
assert!((step_volume(0.5, false) - 0.4).abs() < 1e-6);
assert_eq!(step_volume(0.95, true), 1.0);
assert_eq!(step_volume(0.05, false), 0.0);
}
#[test]
fn render_distance_steps_by_two_chunks_within_limits() {
assert_eq!(step_render_distance_chunks(150.0, true), 12);
assert_eq!(step_render_distance_chunks(150.0, false), 8);
assert_eq!(step_render_distance_chunks(8.0 * 16.0, true), 10);
assert_eq!(step_render_distance_chunks(32.0 * 16.0, true), 32);
assert_eq!(step_render_distance_chunks(4.0 * 16.0, false), 4);
assert_eq!(step_render_distance_chunks(1000.0 * 16.0, false), 30);
}
#[test]
fn sensitivity_steps_by_one_percent_within_limits() {
assert_eq!(step_sensitivity_pct(1.0, false), 99);
assert_eq!(step_sensitivity_pct(1.0, true), 100);
assert_eq!(step_sensitivity_pct(0.5, true), 51);
assert_eq!(step_sensitivity_pct(0.1, false), 10);
}
fn settings_world(pressed: SettingsButton) -> World {
let mut world = World::new();
world.insert_resource(SfxConfig::default());
world.init_resource::<NextState<PauseMenuState>>();
world.init_resource::<Messages<SaveSettingsRequest>>();
world.spawn((
Button,
Interaction::Pressed,
BackgroundColor(Color::NONE),
pressed,
));
world
}
fn press(world: &mut World) {
world
.run_system_once(handle_settings_buttons)
.expect("handle_settings_buttons should run");
}
#[test]
fn sensitivity_button_updates_config_and_live_players() {
let mut world = settings_world(SettingsButton::SensitivityDec);
world.insert_resource(PlayerConfig::default());
let player = world.spawn(Player::default()).id();
assert_eq!(world.get::<Player>(player).unwrap().sensitivity, 1.0);
press(&mut world);
assert!((world.resource::<PlayerConfig>().sensitivity - 0.99).abs() < 1e-6);
assert!(
(world.get::<Player>(player).unwrap().sensitivity - 0.99).abs() < 1e-6,
"the live player must pick up the new sensitivity without a restart"
);
}
#[test]
fn volume_button_updates_sfx_config() {
let mut world = settings_world(SettingsButton::VolumeDec);
let before = world.resource::<SfxConfig>().volume;
press(&mut world);
let after = world.resource::<SfxConfig>().volume;
assert!((after - (before - 0.1).clamp(0.0, 1.0)).abs() < 1e-6);
}
#[test]
fn back_button_requests_save_and_returns_to_pause() {
let mut world = settings_world(SettingsButton::Back);
press(&mut world);
let saves = world.resource::<Messages<SaveSettingsRequest>>();
assert_eq!(saves.iter_current_update_messages().count(), 1);
assert!(matches!(
*world.resource::<NextState<PauseMenuState>>(),
NextState::Pending(PauseMenuState::Paused)
));
}
const PRIMARY: ButtonColors = ButtonColors {
normal: Color::srgb(0.10, 0.20, 0.30),
hovered: Color::srgb(0.11, 0.21, 0.31),
pressed: Color::srgb(0.12, 0.22, 0.32),
text: Color::srgb(0.13, 0.23, 0.33),
};
const SECONDARY: ButtonColors = ButtonColors {
normal: Color::srgb(0.40, 0.50, 0.60),
hovered: Color::srgb(0.41, 0.51, 0.61),
pressed: Color::srgb(0.42, 0.52, 0.62),
text: Color::srgb(0.43, 0.53, 0.63),
};
fn custom_theme() -> PauseMenuTheme {
PauseMenuTheme {
overlay: Color::srgba(0.9, 0.1, 0.1, 0.5),
panel: Color::srgb(0.9, 0.9, 0.8),
header: Color::srgb(0.1, 0.9, 0.1),
text: Color::srgb(0.1, 0.1, 0.9),
label: Color::srgb(0.9, 0.1, 0.9),
button: PRIMARY,
secondary_button: SECONDARY,
corner_radius: 9.0,
panel_width: Val::Px(520.0),
panel_padding: UiRect::all(Val::Px(32.0)),
}
}
fn menu_world(theme: Option<PauseMenuTheme>) -> World {
let mut world = World::new();
world.insert_resource(PauseMenuConfig::default());
world.insert_resource(SfxConfig::default());
if let Some(theme) = theme {
world.insert_resource(theme);
}
world
}
fn open_pause_menu(world: &mut World) {
world
.run_system_once(spawn_pause_menu)
.expect("spawn_pause_menu should run");
}
fn open_settings_menu(world: &mut World) {
world
.run_system_once(spawn_settings_menu)
.expect("spawn_settings_menu should run");
}
fn text_color(world: &mut World, content: &str) -> Color {
let mut query = world.query::<(&Text, &TextColor)>();
let found: Vec<Color> = query
.iter(world)
.filter(|(text, _)| text.0 == content)
.map(|(_, color)| color.0)
.collect();
assert_eq!(found.len(), 1, "expected exactly one text {content:?}");
found[0]
}
fn overlay<R: Component>(world: &mut World) -> (Entity, Color) {
let mut query = world.query_filtered::<(Entity, &BackgroundColor), With<R>>();
let (root, bg) = query
.single(world)
.expect("the menu should have exactly one overlay root");
(root, bg.0)
}
fn panel(world: &mut World) -> (Color, Node, Entity) {
let mut query =
world.query_filtered::<(&BackgroundColor, &Node, &ChildOf), With<PauseMenuPanel>>();
let (bg, node, child_of) = query
.single(world)
.expect("the menu should have exactly one panel");
(bg.0, node.clone(), child_of.parent())
}
fn pause_buttons(
world: &mut World,
select: fn(&PauseButton) -> bool,
) -> Vec<(Color, BorderRadius)> {
let mut query = world.query::<(&PauseButton, &BackgroundColor, &Node)>();
query
.iter(world)
.filter(|(action, _, _)| select(action))
.map(|(_, bg, node)| (bg.0, node.border_radius))
.collect()
}
fn settings_buttons(
world: &mut World,
select: fn(&SettingsButton) -> bool,
) -> Vec<(Color, BorderRadius)> {
let mut query = world.query::<(&SettingsButton, &BackgroundColor, &Node)>();
query
.iter(world)
.filter(|(action, _, _)| select(action))
.map(|(_, bg, node)| (bg.0, node.border_radius))
.collect()
}
#[test]
fn default_theme_equals_the_previous_constants() {
let buttons = ButtonColors::default();
assert_eq!(buttons.normal, Color::srgb(0.15, 0.15, 0.20));
assert_eq!(buttons.hovered, Color::srgb(0.25, 0.25, 0.35));
assert_eq!(buttons.pressed, Color::srgb(0.35, 0.35, 0.50));
assert_eq!(buttons.text, Color::WHITE);
let theme = PauseMenuTheme::default();
assert_eq!(theme.overlay, Color::srgba(0.0, 0.0, 0.0, 0.78));
assert_eq!(theme.panel, Color::NONE);
assert_eq!(theme.header, Color::WHITE);
assert_eq!(theme.text, Color::WHITE);
assert_eq!(theme.label, Color::srgb(0.8, 0.8, 0.8));
assert_eq!(theme.button, buttons);
assert_eq!(theme.secondary_button, buttons);
assert_eq!(theme.corner_radius, 0.0);
assert_eq!(theme.panel_width, Val::Auto);
assert_eq!(theme.panel_padding, UiRect::ZERO);
}
#[test]
fn button_colors_pick_the_background_for_each_interaction() {
assert_eq!(PRIMARY.background(Interaction::None), PRIMARY.normal);
assert_eq!(PRIMARY.background(Interaction::Hovered), PRIMARY.hovered);
assert_eq!(PRIMARY.background(Interaction::Pressed), PRIMARY.pressed);
}
#[test]
fn pause_menu_without_a_theme_resource_keeps_the_previous_look() {
let mut world = menu_world(None);
open_pause_menu(&mut world);
let (root, overlay_bg) = overlay::<PauseMenuRoot>(&mut world);
assert_eq!(overlay_bg, Color::srgba(0.0, 0.0, 0.0, 0.78));
let (panel_bg, panel_node, panel_parent) = panel(&mut world);
assert_eq!(panel_parent, root);
assert_eq!(panel_bg, Color::NONE);
assert_eq!(panel_node.width, Val::Auto);
assert_eq!(panel_node.padding, UiRect::ZERO);
assert_eq!(panel_node.border_radius, BorderRadius::ZERO);
assert_eq!(panel_node.row_gap, Val::Px(14.0));
assert_eq!(panel_node.flex_direction, FlexDirection::Column);
assert_eq!(panel_node.align_items, AlignItems::Center);
assert_eq!(text_color(&mut world, "PAUSED"), Color::WHITE);
let buttons = pause_buttons(&mut world, |_| true);
assert_eq!(buttons.len(), 3);
for (bg, radius) in buttons {
assert_eq!(bg, Color::srgb(0.15, 0.15, 0.20));
assert_eq!(radius, BorderRadius::ZERO);
}
for label in ["Resume", "Settings", "Quit"] {
assert_eq!(text_color(&mut world, label), Color::WHITE);
}
}
#[test]
fn custom_theme_styles_the_pause_menu() {
let theme = custom_theme();
let mut world = menu_world(Some(theme.clone()));
open_pause_menu(&mut world);
let (root, overlay_bg) = overlay::<PauseMenuRoot>(&mut world);
assert_eq!(overlay_bg, theme.overlay);
let (panel_bg, panel_node, panel_parent) = panel(&mut world);
assert_eq!(panel_parent, root);
assert_eq!(panel_bg, theme.panel);
assert_eq!(panel_node.width, Val::Px(520.0));
assert_eq!(panel_node.padding, UiRect::all(Val::Px(32.0)));
assert_eq!(panel_node.border_radius, BorderRadius::all(Val::Px(9.0)));
assert_eq!(text_color(&mut world, "PAUSED"), theme.header);
let radius = BorderRadius::all(Val::Px(9.0));
assert_eq!(
pause_buttons(&mut world, |b| matches!(b, PauseButton::Resume)),
vec![(PRIMARY.normal, radius)]
);
assert_eq!(
pause_buttons(&mut world, |b| !matches!(b, PauseButton::Resume)),
vec![(SECONDARY.normal, radius); 2]
);
assert_eq!(text_color(&mut world, "Resume"), PRIMARY.text);
assert_eq!(text_color(&mut world, "Settings"), SECONDARY.text);
assert_eq!(text_color(&mut world, "Quit"), SECONDARY.text);
}
#[test]
fn pause_menu_buttons_are_children_of_the_panel() {
let mut world = menu_world(None);
open_pause_menu(&mut world);
let mut panels = world.query_filtered::<Entity, With<PauseMenuPanel>>();
let panel_entity = panels.single(&world).expect("one panel");
let mut buttons = world.query_filtered::<&ChildOf, With<PauseButton>>();
let parents: Vec<Entity> = buttons.iter(&world).map(|c| c.parent()).collect();
assert_eq!(parents, vec![panel_entity; 3]);
}
#[test]
fn settings_menu_without_a_theme_resource_keeps_the_previous_look() {
let mut world = menu_world(None);
open_settings_menu(&mut world);
let (root, overlay_bg) = overlay::<SettingsMenuRoot>(&mut world);
assert_eq!(overlay_bg, Color::srgba(0.0, 0.0, 0.0, 0.78));
let (panel_bg, panel_node, panel_parent) = panel(&mut world);
assert_eq!(panel_parent, root);
assert_eq!(panel_bg, Color::NONE);
assert_eq!(panel_node.width, Val::Auto);
assert_eq!(panel_node.padding, UiRect::ZERO);
assert_eq!(text_color(&mut world, "SETTINGS"), Color::WHITE);
assert_eq!(
text_color(&mut world, "Field of View"),
Color::srgb(0.8, 0.8, 0.8)
);
let mut values = world.query_filtered::<&TextColor, With<FovLabel>>();
assert_eq!(
values.single(&world).expect("one FOV value").0,
Color::WHITE
);
let buttons = settings_buttons(&mut world, |_| true);
assert_eq!(buttons.len(), 9);
for (bg, radius) in buttons {
assert_eq!(bg, Color::srgb(0.15, 0.15, 0.20));
assert_eq!(radius, BorderRadius::ZERO);
}
assert_eq!(text_color(&mut world, "< Back"), Color::WHITE);
}
#[test]
fn custom_theme_styles_the_settings_menu() {
let theme = custom_theme();
let mut world = menu_world(Some(theme.clone()));
open_settings_menu(&mut world);
let (root, overlay_bg) = overlay::<SettingsMenuRoot>(&mut world);
assert_eq!(overlay_bg, theme.overlay);
let (panel_bg, panel_node, panel_parent) = panel(&mut world);
assert_eq!(panel_parent, root);
assert_eq!(panel_bg, theme.panel);
assert_eq!(panel_node.width, Val::Px(520.0));
assert_eq!(panel_node.padding, UiRect::all(Val::Px(32.0)));
assert_eq!(panel_node.border_radius, BorderRadius::all(Val::Px(9.0)));
assert_eq!(text_color(&mut world, "SETTINGS"), theme.header);
for label in [
"Field of View",
"SFX Volume",
"Render Distance",
"Sensitivity",
] {
assert_eq!(text_color(&mut world, label), theme.label);
}
let mut values = world.query_filtered::<&TextColor, With<FovLabel>>();
assert_eq!(values.single(&world).expect("one FOV value").0, theme.text);
let radius = BorderRadius::all(Val::Px(9.0));
assert_eq!(
settings_buttons(&mut world, |b| matches!(b, SettingsButton::Back)),
vec![(PRIMARY.normal, radius)]
);
assert_eq!(
settings_buttons(&mut world, |b| !matches!(b, SettingsButton::Back)),
vec![(SECONDARY.normal, radius); 8]
);
assert_eq!(text_color(&mut world, "< Back"), PRIMARY.text);
}
fn handler_world(theme: Option<PauseMenuTheme>) -> World {
let mut world = World::new();
world.insert_resource(SfxConfig::default());
world.init_resource::<NextState<PauseMenuState>>();
world.init_resource::<Messages<SaveSettingsRequest>>();
world.init_resource::<Messages<SfxRequest>>();
world.init_resource::<Messages<AppExit>>();
if let Some(theme) = theme {
world.insert_resource(theme);
}
world
}
fn spawn_button<A: Component>(world: &mut World, action: A, state: Interaction) -> Entity {
world
.spawn((Button, state, BackgroundColor(Color::NONE), action))
.id()
}
fn background(world: &World, entity: Entity) -> Color {
world
.get::<BackgroundColor>(entity)
.expect("button should exist")
.0
}
#[test]
fn pause_buttons_take_theme_colors_per_interaction_state() {
let mut world = handler_world(Some(custom_theme()));
let primary_idle = spawn_button(&mut world, PauseButton::Resume, Interaction::None);
let primary_hovered = spawn_button(&mut world, PauseButton::Resume, Interaction::Hovered);
let primary_pressed = spawn_button(&mut world, PauseButton::Resume, Interaction::Pressed);
let secondary_idle = spawn_button(&mut world, PauseButton::Settings, Interaction::None);
let secondary_hovered = spawn_button(&mut world, PauseButton::Quit, Interaction::Hovered);
let secondary_pressed =
spawn_button(&mut world, PauseButton::Settings, Interaction::Pressed);
world
.run_system_once(handle_pause_buttons)
.expect("handle_pause_buttons should run");
assert_eq!(background(&world, primary_idle), PRIMARY.normal);
assert_eq!(background(&world, primary_hovered), PRIMARY.hovered);
assert_eq!(background(&world, primary_pressed), PRIMARY.pressed);
assert_eq!(background(&world, secondary_idle), SECONDARY.normal);
assert_eq!(background(&world, secondary_hovered), SECONDARY.hovered);
assert_eq!(background(&world, secondary_pressed), SECONDARY.pressed);
}
#[test]
fn settings_buttons_take_theme_colors_per_interaction_state() {
let mut world = handler_world(Some(custom_theme()));
let primary_idle = spawn_button(&mut world, SettingsButton::Back, Interaction::None);
let primary_hovered = spawn_button(&mut world, SettingsButton::Back, Interaction::Hovered);
let primary_pressed = spawn_button(&mut world, SettingsButton::Back, Interaction::Pressed);
let secondary_idle = spawn_button(&mut world, SettingsButton::FovInc, Interaction::None);
let secondary_hovered =
spawn_button(&mut world, SettingsButton::VolumeDec, Interaction::Hovered);
let secondary_pressed =
spawn_button(&mut world, SettingsButton::FovDec, Interaction::Pressed);
press(&mut world);
assert_eq!(background(&world, primary_idle), PRIMARY.normal);
assert_eq!(background(&world, primary_hovered), PRIMARY.hovered);
assert_eq!(background(&world, primary_pressed), PRIMARY.pressed);
assert_eq!(background(&world, secondary_idle), SECONDARY.normal);
assert_eq!(background(&world, secondary_hovered), SECONDARY.hovered);
assert_eq!(background(&world, secondary_pressed), SECONDARY.pressed);
}
#[test]
fn buttons_without_a_theme_resource_use_the_previous_colors() {
let mut world = handler_world(None);
let pause_idle = spawn_button(&mut world, PauseButton::Settings, Interaction::None);
let pause_hovered = spawn_button(&mut world, PauseButton::Resume, Interaction::Hovered);
let pause_pressed = spawn_button(&mut world, PauseButton::Settings, Interaction::Pressed);
let settings_idle = spawn_button(&mut world, SettingsButton::Back, Interaction::None);
let settings_hovered =
spawn_button(&mut world, SettingsButton::FovInc, Interaction::Hovered);
let settings_pressed =
spawn_button(&mut world, SettingsButton::FovDec, Interaction::Pressed);
world
.run_system_once(handle_pause_buttons)
.expect("handle_pause_buttons should run");
press(&mut world);
for idle in [pause_idle, settings_idle] {
assert_eq!(background(&world, idle), Color::srgb(0.15, 0.15, 0.20));
}
for hovered in [pause_hovered, settings_hovered] {
assert_eq!(background(&world, hovered), Color::srgb(0.25, 0.25, 0.35));
}
for pressed in [pause_pressed, settings_pressed] {
assert_eq!(background(&world, pressed), Color::srgb(0.35, 0.35, 0.50));
}
}
}