upgrade to bevy 0.20

This commit is contained in:
2026-10-20 23:59:48 -05:00
parent 4607f12756
commit 25557d85ce
7 changed files with 1626 additions and 1591 deletions
Generated
+1156 -823
View File
File diff suppressed because it is too large Load Diff
+8 -8
View File
@@ -4,14 +4,14 @@ version = "0.1.0"
edition = "2024"
[dependencies]
app_dirs2 = "2.5.5"
bevy = { version = "0.19", features = ["system_clipboard", "debug"] }
bevy-inspector-egui = "0.37"
derive_more = { version = "2.1.1", features = ["deref", "deref_mut"] }
jiff = { version = "0.2.35", features = ["serde"] }
ron = "0.12.2"
serde = { version = "1.0.229", features = ["derive"] }
xxhash-rust = { version = "0.8.18", features = ["xxh3", "std"] }
app_dirs2 = "2.5"
bevy = { version = "0.20", features = ["system_clipboard", "debug"] }
bevy-inspector-egui = "0.38"
derive_more = { version = "2.1", features = ["deref", "deref_mut"] }
jiff = { version = "0.2", features = ["serde"] }
ron = "0.12"
serde = { version = "1.0", features = ["derive"] }
xxhash-rust = { version = "0.8", features = ["xxh3", "std"] }
[profile.dev]
opt-level = 1
+34 -5
View File
@@ -1,7 +1,11 @@
use bevy::prelude::*;
use bevy_inspector_egui::{bevy_egui::EguiPlugin, quick::ResourceInspectorPlugin};
use crate::lobby::LobbyUiState;
use bevy::prelude::*;
use bevy_inspector_egui::{
bevy_egui::EguiPlugin,
quick::{ResourceInspectorPlugin, WorldInspectorPlugin},
};
// TODO: compile these in only if debug build
/// Whether the debug inspector is currently shown.
#[derive(Resource, Debug, Default)]
@@ -13,20 +17,45 @@ impl Plugin for DebugInspectorPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<InspectorEnabled>()
.add_plugins(EguiPlugin::default())
.add_plugins(WorldInspectorPlugin::new())
.add_plugins(
ResourceInspectorPlugin::<LobbyUiState>::new()
.run_if(|enabled: Res<InspectorEnabled>| enabled.0),
)
.add_systems(Update, toggle_inspector);
.add_systems(Update, (toggle_inspector, toggle_ui_layout_debug));
}
}
fn toggle_inspector(keys: Res<ButtonInput<KeyCode>>, mut enabled: ResMut<InspectorEnabled>) {
if keys.just_pressed(KeyCode::F1) {
if !keys.just_pressed(KeyCode::F1) {
return;
}
enabled.0 = !enabled.0;
info!(
"lobby ui inspector toggled {}",
if enabled.0 { "on" } else { "off" }
);
}
fn toggle_ui_layout_debug(
keys: Res<ButtonInput<KeyCode>>,
mut debug_options: ResMut<GlobalUiDebugOptions>,
) {
if !keys.just_pressed(KeyCode::F2) {
return;
}
if debug_options.enabled {
debug_options.enabled = false;
} else {
debug_options.enabled = true;
debug_options.outline_border_box = true;
debug_options.outline_padding_box = true;
debug_options.outline_content_box = true;
}
info!(
"ui layout debug toggled {}",
if debug_options.enabled { "on" } else { "off" }
);
}
+20 -137
View File
@@ -1,9 +1,8 @@
use crate::main_menu::InteractionColors;
use bevy::{
input::gamepad::GamepadButton,
input_focus::{
InputFocus, InputFocusSystems, InputFocusVisible,
directional_navigation::DirectionalNavigationPlugin, tab_navigation::TabNavigationPlugin,
InputFocusSystems, InputFocusVisible, directional_navigation::DirectionalNavigationPlugin,
tab_navigation::TabNavigationPlugin,
},
math::{CompassOctant, Dir2},
prelude::*,
@@ -46,7 +45,7 @@ impl Plugin for FocusNavigationPlugin {
PreUpdate,
navigate_directionally.in_set(NavigationSystems::Navigate),
)
.add_systems(Update, style_focus_outlines)
// .add_systems(Update, style_focus_outlines)
.add_observer(show_focus_after_activation);
}
}
@@ -106,137 +105,21 @@ fn show_focus_after_activation(_: On<Activate>, mut focus_visible: ResMut<InputF
focus_visible.0 = true;
}
fn style_focus_outlines(
input_focus: Res<InputFocus>,
mut outlines: Query<(Entity, &InteractionColors, &mut BorderColor)>,
) {
let focused_entity = input_focus.get();
// fn style_focus_outlines(
// input_focus: Res<InputFocus>,
// mut outlines: Query<(Entity, &InteractionColors, &mut BorderColor)>,
// ) {
// let focused_entity = input_focus.get();
for (entity, colors, mut border_color) in &mut outlines {
let color = if focused_entity == Some(entity) {
colors.focused_outline
} else {
colors.default_outline
};
let new_border_color = BorderColor::all(color);
if *border_color != new_border_color {
*border_color = new_border_color;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use bevy::{
camera::NormalizedRenderTarget,
input_focus::{
InputFocus, InputFocusPlugin,
directional_navigation::{DirectionalNavigationMap, DirectionalNavigationPlugin},
tab_navigation::TabIndex,
},
picking::{
backend::HitData,
events::{Pointer, Press},
pointer::{Location, PointerButton, PointerId},
},
window::PrimaryWindow,
};
#[test]
fn clicking_the_window_clears_focus_via_tab_navigation_plugin() {
let mut app = App::new();
app.add_plugins((InputFocusPlugin, TabNavigationPlugin));
let field = app.world_mut().spawn(TabIndex(0)).id();
let window = app
.world_mut()
.spawn((Window::default(), PrimaryWindow))
.id();
app.world_mut()
.insert_resource(InputFocus::from_entity(field));
app.update();
app.world_mut().trigger(Pointer::new(
PointerId::Mouse,
Location {
target: NormalizedRenderTarget::None {
width: 0,
height: 0,
},
position: Vec2::ZERO,
},
Press {
button: PointerButton::Primary,
hit: HitData {
camera: Entity::PLACEHOLDER,
depth: 0.0,
position: None,
normal: None,
extra: None,
},
count: 1,
},
window,
));
app.update();
assert_eq!(app.world().resource::<InputFocus>().get(), None);
}
#[test]
fn arrow_key_moves_focus_with_directional_navigation() {
let mut app = App::new();
app.add_plugins(DirectionalNavigationPlugin);
let current = app.world_mut().spawn_empty().id();
let next = app.world_mut().spawn_empty().id();
app.world_mut()
.insert_resource(InputFocus::from_entity(current));
app.world_mut().insert_resource(InputFocusVisible(false));
app.world_mut().init_resource::<NavigationInputState>();
app.world_mut().init_resource::<ButtonInput<KeyCode>>();
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.press(KeyCode::ArrowRight);
app.world_mut()
.resource_mut::<DirectionalNavigationMap>()
.add_edge(current, next, CompassOctant::East);
app.add_systems(PreUpdate, navigate_directionally);
app.update();
assert_eq!(app.world().resource::<InputFocus>().get(), Some(next));
assert!(app.world().resource::<InputFocusVisible>().0);
}
#[test]
fn white_outline_tracks_focus_not_hover() {
let mut app = App::new();
let colors = InteractionColors::DEFAULT;
let focused = app
.world_mut()
.spawn((colors.clone(), BorderColor::all(colors.default_outline)))
.id();
let hovered = app
.world_mut()
.spawn((
colors.clone(),
BorderColor::all(colors.default_outline),
Interaction::Hovered,
))
.id();
app.world_mut()
.insert_resource(InputFocus::from_entity(focused));
app.add_systems(Update, style_focus_outlines);
app.update();
assert_eq!(
app.world().get::<BorderColor>(focused).unwrap(),
&BorderColor::all(Color::WHITE)
);
assert_eq!(
app.world().get::<BorderColor>(hovered).unwrap(),
&BorderColor::all(Color::BLACK)
);
}
}
// for (entity, colors, mut border_color) in &mut outlines {
// let color = if focused_entity == Some(entity) {
// colors.focused_outline
// } else {
// colors.default_outline
// };
// let new_border_color = BorderColor::all(color);
// if *border_color != new_border_color {
// *border_color = new_border_color;
// }
// }
// }
+60 -197
View File
@@ -4,10 +4,11 @@ use bevy::{
AutoFocus, InputFocus,
tab_navigation::{TabGroup, TabIndex},
},
picking::hover::Hovered,
prelude::*,
text::{EditableText, EditableTextFilter, TextCursorStyle},
ui::{Checked, auto_directional_navigation::AutoDirectionalNavigation},
ui_widgets::{Activate, Button, RadioButton, RadioGroup, ValueChange},
ui::{Checked, Pressed, auto_directional_navigation::AutoDirectionalNavigation},
ui_widgets::{Activate, Button, RadioButton, RadioGroup, TextInput, ValueChange},
};
use crate::AppState;
@@ -130,7 +131,6 @@ fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRo
}
BackgroundColor(PANEL_BACKGROUND)
Children [
(
Text("Server Settings")
Node {
align_self: AlignSelf::Center,
@@ -140,8 +140,7 @@ fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRo
}
TextColor(TEXT_COLOR)
TextShadow
),
(
--
Text("Session Visibility")
Node {
margin: UiRect::top(px(24)),
@@ -150,8 +149,7 @@ fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRo
font_size: px(38.),
}
TextColor(TEXT_COLOR)
),
(
--
RadioGroup
AutoFocus
AutoDirectionalNavigation::default()
@@ -163,31 +161,31 @@ fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRo
}
TabIndex(0)
Children [
privacy_option(
@privacy_option(
"Public",
LobbyPrivacy::Public,
BorderRadius::px(16., 0., 0., 16.),
),
privacy_option("Friends Only", LobbyPrivacy::FriendsOnly, BorderRadius::ZERO),
privacy_option(
)
--
@privacy_option("Friends Only", LobbyPrivacy::FriendsOnly, BorderRadius::ZERO)
--
@privacy_option(
"Invite Only",
LobbyPrivacy::InviteOnly,
BorderRadius::px(0., 16., 16., 0.),
),
)
]
),
(
field_label("Port")
),
(
--
@field_label("Port")
--
Node {
flex_direction: FlexDirection::Row,
column_gap: px(12),
align_items: AlignItems::Center,
}
Children [
port_field(),
(
@port_field()
--
Button
ResetPortButton
AutoDirectionalNavigation::default()
@@ -202,31 +200,30 @@ fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRo
}
BorderColor::from(Color::BLACK)
InteractionColors::DEFAULT
Interaction
Children [(
Hovered
Children [
Text("Reset")
TextFont {
font_size: px(66.),
}
TextColor(TEXT_COLOR)
TextShadow
)]
]
on(|_event: On<Activate>, mut fields: Query<&mut EditableText, With<PortField>>| {
if let Ok(mut field) = fields.single_mut() {
field.editor_mut().set_text("5599");
}
})
),
]
),
(field_label("Password")),
(password_field()),
(
--
@field_label("Password")
--
@password_field()
--
Node {
flex_grow: 1.,
}
),
(
--
Button
Node {
width: px(600),
@@ -238,14 +235,14 @@ fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRo
}
BorderColor::from(Color::BLACK)
InteractionColors::GOOD
Interaction
Hovered
AutoDirectionalNavigation::default()
TabIndex(4)
on(|_event: On<Activate>, mut lobby: ResMut<LobbyUiState>| {
info!("Session clicked!");
lobby.session_active = !lobby.session_active;
})
Children [(
Children [
Text("Start Session")
SessionStatusLabel
TextFont {
@@ -253,8 +250,7 @@ fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRo
}
TextColor(TEXT_COLOR)
TextShadow
)]
),
]
]
});
@@ -269,7 +265,6 @@ fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRo
}
BackgroundColor(PANEL_BACKGROUND)
Children [
(
Text("Connected Players")
Node {
align_self: AlignSelf::Center,
@@ -279,11 +274,14 @@ fn build_lobby_ui(mut commands: Commands, root_ui: Single<Entity, With<LobbyUiRo
}
TextColor(TEXT_COLOR)
TextShadow
),
player_row("Joe (you)"),
player_row("Alex"),
player_row("Sam"),
player_row("Taylor"),
--
@player_row("Joe (you)")
--
@player_row("Alex")
--
@player_row("Sam")
--
@player_row("Taylor")
]
});
}
@@ -311,6 +309,8 @@ fn port_field() -> impl Scene {
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
InteractionColors::DEFAULT
TextInput
EditableText::new("5599")
EditableText {
cursor_width: 0.05,
@@ -339,6 +339,8 @@ fn password_field() -> impl Scene {
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
InteractionColors::DEFAULT
TextInput
EditableText {
cursor_width: 0.05,
max_characters: Option::Some(32),
@@ -370,22 +372,19 @@ fn player_row(name: &'static str) -> impl Scene {
}
BackgroundColor(OPTION_BACKGROUND)
Children [
(
Node {
width: px(96),
height: px(96),
border_radius: BorderRadius::MAX,
}
BackgroundColor(OPTION_SELECTED_BACKGROUND)
),
(
--
Text(name)
TextFont {
font_size: px(50.),
}
TextColor(TEXT_COLOR)
TextShadow
),
]
}
}
@@ -414,6 +413,7 @@ fn session_visuals(
return;
};
// Set color to danger if on stop session
let new_text = match lobby_ui.session_active {
true => "Stop Session",
false => "Start Session",
@@ -429,7 +429,7 @@ fn privacy_option(
bsn! {
RadioButton
LobbyPrivacyOption(privacy)
Interaction
Hovered
Node {
display: Display::Flex,
flex_grow: 1.,
@@ -440,13 +440,13 @@ fn privacy_option(
}
BorderColor::all(OPTION_BORDER_COLOR)
BackgroundColor(OPTION_BACKGROUND)
Children [(
Children [
Text(label)
TextFont {
font_size: px(38.0),
}
TextColor(OPTION_TEXT_COLOR)
)]
]
}
}
@@ -454,13 +454,13 @@ fn privacy_option(
fn update_privacy_controls(
lobby_ui: Res<LobbyUiState>,
mut commands: Commands,
options: Query<(Entity, &LobbyPrivacyOption, &Interaction, Has<Checked>), With<RadioButton>>,
options: Query<(Entity, &LobbyPrivacyOption, &Hovered, Has<Checked>), With<RadioButton>>,
) {
if !lobby_ui.is_changed() {
return;
}
for (entity, option, interaction, checked) in &options {
for (entity, option, hovered, checked) in &options {
let should_be_checked = option.0 == lobby_ui.privacy;
if should_be_checked && !checked {
commands.entity(entity).insert(Checked);
@@ -468,8 +468,8 @@ fn update_privacy_controls(
commands
.entity(entity)
.remove::<Checked>()
// Reinserting the interaction will trigger the visual redraw
.insert(*interaction);
// Reinserting hovered will trigger the visual redraw
.insert(*hovered);
}
}
}
@@ -488,31 +488,29 @@ fn on_privacy_changed(
/// Styles the UI options according to their interactions.
fn style_privacy_options(
mut options: Query<
(&Interaction, Has<Checked>, &mut BackgroundColor),
(&Hovered, Has<Pressed>, Has<Checked>, &mut BackgroundColor),
(
With<LobbyPrivacyOption>,
Or<(Changed<Interaction>, Changed<Checked>)>,
Or<(Changed<Hovered>, Changed<Checked>)>,
),
>,
) {
for (interaction, checked, mut bg) in options.iter_mut() {
bg.0 = match (checked, *interaction) {
for (hovered, pressed, checked, mut bg) in options.iter_mut() {
bg.0 = match (checked, pressed, hovered.get()) {
// Hovering a selected radio is a no-op (pressing it changes
// nothing), so it keeps its selected color; pressing it darkens.
(true, Interaction::Pressed) => OPTION_SELECTED_PRESSED_BACKGROUND,
(true, _) => OPTION_SELECTED_BACKGROUND,
(false, Interaction::Hovered) => OPTION_HOVERED_BACKGROUND,
(false, _) => OPTION_BACKGROUND,
(true, true, _) => OPTION_SELECTED_PRESSED_BACKGROUND,
(true, _, _) => OPTION_SELECTED_BACKGROUND,
(false, true, _) => OPTION_SELECTED_PRESSED_BACKGROUND, // TODO: <<<< this is not right
(false, false, true) => OPTION_HOVERED_BACKGROUND,
(false, false, false) => OPTION_BACKGROUND,
};
}
}
fn style_lobby_focus(
input_focus: Res<InputFocus>,
mut options: Query<
(&ChildOf, &mut BorderColor),
(With<LobbyPrivacyOption>, Without<InteractionColors>),
>,
mut options: Query<(&ChildOf, &mut BorderColor), With<LobbyPrivacyOption>>,
) {
let focused_entity = input_focus.get();
@@ -528,138 +526,3 @@ fn style_lobby_focus(
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn option(privacy: LobbyPrivacy) -> impl Bundle {
(
RadioButton,
LobbyPrivacyOption(privacy),
BackgroundColor(OPTION_BACKGROUND),
)
}
#[test]
fn autofocus_claims_initial_lobby_focus() {
let mut world = World::new();
world.insert_resource(InputFocus::default());
let radio_group = world.spawn((RadioGroup, AutoFocus)).id();
assert_eq!(world.resource::<InputFocus>().get(), Some(radio_group));
}
#[test]
fn checked_option_is_styled() {
let mut world = World::new();
world.insert_resource(LobbyUiState::default());
let checked = world
.spawn((
option(LobbyPrivacy::Public),
Interaction::default(),
Checked,
))
.id();
let unchecked = world
.spawn((option(LobbyPrivacy::FriendsOnly), Interaction::default()))
.id();
// Regression: without `Interaction` the style system can never match the
// option, so the background stays at the spawn-time color.
let missing_interaction = world.spawn(option(LobbyPrivacy::Public)).id();
let mut schedule = Schedule::default();
schedule.add_systems((update_privacy_controls, style_privacy_options).chain());
schedule.run(&mut world);
let checked_bg = *world.get::<BackgroundColor>(checked).unwrap();
assert_eq!(
checked_bg.0, OPTION_SELECTED_BACKGROUND,
"checked option must be restyled"
);
let unchecked_bg = *world.get::<BackgroundColor>(unchecked).unwrap();
assert_eq!(
unchecked_bg.0, OPTION_BACKGROUND,
"unchecked option must keep its base color"
);
let untouched_bg = *world.get::<BackgroundColor>(missing_interaction).unwrap();
assert_eq!(
untouched_bg.0, OPTION_BACKGROUND,
"option without Interaction is never styled"
);
}
#[test]
fn selected_option_interactions() {
let mut world = World::new();
world.insert_resource(LobbyUiState::default());
let hovered = world
.spawn((option(LobbyPrivacy::Public), Interaction::Hovered, Checked))
.id();
let pressed = world
.spawn((option(LobbyPrivacy::Public), Interaction::Pressed, Checked))
.id();
let mut schedule = Schedule::default();
schedule.add_systems(style_privacy_options);
schedule.run(&mut world);
assert_eq!(
world.get::<BackgroundColor>(hovered).unwrap().0,
OPTION_SELECTED_BACKGROUND,
"selected option must not change on hover"
);
assert_eq!(
world.get::<BackgroundColor>(pressed).unwrap().0,
OPTION_SELECTED_PRESSED_BACKGROUND,
"selected option must darken when pressed"
);
}
#[test]
fn deselected_option_is_restyled() {
let mut world = World::new();
world.insert_resource(LobbyUiState::default());
let first = world
.spawn((
option(LobbyPrivacy::Public),
Interaction::default(),
Checked,
))
.id();
let second = world
.spawn((option(LobbyPrivacy::FriendsOnly), Interaction::default()))
.id();
let mut schedule = Schedule::default();
schedule.add_systems((update_privacy_controls, style_privacy_options).chain());
schedule.run(&mut world);
assert_eq!(
world.get::<BackgroundColor>(first).unwrap().0,
OPTION_SELECTED_BACKGROUND,
"first option must be styled as checked"
);
// Selecting the other option moves the resource; `sync_privacy_options`
// must then move `Checked` and the style system must react to the move.
world.resource_mut::<LobbyUiState>().privacy = LobbyPrivacy::FriendsOnly;
schedule.run(&mut world);
assert_eq!(
world.get::<BackgroundColor>(first).unwrap().0,
OPTION_BACKGROUND,
"deselected option must be restyled to base color"
);
assert_eq!(
world.get::<BackgroundColor>(second).unwrap().0,
OPTION_SELECTED_BACKGROUND,
"newly checked option must be styled as checked"
);
}
}
+2 -3
View File
@@ -1,10 +1,9 @@
use crate::focus_navigation::FocusNavigationPlugin;
use crate::{debug::DebugInspectorPlugin, lobby::LobbyPlugin, save::SavePlugin};
use bevy::{camera::ScalingMode, color::palettes::css::GREEN, prelude::*};
use main_menu::MainMenuPlugin;
use networking::NetworkingPlugin;
use crate::focus_navigation::FocusNavigationPlugin;
use crate::{debug::DebugInspectorPlugin, lobby::LobbyPlugin, save::SavePlugin};
mod debug;
mod focus_navigation;
mod lobby;
+107 -179
View File
@@ -7,9 +7,11 @@ use bevy::input_focus::{
AutoFocus, FocusCause, InputFocus, InputFocusVisible,
tab_navigation::{TabGroup, TabIndex},
};
use bevy::picking::hover::Hovered;
use bevy::text::{EditableText, EditableTextFilter, TextCursorStyle};
use bevy::ui::Pressed;
use bevy::ui::auto_directional_navigation::AutoDirectionalNavigation;
use bevy::ui_widgets::Button;
use bevy::ui_widgets::{Button, TextInput};
use bevy::{prelude::*, ui_widgets::Activate};
use derive_more::{Deref, DerefMut};
@@ -19,7 +21,6 @@ impl Plugin for MainMenuPlugin {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(AppState::Menu), setup_menu)
.add_systems(OnExit(AppState::Menu), cleanup_menu)
// .add_systems(Startup, enable_ui_debug)
.add_systems(Update, (menu_redraw).run_if(in_state(AppState::Menu)))
.add_observer(button_activate_observer)
.add_systems(Update, (scale_ui, style_ui_elements))
@@ -45,15 +46,15 @@ struct Selected;
/// Defines colors that a UI object should turn when interactions occur.
#[derive(Component, Clone, PartialEq, Default, Debug)]
pub(crate) struct InteractionColors {
default: Color,
hovered: Color,
pressed: Color,
selected: Color,
selected_hovered: Color,
selected_pressed: Color,
pub(crate) default_outline: Color,
pub(crate) focused_outline: Color,
pub struct InteractionColors {
pub default: Color,
pub hovered: Color,
pub pressed: Color,
pub selected: Color,
pub selected_hovered: Color,
pub selected_pressed: Color,
pub default_outline: Color,
pub focused_outline: Color,
}
impl InteractionColors {
pub const DEFAULT: InteractionColors = InteractionColors {
@@ -122,25 +123,27 @@ impl MenuLayer {
fn render(&self, layer: usize, menu_root: Entity) -> Box<dyn Scene> {
match self {
MenuLayer::Root => Box::new(bsn! {
menu_layer(layer)
@menu_layer(layer)
ChildOf(menu_root)
Children [
menu_button("Play", Some(MenuLayer::Play)),
menu_button("Settings", Some(MenuLayer::Settings)),
(
menu_button("Quit", None)
@menu_button("Play", Some(MenuLayer::Play))
--
@menu_button("Settings", Some(MenuLayer::Settings))
--
@menu_button("Quit", None)
on(|_event: On<Activate>, mut exit: MessageWriter<AppExit>| { exit.write(AppExit::Success); } )
InteractionColors::DANGER
),
]
}),
MenuLayer::Play => Box::new(bsn! {
menu_layer(layer)
@menu_layer(layer)
ChildOf(menu_root)
Children [
menu_button("Load Save", Some(MenuLayer::LoadSave)),
menu_button("Browse Games", Some(MenuLayer::Browse)),
menu_button("Direct Connect", Some(MenuLayer::DirectConnect)),
@menu_button("Load Save", Some(MenuLayer::LoadSave))
--
@menu_button("Browse Games", Some(MenuLayer::Browse))
--
@menu_button("Direct Connect", Some(MenuLayer::DirectConnect))
]
}),
MenuLayer::LoadSave => {
@@ -155,40 +158,39 @@ impl MenuLayer {
// TODO: get rid of row gap when many saves are present.
Box::new(bsn! {
menu_layer(layer)
@menu_layer(layer)
ChildOf(menu_root)
Children [
{entries},
(
menu_button("New Game", Some(MenuLayer::NewGame))
{entries}
--
@menu_button("New Game", Some(MenuLayer::NewGame))
InteractionColors::GOOD
),
]
})
}
MenuLayer::NewGame => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
{new_game_menu()}
]
}),
MenuLayer::GameInfo(game) => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
{game_info_menu(game)}
]
}),
MenuLayer::Browse => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
menu_button("Game 1", None)
@menu_button("Game 1", None)
]
}),
MenuLayer::DirectConnect => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
// TODO: have IP addr text box here
@@ -196,22 +198,23 @@ impl MenuLayer {
]
}),
MenuLayer::Settings => Box::new(bsn! {
menu_layer(layer)
@menu_layer(layer)
ChildOf(menu_root)
Children [
menu_button("Controls", Some(MenuLayer::Controls)),
menu_button("Graphics", Some(MenuLayer::Graphics)),
@menu_button("Controls", Some(MenuLayer::Controls))
--
@menu_button("Graphics", Some(MenuLayer::Graphics))
]
}),
MenuLayer::Controls => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
Text("Controls..")
]
}),
MenuLayer::Graphics => Box::new(bsn! {
full_menu_layer(layer)
@full_menu_layer(layer)
ChildOf(menu_root)
Children [
Text("Graphics..")
@@ -228,13 +231,6 @@ struct LastMenu(Vec<MenuLayer>);
#[derive(Resource, Debug, Clone, PartialEq, Eq, Hash, Deref, DerefMut)]
struct CurrentMenu(Vec<MenuLayer>);
// fn enable_ui_debug(mut debug_options: ResMut<GlobalUiDebugOptions>) {
// debug_options.enabled = true;
// debug_options.outline_border_box = true;
// debug_options.outline_padding_box = true;
// debug_options.outline_content_box = true;
// }
fn setup_menu(mut commands: Commands) {
commands.insert_resource(CurrentMenu(vec![MenuLayer::Root]));
commands.insert_resource(LastMenu(vec![]));
@@ -297,8 +293,7 @@ fn menu_redraw(
}
fn new_game_menu() -> impl SceneList {
bsn_list![
(
bsn_list! {
Text("New Game")
Node {
align_self: AlignSelf::Center,
@@ -309,8 +304,7 @@ fn new_game_menu() -> impl SceneList {
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
),
(
--
Text("Save Name")
Node {
margin: UiRect::axes(px(12), px(0)),
@@ -321,8 +315,7 @@ fn new_game_menu() -> impl SceneList {
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
),
(
--
#NewGameTextField
GameNameTextField
Node {
@@ -331,6 +324,8 @@ fn new_game_menu() -> impl SceneList {
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
InteractionColors::DEFAULT
TextInput
EditableText {
cursor_width: 0.05,
max_characters: Option::Some(14),
@@ -347,13 +342,12 @@ fn new_game_menu() -> impl SceneList {
AutoFocus
TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
),
(
--
Node {
margin: UiRect::top(px(48)),
}
Children [
menu_button("Create", None)
@menu_button("Create", None)
InteractionColors::GOOD
Node {
margin: UiRect::left(Val::Auto),
@@ -365,14 +359,12 @@ fn new_game_menu() -> impl SceneList {
// TODO: refresh listing
})
]
),
]
}
}
fn game_info_menu(name: impl Into<String>) -> impl SceneList {
let name = name.into();
bsn_list![
(
bsn_list! {
#GameInfoTitle
Text("Load Save")
Node {
@@ -384,8 +376,7 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
),
(
--
Text("Save Name")
Node {
margin: UiRect::axes(px(12), px(0)),
@@ -396,8 +387,7 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
),
(
--
#SaveNameTextField
GameNameTextField
Node {
@@ -406,6 +396,8 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
border_radius: BorderRadius::all(px(12)),
}
BorderColor::from(SLATE_900)
InteractionColors::DEFAULT
TextInput
EditableText::new(name)
EditableText {
cursor_width: 0.05,
@@ -423,14 +415,12 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
AutoFocus
TabIndex(0)
BackgroundColor(Color::srgb(0.48, 0.84, 0.87))
),
(
--
Node {
margin: UiRect::top(px(48)),
}
Children [
(
menu_button("Delete", None)
@menu_button("Delete", None)
InteractionColors::DANGER
Node {
margin: UiRect::right(Val::Auto),
@@ -441,10 +431,9 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
delete_game_save(value.to_string()).unwrap();
// TODO: refresh listing
})
),
(
--
// TODO: when the user changed the name of the game, change this to a "rename" button
menu_button("Play", None)
@menu_button("Play", None)
InteractionColors::GOOD
Node {
margin: UiRect::left(Val::Auto),
@@ -459,10 +448,8 @@ fn game_info_menu(name: impl Into<String>) -> impl SceneList {
// TODO: refresh listing
})
),
]
),
]
}
}
fn menu_layer(layer: usize) -> impl Scene {
@@ -500,6 +487,14 @@ fn full_menu_layer(layer: usize) -> impl Scene {
fn menu_button(label: impl Into<String>, next_layer: Option<MenuLayer>) -> Box<dyn Scene> {
let label = label.into();
let next_layer: Box<dyn Scene> = if let Some(next_layer) = next_layer {
Box::new(bsn! {
NextLayer(next_layer)
})
} else {
Box::new(bsn! {})
};
Box::new(bsn! {
Button
AutoDirectionalNavigation::default()
@@ -513,11 +508,12 @@ fn menu_button(label: impl Into<String>, next_layer: Option<MenuLayer>) -> Box<d
align_items: AlignItems::Center,
margin: UiRect::all(px(4)),
}
{next_layer.map(|l| template_value(NextLayer(l)))}
@next_layer
BorderColor::from(Color::BLACK)
InteractionColors::DEFAULT
Interaction
Children [(
// TODO: add interaction component here if neccesary
Hovered
Children [
Text(label)
TextFont {
// font: FontSourceTemplate::Handle("fonts/FiraSans-Bold.ttf"),
@@ -525,7 +521,7 @@ fn menu_button(label: impl Into<String>, next_layer: Option<MenuLayer>) -> Box<d
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
TextShadow
)]
]
})
}
@@ -555,7 +551,7 @@ fn button_activate_observer(
// push next layer
menu.push(next_layer.0.clone());
for (entity, selected) in q_selected.iter_many(layer_entries) {
for (entity, selected) in q_selected.iter_many(layer_entries).matched() {
if entity == event.entity {
if !selected {
commands.entity(entity).insert(Selected);
@@ -570,30 +566,52 @@ fn button_activate_observer(
/// Styles the UI elements according to their [`InteractionColors`].
fn style_ui_elements(
input_focus: Res<InputFocus>,
mut elements: Query<(
mut q_elements: Query<
(
Entity,
&Interaction,
&mut BackgroundColor,
Option<&Hovered>,
Has<Pressed>,
Option<&mut BackgroundColor>,
Option<&mut BorderColor>,
&InteractionColors,
Has<Selected>,
)>,
),
Or<(With<BackgroundColor>, With<BorderColor>)>,
>,
) {
let focused_entity = input_focus.get();
for (entity, interaction, mut bg, colors, selected) in &mut elements {
let new_color = match (selected, *interaction) {
(true, Interaction::Pressed) => colors.selected_pressed,
(true, Interaction::Hovered) => colors.selected_hovered,
(true, Interaction::None) => colors.selected,
(false, Interaction::Pressed) => colors.pressed,
(false, Interaction::Hovered) => colors.hovered,
(false, Interaction::None) if focused_entity == Some(entity) => colors.hovered,
(false, Interaction::None) => colors.default,
for (entity, hovered, pressed, bg, border, colors, selected) in &mut q_elements {
let is_focused = focused_entity == Some(entity);
// if the entity is focused, its similar to it being hovered.
let hovered = hovered.is_some_and(|h| h.get()) || is_focused;
let new_color = match (selected, pressed, hovered) {
(true, true, _) => colors.selected_pressed,
(true, false, true) => colors.selected_hovered,
(true, false, false) => colors.selected,
(false, true, _) => colors.pressed,
(false, false, true) => colors.hovered,
(false, false, false) => colors.default,
};
if let Some(mut border) = border {
if is_focused {
if border.top != colors.focused_outline {
border.set_all(colors.focused_outline);
}
} else {
if border.top != colors.default_outline {
border.set_all(colors.default_outline);
}
}
}
if let Some(mut bg) = bg {
if bg.0 != new_color {
bg.0 = new_color;
}
}
}
}
fn scale_ui(mut ui_scale: ResMut<UiScale>, window: Single<&Window>) {
@@ -602,6 +620,7 @@ fn scale_ui(mut ui_scale: ResMut<UiScale>, window: Single<&Window>) {
ui_scale.0 = scale_factor;
}
// TODO: generify the inputing of the nav inputs that are in here
fn focus_rightmost_layer_on_navigation(
keyboard: Res<ButtonInput<KeyCode>>,
gamepads: Query<&Gamepad>,
@@ -671,94 +690,3 @@ fn first_focusable_in_layer(
.iter()
.find_map(|child| first_focusable_in_layer(child, children, focusable_entities))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::focus_navigation::navigate_directionally;
use bevy::{
input_focus::directional_navigation::{
DirectionalNavigationMap, DirectionalNavigationPlugin,
},
math::CompassOctant,
};
#[test]
fn focus_uses_hover_color_while_selected_keeps_selected_color() {
let mut app = App::new();
let colors = InteractionColors::DEFAULT;
let focused = app
.world_mut()
.spawn((
Interaction::None,
BackgroundColor(colors.default),
colors.clone(),
))
.id();
let selected = app
.world_mut()
.spawn((
Interaction::None,
BackgroundColor(colors.default),
colors.clone(),
Selected,
))
.id();
app.world_mut()
.insert_resource(InputFocus::from_entity(focused));
app.add_systems(Update, style_ui_elements);
app.update();
assert_eq!(
app.world().get::<BackgroundColor>(focused).unwrap().0,
colors.hovered
);
assert_eq!(
app.world().get::<BackgroundColor>(selected).unwrap().0,
colors.selected
);
}
#[test]
fn first_directional_input_only_focuses_first_item_in_rightmost_layer() {
let mut app = App::new();
app.add_plugins(DirectionalNavigationPlugin);
let left_layer = app.world_mut().spawn(Layer(0)).id();
app.world_mut()
.spawn((AutoDirectionalNavigation::default(), ChildOf(left_layer)));
let right_layer = app.world_mut().spawn(Layer(1)).id();
let first_right_item = app
.world_mut()
.spawn((AutoDirectionalNavigation::default(), ChildOf(right_layer)))
.id();
let next_right_item = app
.world_mut()
.spawn((AutoDirectionalNavigation::default(), ChildOf(right_layer)))
.id();
app.world_mut().insert_resource(InputFocus::default());
app.world_mut().insert_resource(InputFocusVisible(false));
app.world_mut().init_resource::<NavigationInputState>();
app.world_mut().init_resource::<ButtonInput<KeyCode>>();
app.world_mut()
.resource_mut::<ButtonInput<KeyCode>>()
.press(KeyCode::ArrowRight);
app.world_mut()
.resource_mut::<DirectionalNavigationMap>()
.add_edge(first_right_item, next_right_item, CompassOctant::East);
app.add_systems(
PreUpdate,
(focus_rightmost_layer_on_navigation, navigate_directionally).chain(),
);
app.update();
assert_eq!(
app.world().resource::<InputFocus>().get(),
Some(first_right_item)
);
assert!(app.world().resource::<InputFocusVisible>().0);
}
}