1use bevy::asset::embedded_asset;
54use bevy::prelude::*;
55
56use crate::audio::{SfxConfig, SfxEvent, SfxRequest};
57use crate::player::{Player, PlayerConfig};
58use crate::settings::{RENDER_DISTANCE_STEP, RENDER_DISTANCE_UNLOAD_MARGIN};
59use crate::world::{ChunkManager, WorldConfig};
60
61pub const EMBEDDED_NOTO_SANS_PATH: &str = "embedded://voxel_framework/ui/NotoSans-Regular.ttf";
69
70pub const EMBEDDED_NOTO_SYMBOLS_PATH: &str =
77 "embedded://voxel_framework/ui/NotoSansSymbols2-Regular.ttf";
78
79#[derive(States, Debug, Clone, PartialEq, Eq, Hash, Default)]
108pub enum PauseMenuState {
109 #[default]
112 Playing,
113 Paused,
116 Settings,
119}
120
121#[derive(Debug, Clone, Copy, PartialEq)]
136pub struct ButtonColors {
137 pub normal: Color,
139 pub hovered: Color,
141 pub pressed: Color,
143 pub text: Color,
146}
147
148impl ButtonColors {
149 pub fn background(&self, interaction: Interaction) -> Color {
153 match interaction {
154 Interaction::None => self.normal,
155 Interaction::Hovered => self.hovered,
156 Interaction::Pressed => self.pressed,
157 }
158 }
159}
160
161impl Default for ButtonColors {
162 fn default() -> Self {
163 Self {
164 normal: Color::srgb(0.15, 0.15, 0.20),
165 hovered: Color::srgb(0.25, 0.25, 0.35),
166 pressed: Color::srgb(0.35, 0.35, 0.50),
167 text: Color::WHITE,
168 }
169 }
170}
171
172#[derive(Resource, Debug, Clone, PartialEq)]
247pub struct PauseMenuTheme {
248 pub overlay: Color,
251 pub panel: Color,
255 pub header: Color,
257 pub text: Color,
260 pub label: Color,
263 pub button: ButtonColors,
266 pub secondary_button: ButtonColors,
269 pub corner_radius: f32,
272 pub panel_width: Val,
276 pub panel_padding: UiRect,
278}
279
280impl Default for PauseMenuTheme {
281 fn default() -> Self {
282 Self {
283 overlay: Color::srgba(0.0, 0.0, 0.0, 0.78),
284 panel: Color::NONE,
285 header: Color::WHITE,
286 text: Color::WHITE,
287 label: Color::srgb(0.8, 0.8, 0.8),
288 button: ButtonColors::default(),
289 secondary_button: ButtonColors::default(),
290 corner_radius: 0.0,
291 panel_width: Val::Auto,
292 panel_padding: UiRect::ZERO,
293 }
294 }
295}
296
297fn current_theme(theme: Option<Res<PauseMenuTheme>>) -> PauseMenuTheme {
300 theme.as_deref().cloned().unwrap_or_default()
301}
302
303trait ThemedButton {
306 fn colors(&self, theme: &PauseMenuTheme) -> ButtonColors;
307}
308
309#[derive(Component)]
312struct PauseMenuRoot;
313#[derive(Component)]
314struct SettingsMenuRoot;
315#[derive(Component)]
317struct PauseMenuPanel;
318#[derive(Component)]
319struct FovLabel;
320#[derive(Component)]
321struct VolumeLabel;
322#[derive(Component)]
323struct RenderDistLabel;
324#[derive(Component)]
325struct SensitivityLabel;
326
327#[derive(Component)]
328enum PauseButton {
329 Resume,
330 Settings,
331 Quit,
332}
333
334#[derive(Component)]
335enum SettingsButton {
336 FovInc,
337 FovDec,
338 VolumeInc,
339 VolumeDec,
340 RenderDistInc,
341 RenderDistDec,
342 SensitivityInc,
343 SensitivityDec,
344 Back,
345}
346
347impl ThemedButton for PauseButton {
348 fn colors(&self, theme: &PauseMenuTheme) -> ButtonColors {
349 match self {
350 PauseButton::Resume => theme.button,
351 PauseButton::Settings | PauseButton::Quit => theme.secondary_button,
352 }
353 }
354}
355
356impl ThemedButton for SettingsButton {
357 fn colors(&self, theme: &PauseMenuTheme) -> ButtonColors {
358 match self {
359 SettingsButton::Back => theme.button,
360 _ => theme.secondary_button,
361 }
362 }
363}
364
365#[derive(Message, Debug, Clone)]
374pub struct SaveSettingsRequest;
375
376#[derive(Resource, Clone)]
401pub struct PauseMenuConfig {
402 pub font: Handle<Font>,
412 pub symbol_font: Handle<Font>,
422}
423
424impl Default for PauseMenuConfig {
425 fn default() -> Self {
426 Self {
427 font: Handle::default(),
428 symbol_font: Handle::default(),
429 }
430 }
431}
432
433pub struct PauseMenuPlugin;
490
491impl Plugin for PauseMenuPlugin {
492 fn build(&self, app: &mut App) {
493 embedded_asset!(app, "NotoSans-Regular.ttf");
497 embedded_asset!(app, "NotoSansSymbols2-Regular.ttf");
498
499 app.init_resource::<PauseMenuConfig>();
500 app.init_resource::<PauseMenuTheme>();
501 app.init_state::<PauseMenuState>();
502 app.add_message::<SaveSettingsRequest>();
503
504 app.add_systems(Startup, load_default_font);
509
510 app.add_systems(
512 Update,
513 toggle_pause.run_if(in_state(PauseMenuState::Playing)),
514 );
515
516 app.add_systems(
518 OnEnter(PauseMenuState::Paused),
519 (spawn_pause_menu, release_cursor),
520 );
521 app.add_systems(OnExit(PauseMenuState::Paused), despawn_pause_menu);
522 app.add_systems(
523 Update,
524 (handle_pause_buttons, escape_to_resume).run_if(in_state(PauseMenuState::Paused)),
525 );
526
527 app.add_systems(OnEnter(PauseMenuState::Settings), spawn_settings_menu);
529 app.add_systems(OnExit(PauseMenuState::Settings), despawn_settings_menu);
530 app.add_systems(
531 Update,
532 handle_settings_buttons.run_if(in_state(PauseMenuState::Settings)),
533 );
534 }
535}
536
537fn load_default_font(mut cfg: ResMut<PauseMenuConfig>, asset_server: Res<AssetServer>) {
548 if cfg.font == Handle::default() {
549 cfg.font = asset_server.load(EMBEDDED_NOTO_SANS_PATH);
550 }
551 if cfg.symbol_font == Handle::default() {
552 cfg.symbol_font = asset_server.load(EMBEDDED_NOTO_SYMBOLS_PATH);
553 }
554}
555
556fn release_cursor(mut windows: PrimaryCursor) {
564 for (_, mut cursor) in &mut windows {
565 cursor.grab_mode = bevy::window::CursorGrabMode::None;
566 cursor.visible = true;
567 }
568}
569
570type PrimaryCursor<'w, 's> = Query<
573 'w,
574 's,
575 (&'static Window, &'static mut bevy::window::CursorOptions),
576 With<bevy::window::PrimaryWindow>,
577>;
578
579fn lock_cursor(windows: &mut PrimaryCursor) {
588 for (window, mut cursor) in windows.iter_mut() {
589 if !window.focused {
590 continue;
591 }
592 cursor.grab_mode = bevy::window::CursorGrabMode::Locked;
593 cursor.visible = false;
594 }
595}
596
597fn toggle_pause(
604 keys: Res<ButtonInput<KeyCode>>,
605 mut next: ResMut<NextState<PauseMenuState>>,
606 mut sfx: MessageWriter<SfxRequest>,
607) {
608 if keys.just_pressed(KeyCode::Escape) {
609 next.set(PauseMenuState::Paused);
610 sfx.write(SfxRequest {
611 event: SfxEvent::PauseOpen,
612 position: None,
613 });
614 }
615}
616
617fn escape_to_resume(
622 keys: Res<ButtonInput<KeyCode>>,
623 mut next: ResMut<NextState<PauseMenuState>>,
624 mut windows: PrimaryCursor,
625 mut sfx: MessageWriter<SfxRequest>,
626) {
627 if keys.just_pressed(KeyCode::Escape) {
628 next.set(PauseMenuState::Playing);
629 lock_cursor(&mut windows);
630 sfx.write(SfxRequest {
631 event: SfxEvent::PauseClose,
632 position: None,
633 });
634 }
635}
636
637fn spawn_btn<C: Component + ThemedButton>(
640 parent: &mut ChildSpawnerCommands,
641 label: &str,
642 action: C,
643 width: f32,
644 height: f32,
645 font: Handle<Font>,
646 theme: &PauseMenuTheme,
647) {
648 let colors = action.colors(theme);
649 parent
650 .spawn((
651 action,
652 Button,
653 Node {
654 width: Val::Px(width),
655 height: Val::Px(height),
656 justify_content: JustifyContent::Center,
657 align_items: AlignItems::Center,
658 border_radius: BorderRadius::all(Val::Px(theme.corner_radius)),
659 ..default()
660 },
661 BackgroundColor(colors.normal),
662 ))
663 .with_children(|b| {
664 b.spawn((
665 Text::new(label),
666 TextFont {
667 font,
668 font_size: 20.0,
669 ..default()
670 },
671 TextColor(colors.text),
672 ));
673 });
674}
675
676fn overlay_node(theme: &PauseMenuTheme) -> (Node, BackgroundColor) {
677 (
678 Node {
679 width: Val::Percent(100.0),
680 height: Val::Percent(100.0),
681 flex_direction: FlexDirection::Column,
682 justify_content: JustifyContent::Center,
683 align_items: AlignItems::Center,
684 row_gap: Val::Px(14.0),
685 ..default()
686 },
687 BackgroundColor(theme.overlay),
688 )
689}
690
691fn panel_node(theme: &PauseMenuTheme) -> (PauseMenuPanel, Node, BackgroundColor) {
697 (
698 PauseMenuPanel,
699 Node {
700 width: theme.panel_width,
701 padding: theme.panel_padding,
702 flex_direction: FlexDirection::Column,
703 justify_content: JustifyContent::Center,
704 align_items: AlignItems::Center,
705 row_gap: Val::Px(14.0),
706 border_radius: BorderRadius::all(Val::Px(theme.corner_radius)),
707 ..default()
708 },
709 BackgroundColor(theme.panel),
710 )
711}
712
713fn spawn_pause_menu(
721 mut commands: Commands,
722 config: Res<PauseMenuConfig>,
723 theme: Option<Res<PauseMenuTheme>>,
724) {
725 let theme = current_theme(theme);
726 let (node, bg) = overlay_node(&theme);
727 commands
728 .spawn((PauseMenuRoot, node, bg))
729 .with_children(|overlay| {
730 overlay.spawn(panel_node(&theme)).with_children(|p| {
731 p.spawn((
732 Text::new("PAUSED"),
733 TextFont {
734 font: config.font.clone(),
735 font_size: 52.0,
736 ..default()
737 },
738 TextColor(theme.header),
739 Node {
740 margin: UiRect::bottom(Val::Px(28.0)),
741 ..default()
742 },
743 ));
744 spawn_btn(
745 p,
746 "Resume",
747 PauseButton::Resume,
748 280.0,
749 52.0,
750 config.font.clone(),
751 &theme,
752 );
753 spawn_btn(
754 p,
755 "Settings",
756 PauseButton::Settings,
757 280.0,
758 52.0,
759 config.font.clone(),
760 &theme,
761 );
762 spawn_btn(
763 p,
764 "Quit",
765 PauseButton::Quit,
766 280.0,
767 52.0,
768 config.font.clone(),
769 &theme,
770 );
771 });
772 });
773}
774
775fn despawn_pause_menu(mut commands: Commands, q: Query<Entity, With<PauseMenuRoot>>) {
780 for e in &q {
781 commands.entity(e).despawn();
782 }
783}
784
785fn handle_pause_buttons(
792 mut q: Query<
793 (&Interaction, &mut BackgroundColor, &PauseButton),
794 (Changed<Interaction>, With<Button>),
795 >,
796 mut next: ResMut<NextState<PauseMenuState>>,
797 mut windows: PrimaryCursor,
798 mut app_exit: MessageWriter<AppExit>,
799 mut sfx: MessageWriter<SfxRequest>,
800 theme: Option<Res<PauseMenuTheme>>,
801) {
802 let theme = current_theme(theme);
803 for (interaction, mut bg, action) in &mut q {
804 *bg = BackgroundColor(action.colors(&theme).background(*interaction));
805 if *interaction != Interaction::Pressed {
806 continue;
807 }
808 match action {
809 PauseButton::Resume => {
810 next.set(PauseMenuState::Playing);
811 lock_cursor(&mut windows);
812 sfx.write(SfxRequest {
813 event: SfxEvent::PauseClose,
814 position: None,
815 });
816 }
817 PauseButton::Settings => next.set(PauseMenuState::Settings),
818 PauseButton::Quit => {
819 app_exit.write(AppExit::Success);
820 }
821 }
822 }
823}
824
825fn spawn_settings_menu(
834 mut commands: Commands,
835 sfx_config: Res<SfxConfig>,
836 world_config: Option<Res<WorldConfig>>,
837 player_config: Option<Res<PlayerConfig>>,
838 camera_q: Query<&Projection, With<Camera3d>>,
839 config: Res<PauseMenuConfig>,
840 theme: Option<Res<PauseMenuTheme>>,
841) {
842 let fov_deg = camera_q
843 .single()
844 .ok()
845 .and_then(|p| {
846 if let Projection::Perspective(pp) = p {
847 Some(pp.fov.to_degrees())
848 } else {
849 None
850 }
851 })
852 .unwrap_or(90.0);
853 let volume_pct = sfx_config.volume * 100.0;
854 let render_dist_chunks = world_config
855 .as_ref()
856 .map(|wc| ((wc.load_distance / RENDER_DISTANCE_STEP).round() as i32).clamp(4, 32))
857 .unwrap_or(10);
858 let render_dist_chunks = if render_dist_chunks % 2 == 0 {
860 render_dist_chunks
861 } else {
862 render_dist_chunks + 1
863 };
864 let sensitivity_pct = player_config
865 .as_ref()
866 .map(|pc| ((pc.sensitivity * 100.0).round() as i32).clamp(10, 100))
867 .unwrap_or(100);
868
869 let theme = current_theme(theme);
870 let (node, bg) = overlay_node(&theme);
871 commands
872 .spawn((SettingsMenuRoot, node, bg))
873 .with_children(|overlay| {
874 overlay.spawn(panel_node(&theme)).with_children(|p| {
875 p.spawn((
876 Text::new("SETTINGS"),
877 TextFont {
878 font: config.font.clone(),
879 font_size: 42.0,
880 ..default()
881 },
882 TextColor(theme.header),
883 Node {
884 margin: UiRect::bottom(Val::Px(20.0)),
885 ..default()
886 },
887 ));
888
889 spawn_slider_row(
890 p,
891 "Field of View",
892 format!("{fov_deg:.0}°"),
893 FovLabel,
894 SettingsButton::FovDec,
895 SettingsButton::FovInc,
896 config.font.clone(),
897 config.symbol_font.clone(),
898 &theme,
899 );
900
901 spawn_slider_row(
902 p,
903 "SFX Volume",
904 format!("{volume_pct:.0}%"),
905 VolumeLabel,
906 SettingsButton::VolumeDec,
907 SettingsButton::VolumeInc,
908 config.font.clone(),
909 config.symbol_font.clone(),
910 &theme,
911 );
912
913 spawn_slider_row(
914 p,
915 "Render Distance",
916 format!("{render_dist_chunks} chunks"),
917 RenderDistLabel,
918 SettingsButton::RenderDistDec,
919 SettingsButton::RenderDistInc,
920 config.font.clone(),
921 config.symbol_font.clone(),
922 &theme,
923 );
924
925 spawn_slider_row(
926 p,
927 "Sensitivity",
928 format!("{sensitivity_pct:.0}%"),
929 SensitivityLabel,
930 SettingsButton::SensitivityDec,
931 SettingsButton::SensitivityInc,
932 config.font.clone(),
933 config.symbol_font.clone(),
934 &theme,
935 );
936
937 p.spawn(Node {
938 margin: UiRect::top(Val::Px(20.0)),
939 ..default()
940 })
941 .with_children(|row| {
942 spawn_btn(
943 row,
944 "< Back",
945 SettingsButton::Back,
946 200.0,
947 50.0,
948 config.font.clone(),
949 &theme,
950 );
951 });
952 });
953 });
954}
955
956#[allow(clippy::too_many_arguments)]
957fn spawn_slider_row<L: Component, D: Component + ThemedButton, I: Component + ThemedButton>(
958 parent: &mut ChildSpawnerCommands,
959 label: &str,
960 value: String,
961 value_marker: L,
962 dec: D,
963 inc: I,
964 font: Handle<Font>,
965 symbol_font: Handle<Font>,
966 theme: &PauseMenuTheme,
967) {
968 parent
969 .spawn(Node {
970 flex_direction: FlexDirection::Row,
971 align_items: AlignItems::Center,
972 column_gap: Val::Px(12.0),
973 ..default()
974 })
975 .with_children(|row| {
976 row.spawn((
977 Text::new(label),
978 TextFont {
979 font: font.clone(),
980 font_size: 20.0,
981 ..default()
982 },
983 TextColor(theme.label),
984 Node {
985 width: Val::Px(200.0),
986 ..default()
987 },
988 ));
989 spawn_btn(row, "\u{25C0}", dec, 44.0, 44.0, symbol_font.clone(), theme);
990 row.spawn((
991 value_marker,
992 Text::new(value),
993 TextFont {
994 font: font.clone(),
995 font_size: 22.0,
996 ..default()
997 },
998 TextColor(theme.text),
999 Node {
1000 width: Val::Px(80.0),
1001 justify_content: JustifyContent::Center,
1002 ..default()
1003 },
1004 ));
1005 spawn_btn(row, "\u{25B6}", inc, 44.0, 44.0, symbol_font, theme);
1006 });
1007}
1008
1009fn despawn_settings_menu(mut commands: Commands, q: Query<Entity, With<SettingsMenuRoot>>) {
1014 for e in &q {
1015 commands.entity(e).despawn();
1016 }
1017}
1018
1019#[allow(clippy::too_many_arguments)]
1036fn handle_settings_buttons(
1037 mut q: Query<
1038 (&Interaction, &mut BackgroundColor, &SettingsButton),
1039 (Changed<Interaction>, With<Button>),
1040 >,
1041 mut sfx_config: ResMut<SfxConfig>,
1042 mut world_config: Option<ResMut<WorldConfig>>,
1043 mut chunk_manager: Option<ResMut<ChunkManager>>,
1044 mut player_config: Option<ResMut<PlayerConfig>>,
1045 mut next: ResMut<NextState<PauseMenuState>>,
1046 mut fov_label: Query<
1047 &mut Text,
1048 (
1049 With<FovLabel>,
1050 Without<VolumeLabel>,
1051 Without<RenderDistLabel>,
1052 Without<SensitivityLabel>,
1053 ),
1054 >,
1055 mut vol_label: Query<
1056 &mut Text,
1057 (
1058 With<VolumeLabel>,
1059 Without<FovLabel>,
1060 Without<RenderDistLabel>,
1061 Without<SensitivityLabel>,
1062 ),
1063 >,
1064 mut rdist_label: Query<
1065 &mut Text,
1066 (
1067 With<RenderDistLabel>,
1068 Without<FovLabel>,
1069 Without<VolumeLabel>,
1070 Without<SensitivityLabel>,
1071 ),
1072 >,
1073 mut sens_label: Query<
1074 &mut Text,
1075 (
1076 With<SensitivityLabel>,
1077 Without<FovLabel>,
1078 Without<VolumeLabel>,
1079 Without<RenderDistLabel>,
1080 ),
1081 >,
1082 mut camera_q: Query<&mut Projection, With<Camera3d>>,
1083 mut players: Query<&mut Player>,
1084 mut save_writer: MessageWriter<SaveSettingsRequest>,
1085 theme: Option<Res<PauseMenuTheme>>,
1086) {
1087 let theme = current_theme(theme);
1088 for (interaction, mut bg, action) in &mut q {
1089 *bg = BackgroundColor(action.colors(&theme).background(*interaction));
1090 if *interaction != Interaction::Pressed {
1091 continue;
1092 }
1093
1094 match action {
1095 SettingsButton::FovInc | SettingsButton::FovDec => {
1096 if let Ok(mut proj) = camera_q.single_mut() {
1097 if let Projection::Perspective(ref mut pp) = *proj {
1098 let new_fov = step_fov_degrees(
1099 pp.fov.to_degrees(),
1100 matches!(action, SettingsButton::FovInc),
1101 );
1102 pp.fov = new_fov.to_radians();
1103 if let Some(ref mut pc) = player_config {
1106 pc.fov_degrees = new_fov;
1107 }
1108 if let Ok(mut t) = fov_label.single_mut() {
1109 **t = format!("{new_fov:.0}°");
1110 }
1111 }
1112 }
1113 }
1114 SettingsButton::VolumeInc | SettingsButton::VolumeDec => {
1115 sfx_config.volume = step_volume(
1116 sfx_config.volume,
1117 matches!(action, SettingsButton::VolumeInc),
1118 );
1119 let pct = sfx_config.volume * 100.0;
1120 if let Ok(mut t) = vol_label.single_mut() {
1121 **t = format!("{pct:.0}%");
1122 }
1123 }
1124 SettingsButton::RenderDistInc | SettingsButton::RenderDistDec => {
1125 if let Some(ref mut wc) = world_config {
1126 let new_chunks = step_render_distance_chunks(
1127 wc.load_distance,
1128 matches!(action, SettingsButton::RenderDistInc),
1129 );
1130 wc.load_distance = new_chunks as f32 * RENDER_DISTANCE_STEP;
1131 wc.unload_distance = wc.load_distance + RENDER_DISTANCE_UNLOAD_MARGIN;
1132 if let Some(ref mut cm) = chunk_manager {
1133 cm.load_distance = wc.load_distance;
1134 cm.unload_distance = wc.unload_distance;
1135 }
1136 if let Ok(mut t) = rdist_label.single_mut() {
1137 **t = format!("{new_chunks} chunks");
1138 }
1139 }
1140 }
1141 SettingsButton::SensitivityInc | SettingsButton::SensitivityDec => {
1142 if let Some(ref mut pc) = player_config {
1143 let new_pct = step_sensitivity_pct(
1144 pc.sensitivity,
1145 matches!(action, SettingsButton::SensitivityInc),
1146 );
1147 pc.sensitivity = new_pct as f32 / 100.0;
1148 for mut player in &mut players {
1152 player.sensitivity = pc.sensitivity;
1153 }
1154 if let Ok(mut t) = sens_label.single_mut() {
1155 **t = format!("{new_pct:.0}%");
1156 }
1157 }
1158 }
1159 SettingsButton::Back => {
1160 save_writer.write(SaveSettingsRequest);
1161 next.set(PauseMenuState::Paused);
1162 }
1163 }
1164 }
1165}
1166
1167fn step_fov_degrees(current_deg: f32, increase: bool) -> f32 {
1174 let delta = if increase { 5.0 } else { -5.0 };
1175 (current_deg + delta).clamp(50.0, 120.0)
1176}
1177
1178fn step_volume(current: f32, increase: bool) -> f32 {
1180 let delta = if increase { 0.1 } else { -0.1 };
1181 (current + delta).clamp(0.0, 1.0)
1182}
1183
1184fn step_render_distance_chunks(load_distance: f32, increase: bool) -> i32 {
1188 let current = ((load_distance / RENDER_DISTANCE_STEP).round() as i32).clamp(4, 32);
1189 let current = if current % 2 == 0 {
1190 current
1191 } else {
1192 current + 1
1193 };
1194 let delta = if increase { 2 } else { -2 };
1195 (current + delta).clamp(4, 32)
1196}
1197
1198fn step_sensitivity_pct(sensitivity: f32, increase: bool) -> i32 {
1200 let current_pct = (sensitivity * 100.0).round() as i32;
1201 let delta = if increase { 1 } else { -1 };
1202 (current_pct + delta).clamp(10, 100)
1203}
1204
1205#[cfg(test)]
1208mod tests {
1209 use super::*;
1210 use bevy::ecs::message::Messages;
1211 use bevy::ecs::system::RunSystemOnce;
1212
1213 use crate::player::player_cursor_system;
1214 use bevy::state::app::StatesPlugin;
1215 use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
1216
1217 fn pause_cursor_app() -> (App, Entity) {
1221 let mut app = App::new();
1222 app.add_plugins(StatesPlugin);
1223 app.init_state::<PauseMenuState>();
1224 app.add_message::<SfxRequest>();
1225 app.init_resource::<ButtonInput<KeyCode>>();
1226 app.init_resource::<ButtonInput<MouseButton>>();
1227 app.add_systems(
1228 Update,
1229 (
1230 toggle_pause.run_if(in_state(PauseMenuState::Playing)),
1231 escape_to_resume.run_if(in_state(PauseMenuState::Paused)),
1232 player_cursor_system.run_if(in_state(PauseMenuState::Playing)),
1233 ),
1234 );
1235 app.add_systems(OnEnter(PauseMenuState::Paused), release_cursor);
1236 let window = app
1237 .world_mut()
1238 .spawn((
1239 Window {
1240 focused: true,
1241 ..default()
1242 },
1243 PrimaryWindow,
1244 ))
1245 .id();
1246 (app, window)
1247 }
1248
1249 fn tap(app: &mut App, key: KeyCode) {
1252 app.world_mut()
1253 .resource_mut::<ButtonInput<KeyCode>>()
1254 .press(key);
1255 app.update();
1256 app.world_mut()
1257 .resource_mut::<ButtonInput<KeyCode>>()
1258 .reset_all();
1259 app.update();
1260 }
1261
1262 fn click(app: &mut App) {
1263 app.world_mut()
1264 .resource_mut::<ButtonInput<MouseButton>>()
1265 .press(MouseButton::Left);
1266 app.update();
1267 app.world_mut()
1268 .resource_mut::<ButtonInput<MouseButton>>()
1269 .reset_all();
1270 }
1271
1272 fn pause_state(app: &App) -> PauseMenuState {
1273 app.world()
1274 .resource::<State<PauseMenuState>>()
1275 .get()
1276 .clone()
1277 }
1278
1279 fn grab(app: &App, window: Entity) -> CursorGrabMode {
1280 app.world()
1281 .get::<CursorOptions>(window)
1282 .expect("window should still exist")
1283 .grab_mode
1284 }
1285
1286 #[test]
1287 fn cursor_follows_pause_focus_and_click_with_the_player_cursor_system() {
1288 let (mut app, window) = pause_cursor_app();
1289
1290 tap(&mut app, KeyCode::Escape);
1292 assert_eq!(pause_state(&app), PauseMenuState::Paused);
1293 assert_eq!(grab(&app, window), CursorGrabMode::None);
1294
1295 tap(&mut app, KeyCode::Escape);
1297 assert_eq!(pause_state(&app), PauseMenuState::Playing);
1298 assert_eq!(grab(&app, window), CursorGrabMode::Locked);
1299
1300 app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
1302 app.update();
1303 assert_eq!(grab(&app, window), CursorGrabMode::None);
1304 assert_eq!(pause_state(&app), PauseMenuState::Playing);
1305
1306 app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
1308 app.update();
1309 assert_eq!(grab(&app, window), CursorGrabMode::None);
1310 click(&mut app);
1311 assert_eq!(grab(&app, window), CursorGrabMode::Locked);
1312
1313 tap(&mut app, KeyCode::Escape);
1315 assert_eq!(pause_state(&app), PauseMenuState::Paused);
1316 assert_eq!(grab(&app, window), CursorGrabMode::None);
1317 }
1318
1319 #[test]
1320 fn resuming_does_not_capture_an_unfocused_window() {
1321 let (mut app, window) = pause_cursor_app();
1322 tap(&mut app, KeyCode::Escape);
1323 assert_eq!(pause_state(&app), PauseMenuState::Paused);
1324 app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
1325
1326 app.world_mut()
1327 .resource_mut::<ButtonInput<KeyCode>>()
1328 .press(KeyCode::Escape);
1329 app.update();
1330 assert_eq!(grab(&app, window), CursorGrabMode::None);
1333 app.world_mut()
1334 .resource_mut::<ButtonInput<KeyCode>>()
1335 .reset_all();
1336 app.update();
1337
1338 assert_eq!(pause_state(&app), PauseMenuState::Playing);
1339 assert_eq!(grab(&app, window), CursorGrabMode::None);
1340 }
1341
1342 #[test]
1343 fn pause_cursor_changes_only_touch_the_primary_window() {
1344 let (mut app, window) = pause_cursor_app();
1345 let secondary = app
1346 .world_mut()
1347 .spawn((
1348 Window {
1349 focused: false,
1350 ..default()
1351 },
1352 CursorOptions {
1353 grab_mode: CursorGrabMode::Confined,
1354 ..default()
1355 },
1356 ))
1357 .id();
1358
1359 tap(&mut app, KeyCode::Escape);
1360 tap(&mut app, KeyCode::Escape);
1361
1362 assert_eq!(grab(&app, window), CursorGrabMode::Locked);
1363 assert_eq!(grab(&app, secondary), CursorGrabMode::Confined);
1364 }
1365
1366 #[test]
1367 fn fov_steps_by_five_degrees_within_limits() {
1368 assert_eq!(step_fov_degrees(70.0, true), 75.0);
1369 assert_eq!(step_fov_degrees(70.0, false), 65.0);
1370 assert_eq!(step_fov_degrees(118.0, true), 120.0);
1371 assert_eq!(step_fov_degrees(52.0, false), 50.0);
1372 }
1373
1374 #[test]
1375 fn volume_steps_by_a_tenth_within_limits() {
1376 assert!((step_volume(0.5, true) - 0.6).abs() < 1e-6);
1377 assert!((step_volume(0.5, false) - 0.4).abs() < 1e-6);
1378 assert_eq!(step_volume(0.95, true), 1.0);
1379 assert_eq!(step_volume(0.05, false), 0.0);
1380 }
1381
1382 #[test]
1383 fn render_distance_steps_by_two_chunks_within_limits() {
1384 assert_eq!(step_render_distance_chunks(150.0, true), 12);
1386 assert_eq!(step_render_distance_chunks(150.0, false), 8);
1387 assert_eq!(step_render_distance_chunks(8.0 * 16.0, true), 10);
1388 assert_eq!(step_render_distance_chunks(32.0 * 16.0, true), 32);
1389 assert_eq!(step_render_distance_chunks(4.0 * 16.0, false), 4);
1390 assert_eq!(step_render_distance_chunks(1000.0 * 16.0, false), 30);
1392 }
1393
1394 #[test]
1395 fn sensitivity_steps_by_one_percent_within_limits() {
1396 assert_eq!(step_sensitivity_pct(1.0, false), 99);
1397 assert_eq!(step_sensitivity_pct(1.0, true), 100);
1398 assert_eq!(step_sensitivity_pct(0.5, true), 51);
1399 assert_eq!(step_sensitivity_pct(0.1, false), 10);
1400 }
1401
1402 fn settings_world(pressed: SettingsButton) -> World {
1405 let mut world = World::new();
1406 world.insert_resource(SfxConfig::default());
1407 world.init_resource::<NextState<PauseMenuState>>();
1408 world.init_resource::<Messages<SaveSettingsRequest>>();
1409 world.spawn((
1410 Button,
1411 Interaction::Pressed,
1412 BackgroundColor(Color::NONE),
1413 pressed,
1414 ));
1415 world
1416 }
1417
1418 fn press(world: &mut World) {
1419 world
1420 .run_system_once(handle_settings_buttons)
1421 .expect("handle_settings_buttons should run");
1422 }
1423
1424 #[test]
1425 fn sensitivity_button_updates_config_and_live_players() {
1426 let mut world = settings_world(SettingsButton::SensitivityDec);
1427 world.insert_resource(PlayerConfig::default());
1428 let player = world.spawn(Player::default()).id();
1429 assert_eq!(world.get::<Player>(player).unwrap().sensitivity, 1.0);
1430
1431 press(&mut world);
1432
1433 assert!((world.resource::<PlayerConfig>().sensitivity - 0.99).abs() < 1e-6);
1434 assert!(
1435 (world.get::<Player>(player).unwrap().sensitivity - 0.99).abs() < 1e-6,
1436 "the live player must pick up the new sensitivity without a restart"
1437 );
1438 }
1439
1440 #[test]
1441 fn fov_button_updates_the_camera_and_the_player_config() {
1442 let mut world = settings_world(SettingsButton::FovInc);
1443 world.insert_resource(PlayerConfig {
1444 fov_degrees: 70.0,
1445 ..default()
1446 });
1447 let camera = world
1448 .spawn((
1449 Camera3d::default(),
1450 Projection::Perspective(PerspectiveProjection {
1451 fov: 70.0_f32.to_radians(),
1452 ..default()
1453 }),
1454 ))
1455 .id();
1456
1457 press(&mut world);
1458
1459 let Projection::Perspective(perspective) = world.get::<Projection>(camera).unwrap() else {
1460 panic!("perspective camera");
1461 };
1462 assert!((perspective.fov.to_degrees() - 75.0).abs() < 1e-3);
1463 assert!((world.resource::<PlayerConfig>().fov_degrees - 75.0).abs() < 1e-3);
1464 }
1465
1466 #[test]
1467 fn volume_button_updates_sfx_config() {
1468 let mut world = settings_world(SettingsButton::VolumeDec);
1469 let before = world.resource::<SfxConfig>().volume;
1470
1471 press(&mut world);
1472
1473 let after = world.resource::<SfxConfig>().volume;
1474 assert!((after - (before - 0.1).clamp(0.0, 1.0)).abs() < 1e-6);
1475 }
1476
1477 #[test]
1478 fn back_button_requests_save_and_returns_to_pause() {
1479 let mut world = settings_world(SettingsButton::Back);
1480
1481 press(&mut world);
1482
1483 let saves = world.resource::<Messages<SaveSettingsRequest>>();
1484 assert_eq!(saves.iter_current_update_messages().count(), 1);
1485 assert!(matches!(
1486 *world.resource::<NextState<PauseMenuState>>(),
1487 NextState::Pending(PauseMenuState::Paused)
1488 ));
1489 }
1490
1491 const PRIMARY: ButtonColors = ButtonColors {
1494 normal: Color::srgb(0.10, 0.20, 0.30),
1495 hovered: Color::srgb(0.11, 0.21, 0.31),
1496 pressed: Color::srgb(0.12, 0.22, 0.32),
1497 text: Color::srgb(0.13, 0.23, 0.33),
1498 };
1499 const SECONDARY: ButtonColors = ButtonColors {
1500 normal: Color::srgb(0.40, 0.50, 0.60),
1501 hovered: Color::srgb(0.41, 0.51, 0.61),
1502 pressed: Color::srgb(0.42, 0.52, 0.62),
1503 text: Color::srgb(0.43, 0.53, 0.63),
1504 };
1505
1506 fn custom_theme() -> PauseMenuTheme {
1509 PauseMenuTheme {
1510 overlay: Color::srgba(0.9, 0.1, 0.1, 0.5),
1511 panel: Color::srgb(0.9, 0.9, 0.8),
1512 header: Color::srgb(0.1, 0.9, 0.1),
1513 text: Color::srgb(0.1, 0.1, 0.9),
1514 label: Color::srgb(0.9, 0.1, 0.9),
1515 button: PRIMARY,
1516 secondary_button: SECONDARY,
1517 corner_radius: 9.0,
1518 panel_width: Val::Px(520.0),
1519 panel_padding: UiRect::all(Val::Px(32.0)),
1520 }
1521 }
1522
1523 fn menu_world(theme: Option<PauseMenuTheme>) -> World {
1525 let mut world = World::new();
1526 world.insert_resource(PauseMenuConfig::default());
1527 world.insert_resource(SfxConfig::default());
1528 if let Some(theme) = theme {
1529 world.insert_resource(theme);
1530 }
1531 world
1532 }
1533
1534 fn open_pause_menu(world: &mut World) {
1535 world
1536 .run_system_once(spawn_pause_menu)
1537 .expect("spawn_pause_menu should run");
1538 }
1539
1540 fn open_settings_menu(world: &mut World) {
1541 world
1542 .run_system_once(spawn_settings_menu)
1543 .expect("spawn_settings_menu should run");
1544 }
1545
1546 fn text_color(world: &mut World, content: &str) -> Color {
1548 let mut query = world.query::<(&Text, &TextColor)>();
1549 let found: Vec<Color> = query
1550 .iter(world)
1551 .filter(|(text, _)| text.0 == content)
1552 .map(|(_, color)| color.0)
1553 .collect();
1554 assert_eq!(found.len(), 1, "expected exactly one text {content:?}");
1555 found[0]
1556 }
1557
1558 fn overlay<R: Component>(world: &mut World) -> (Entity, Color) {
1560 let mut query = world.query_filtered::<(Entity, &BackgroundColor), With<R>>();
1561 let (root, bg) = query
1562 .single(world)
1563 .expect("the menu should have exactly one overlay root");
1564 (root, bg.0)
1565 }
1566
1567 fn panel(world: &mut World) -> (Color, Node, Entity) {
1569 let mut query =
1570 world.query_filtered::<(&BackgroundColor, &Node, &ChildOf), With<PauseMenuPanel>>();
1571 let (bg, node, child_of) = query
1572 .single(world)
1573 .expect("the menu should have exactly one panel");
1574 (bg.0, node.clone(), child_of.parent())
1575 }
1576
1577 fn pause_buttons(
1580 world: &mut World,
1581 select: fn(&PauseButton) -> bool,
1582 ) -> Vec<(Color, BorderRadius)> {
1583 let mut query = world.query::<(&PauseButton, &BackgroundColor, &Node)>();
1584 query
1585 .iter(world)
1586 .filter(|(action, _, _)| select(action))
1587 .map(|(_, bg, node)| (bg.0, node.border_radius))
1588 .collect()
1589 }
1590
1591 fn settings_buttons(
1593 world: &mut World,
1594 select: fn(&SettingsButton) -> bool,
1595 ) -> Vec<(Color, BorderRadius)> {
1596 let mut query = world.query::<(&SettingsButton, &BackgroundColor, &Node)>();
1597 query
1598 .iter(world)
1599 .filter(|(action, _, _)| select(action))
1600 .map(|(_, bg, node)| (bg.0, node.border_radius))
1601 .collect()
1602 }
1603
1604 #[test]
1605 fn default_theme_equals_the_previous_constants() {
1606 let buttons = ButtonColors::default();
1607 assert_eq!(buttons.normal, Color::srgb(0.15, 0.15, 0.20));
1608 assert_eq!(buttons.hovered, Color::srgb(0.25, 0.25, 0.35));
1609 assert_eq!(buttons.pressed, Color::srgb(0.35, 0.35, 0.50));
1610 assert_eq!(buttons.text, Color::WHITE);
1611
1612 let theme = PauseMenuTheme::default();
1613 assert_eq!(theme.overlay, Color::srgba(0.0, 0.0, 0.0, 0.78));
1614 assert_eq!(theme.panel, Color::NONE);
1615 assert_eq!(theme.header, Color::WHITE);
1616 assert_eq!(theme.text, Color::WHITE);
1617 assert_eq!(theme.label, Color::srgb(0.8, 0.8, 0.8));
1618 assert_eq!(theme.button, buttons);
1619 assert_eq!(theme.secondary_button, buttons);
1620 assert_eq!(theme.corner_radius, 0.0);
1621 assert_eq!(theme.panel_width, Val::Auto);
1622 assert_eq!(theme.panel_padding, UiRect::ZERO);
1623 }
1624
1625 #[test]
1626 fn button_colors_pick_the_background_for_each_interaction() {
1627 assert_eq!(PRIMARY.background(Interaction::None), PRIMARY.normal);
1628 assert_eq!(PRIMARY.background(Interaction::Hovered), PRIMARY.hovered);
1629 assert_eq!(PRIMARY.background(Interaction::Pressed), PRIMARY.pressed);
1630 }
1631
1632 #[test]
1633 fn pause_menu_without_a_theme_resource_keeps_the_previous_look() {
1634 let mut world = menu_world(None);
1635
1636 open_pause_menu(&mut world);
1637
1638 let (root, overlay_bg) = overlay::<PauseMenuRoot>(&mut world);
1639 assert_eq!(overlay_bg, Color::srgba(0.0, 0.0, 0.0, 0.78));
1640
1641 let (panel_bg, panel_node, panel_parent) = panel(&mut world);
1643 assert_eq!(panel_parent, root);
1644 assert_eq!(panel_bg, Color::NONE);
1645 assert_eq!(panel_node.width, Val::Auto);
1646 assert_eq!(panel_node.padding, UiRect::ZERO);
1647 assert_eq!(panel_node.border_radius, BorderRadius::ZERO);
1648 assert_eq!(panel_node.row_gap, Val::Px(14.0));
1649 assert_eq!(panel_node.flex_direction, FlexDirection::Column);
1650 assert_eq!(panel_node.align_items, AlignItems::Center);
1651
1652 assert_eq!(text_color(&mut world, "PAUSED"), Color::WHITE);
1653 let buttons = pause_buttons(&mut world, |_| true);
1654 assert_eq!(buttons.len(), 3);
1655 for (bg, radius) in buttons {
1656 assert_eq!(bg, Color::srgb(0.15, 0.15, 0.20));
1657 assert_eq!(radius, BorderRadius::ZERO);
1658 }
1659 for label in ["Resume", "Settings", "Quit"] {
1660 assert_eq!(text_color(&mut world, label), Color::WHITE);
1661 }
1662 }
1663
1664 #[test]
1665 fn custom_theme_styles_the_pause_menu() {
1666 let theme = custom_theme();
1667 let mut world = menu_world(Some(theme.clone()));
1668
1669 open_pause_menu(&mut world);
1670
1671 let (root, overlay_bg) = overlay::<PauseMenuRoot>(&mut world);
1672 assert_eq!(overlay_bg, theme.overlay);
1673
1674 let (panel_bg, panel_node, panel_parent) = panel(&mut world);
1675 assert_eq!(panel_parent, root);
1676 assert_eq!(panel_bg, theme.panel);
1677 assert_eq!(panel_node.width, Val::Px(520.0));
1678 assert_eq!(panel_node.padding, UiRect::all(Val::Px(32.0)));
1679 assert_eq!(panel_node.border_radius, BorderRadius::all(Val::Px(9.0)));
1680
1681 assert_eq!(text_color(&mut world, "PAUSED"), theme.header);
1682
1683 let radius = BorderRadius::all(Val::Px(9.0));
1684 assert_eq!(
1685 pause_buttons(&mut world, |b| matches!(b, PauseButton::Resume)),
1686 vec![(PRIMARY.normal, radius)]
1687 );
1688 assert_eq!(
1689 pause_buttons(&mut world, |b| !matches!(b, PauseButton::Resume)),
1690 vec![(SECONDARY.normal, radius); 2]
1691 );
1692 assert_eq!(text_color(&mut world, "Resume"), PRIMARY.text);
1693 assert_eq!(text_color(&mut world, "Settings"), SECONDARY.text);
1694 assert_eq!(text_color(&mut world, "Quit"), SECONDARY.text);
1695 }
1696
1697 #[test]
1698 fn pause_menu_buttons_are_children_of_the_panel() {
1699 let mut world = menu_world(None);
1700
1701 open_pause_menu(&mut world);
1702
1703 let mut panels = world.query_filtered::<Entity, With<PauseMenuPanel>>();
1704 let panel_entity = panels.single(&world).expect("one panel");
1705 let mut buttons = world.query_filtered::<&ChildOf, With<PauseButton>>();
1706 let parents: Vec<Entity> = buttons.iter(&world).map(|c| c.parent()).collect();
1707 assert_eq!(parents, vec![panel_entity; 3]);
1708 }
1709
1710 #[test]
1711 fn settings_menu_without_a_theme_resource_keeps_the_previous_look() {
1712 let mut world = menu_world(None);
1713
1714 open_settings_menu(&mut world);
1715
1716 let (root, overlay_bg) = overlay::<SettingsMenuRoot>(&mut world);
1717 assert_eq!(overlay_bg, Color::srgba(0.0, 0.0, 0.0, 0.78));
1718 let (panel_bg, panel_node, panel_parent) = panel(&mut world);
1719 assert_eq!(panel_parent, root);
1720 assert_eq!(panel_bg, Color::NONE);
1721 assert_eq!(panel_node.width, Val::Auto);
1722 assert_eq!(panel_node.padding, UiRect::ZERO);
1723
1724 assert_eq!(text_color(&mut world, "SETTINGS"), Color::WHITE);
1725 assert_eq!(
1726 text_color(&mut world, "Field of View"),
1727 Color::srgb(0.8, 0.8, 0.8)
1728 );
1729 let mut values = world.query_filtered::<&TextColor, With<FovLabel>>();
1730 assert_eq!(
1731 values.single(&world).expect("one FOV value").0,
1732 Color::WHITE
1733 );
1734 let buttons = settings_buttons(&mut world, |_| true);
1735 assert_eq!(buttons.len(), 9);
1736 for (bg, radius) in buttons {
1737 assert_eq!(bg, Color::srgb(0.15, 0.15, 0.20));
1738 assert_eq!(radius, BorderRadius::ZERO);
1739 }
1740 assert_eq!(text_color(&mut world, "< Back"), Color::WHITE);
1741 }
1742
1743 #[test]
1744 fn custom_theme_styles_the_settings_menu() {
1745 let theme = custom_theme();
1746 let mut world = menu_world(Some(theme.clone()));
1747
1748 open_settings_menu(&mut world);
1749
1750 let (root, overlay_bg) = overlay::<SettingsMenuRoot>(&mut world);
1751 assert_eq!(overlay_bg, theme.overlay);
1752
1753 let (panel_bg, panel_node, panel_parent) = panel(&mut world);
1754 assert_eq!(panel_parent, root);
1755 assert_eq!(panel_bg, theme.panel);
1756 assert_eq!(panel_node.width, Val::Px(520.0));
1757 assert_eq!(panel_node.padding, UiRect::all(Val::Px(32.0)));
1758 assert_eq!(panel_node.border_radius, BorderRadius::all(Val::Px(9.0)));
1759
1760 assert_eq!(text_color(&mut world, "SETTINGS"), theme.header);
1761 for label in [
1762 "Field of View",
1763 "SFX Volume",
1764 "Render Distance",
1765 "Sensitivity",
1766 ] {
1767 assert_eq!(text_color(&mut world, label), theme.label);
1768 }
1769 let mut values = world.query_filtered::<&TextColor, With<FovLabel>>();
1770 assert_eq!(values.single(&world).expect("one FOV value").0, theme.text);
1771
1772 let radius = BorderRadius::all(Val::Px(9.0));
1773 assert_eq!(
1774 settings_buttons(&mut world, |b| matches!(b, SettingsButton::Back)),
1775 vec![(PRIMARY.normal, radius)]
1776 );
1777 assert_eq!(
1778 settings_buttons(&mut world, |b| !matches!(b, SettingsButton::Back)),
1779 vec![(SECONDARY.normal, radius); 8]
1780 );
1781 assert_eq!(text_color(&mut world, "< Back"), PRIMARY.text);
1782 }
1783
1784 fn handler_world(theme: Option<PauseMenuTheme>) -> World {
1786 let mut world = World::new();
1787 world.insert_resource(SfxConfig::default());
1788 world.init_resource::<NextState<PauseMenuState>>();
1789 world.init_resource::<Messages<SaveSettingsRequest>>();
1790 world.init_resource::<Messages<SfxRequest>>();
1791 world.init_resource::<Messages<AppExit>>();
1792 if let Some(theme) = theme {
1793 world.insert_resource(theme);
1794 }
1795 world
1796 }
1797
1798 fn spawn_button<A: Component>(world: &mut World, action: A, state: Interaction) -> Entity {
1801 world
1802 .spawn((Button, state, BackgroundColor(Color::NONE), action))
1803 .id()
1804 }
1805
1806 fn background(world: &World, entity: Entity) -> Color {
1807 world
1808 .get::<BackgroundColor>(entity)
1809 .expect("button should exist")
1810 .0
1811 }
1812
1813 #[test]
1814 fn pause_buttons_take_theme_colors_per_interaction_state() {
1815 let mut world = handler_world(Some(custom_theme()));
1816 let primary_idle = spawn_button(&mut world, PauseButton::Resume, Interaction::None);
1817 let primary_hovered = spawn_button(&mut world, PauseButton::Resume, Interaction::Hovered);
1818 let primary_pressed = spawn_button(&mut world, PauseButton::Resume, Interaction::Pressed);
1819 let secondary_idle = spawn_button(&mut world, PauseButton::Settings, Interaction::None);
1820 let secondary_hovered = spawn_button(&mut world, PauseButton::Quit, Interaction::Hovered);
1821 let secondary_pressed =
1822 spawn_button(&mut world, PauseButton::Settings, Interaction::Pressed);
1823
1824 world
1825 .run_system_once(handle_pause_buttons)
1826 .expect("handle_pause_buttons should run");
1827
1828 assert_eq!(background(&world, primary_idle), PRIMARY.normal);
1829 assert_eq!(background(&world, primary_hovered), PRIMARY.hovered);
1830 assert_eq!(background(&world, primary_pressed), PRIMARY.pressed);
1831 assert_eq!(background(&world, secondary_idle), SECONDARY.normal);
1832 assert_eq!(background(&world, secondary_hovered), SECONDARY.hovered);
1833 assert_eq!(background(&world, secondary_pressed), SECONDARY.pressed);
1834 }
1835
1836 #[test]
1837 fn settings_buttons_take_theme_colors_per_interaction_state() {
1838 let mut world = handler_world(Some(custom_theme()));
1839 let primary_idle = spawn_button(&mut world, SettingsButton::Back, Interaction::None);
1840 let primary_hovered = spawn_button(&mut world, SettingsButton::Back, Interaction::Hovered);
1841 let primary_pressed = spawn_button(&mut world, SettingsButton::Back, Interaction::Pressed);
1842 let secondary_idle = spawn_button(&mut world, SettingsButton::FovInc, Interaction::None);
1843 let secondary_hovered =
1844 spawn_button(&mut world, SettingsButton::VolumeDec, Interaction::Hovered);
1845 let secondary_pressed =
1846 spawn_button(&mut world, SettingsButton::FovDec, Interaction::Pressed);
1847
1848 press(&mut world);
1849
1850 assert_eq!(background(&world, primary_idle), PRIMARY.normal);
1851 assert_eq!(background(&world, primary_hovered), PRIMARY.hovered);
1852 assert_eq!(background(&world, primary_pressed), PRIMARY.pressed);
1853 assert_eq!(background(&world, secondary_idle), SECONDARY.normal);
1854 assert_eq!(background(&world, secondary_hovered), SECONDARY.hovered);
1855 assert_eq!(background(&world, secondary_pressed), SECONDARY.pressed);
1856 }
1857
1858 #[test]
1859 fn buttons_without_a_theme_resource_use_the_previous_colors() {
1860 let mut world = handler_world(None);
1861 let pause_idle = spawn_button(&mut world, PauseButton::Settings, Interaction::None);
1862 let pause_hovered = spawn_button(&mut world, PauseButton::Resume, Interaction::Hovered);
1863 let pause_pressed = spawn_button(&mut world, PauseButton::Settings, Interaction::Pressed);
1864 let settings_idle = spawn_button(&mut world, SettingsButton::Back, Interaction::None);
1865 let settings_hovered =
1866 spawn_button(&mut world, SettingsButton::FovInc, Interaction::Hovered);
1867 let settings_pressed =
1868 spawn_button(&mut world, SettingsButton::FovDec, Interaction::Pressed);
1869
1870 world
1871 .run_system_once(handle_pause_buttons)
1872 .expect("handle_pause_buttons should run");
1873 press(&mut world);
1874
1875 for idle in [pause_idle, settings_idle] {
1876 assert_eq!(background(&world, idle), Color::srgb(0.15, 0.15, 0.20));
1877 }
1878 for hovered in [pause_hovered, settings_hovered] {
1879 assert_eq!(background(&world, hovered), Color::srgb(0.25, 0.25, 0.35));
1880 }
1881 for pressed in [pause_pressed, settings_pressed] {
1882 assert_eq!(background(&world, pressed), Color::srgb(0.35, 0.35, 0.50));
1883 }
1884 }
1885}