Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -912,6 +912,7 @@ wasm = true
name = "2d_shapes"
path = "examples/2d/2d_shapes.rs"
doc-scrape-examples = true
required-features = ["bevy_feathers"]

[package.metadata.example.2d_shapes]
name = "2D Shapes"
Expand Down
108 changes: 78 additions & 30 deletions examples/2d/2d_shapes.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//! Here we use shape primitives to build meshes in a 2D rendering context, making each mesh a certain color by giving that mesh's entity a material based off a [`Color`].
//!
//! Meshes are better known for their use in 3D rendering, but we can use them in a 2D context too. Without a third dimension, the meshes we're building are flat – like paper on a table. These are still very useful for "vector-style" graphics, picking behavior, or as a foundation to build off of for where to apply a shader.
//!
//! A "shape definition" is not a mesh on its own. A circle can be defined with a radius, i.e. [`Circle::new(50.0)`][Circle::new], but rendering tends to happen with meshes built out of triangles. So we need to turn shape descriptions into meshes.
Expand All @@ -10,33 +9,55 @@
//!
//! Both the mesh and material need to be wrapped in their own "newtypes". The mesh and material are currently [`Handle<Mesh>`] and [`Handle<ColorMaterial>`] at the moment, which are not components. Handles are put behind "newtypes" to prevent ambiguity, as some entities might want to have handles to meshes (or images, or materials etc.) for different purposes! All we need to do to make them rendering-relevant components is wrap the mesh handle and the material handle in [`Mesh2d`] and [`MeshMaterial2d`] respectively.
//!
//! You can toggle wireframes with the space bar except on wasm. Wasm does not support
//! You can toggle wireframes with a Feathers checkbox except on wasm. Wasm does not support
//! `POLYGON_MODE_LINE` on the gpu.

use bevy::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
use bevy::sprite_render::{Wireframe2dConfig, Wireframe2dPlugin};
use bevy::{
input::common_conditions::input_just_pressed,
sprite_render::{Wireframe2dConfig, Wireframe2dPlugin},
feathers::{controls::FeathersCheckbox, theme::UiTheme, FeathersPlugins},
ui_widgets::{checkbox_self_update, ValueChange},
};
use bevy::{input::common_conditions::input_toggle_active, prelude::*};
use checkbox::feathers_option_checkbox;
use scene::{bottom_left_scene, top_left_scene};

#[path = "../helpers/checkbox.rs"]
mod checkbox;

#[path = "../helpers/theme.rs"]
mod theme;

#[path = "../helpers/scene.rs"]
mod scene;

/// Various settings for the demo.
#[derive(Resource, Default)]
struct AppStatus {
rotation: bool,
}

#[derive(Clone, Copy, Component, Debug, Default, PartialEq)]
enum CheckboxInput {
#[default]
Rotation,
Wireframe,
}

fn main() {
let mut app = App::new();
app.add_plugins((
DefaultPlugins,
FeathersPlugins,
#[cfg(not(target_arch = "wasm32"))]
Wireframe2dPlugin::default(),
))
.init_resource::<AppStatus>()
.add_systems(Startup, setup);
#[cfg(not(target_arch = "wasm32"))]
app.add_systems(
Update,
toggle_wireframe.run_if(input_just_pressed(KeyCode::Space)),
);
app.add_systems(
Update,
rotate.run_if(input_toggle_active(false, KeyCode::KeyR)),
);
app.insert_resource(UiTheme(theme::basic_example_theme(Color::WHITE)));
app.add_observer(handle_value_change_checkbox);
app.add_systems(Update, rotate.run_if(rotate_checkbox_checked));
app.add_observer(checkbox_self_update);
app.run();
}

Expand Down Expand Up @@ -142,25 +163,52 @@ fn setup(
),
));
}
spawn_buttons(&mut commands);
}

let mut text = "Press 'R' to pause/resume rotation".to_string();
#[cfg(not(target_arch = "wasm32"))]
text.push_str("\nPress 'Space' to toggle wireframes");

commands.spawn((
Text::new(text),
Node {
position_type: PositionType::Absolute,
top: px(12),
left: px(12),
..default()
},
));
/// Spawns the checkboxes in the bottom left corner of the screen.
fn spawn_buttons(commands: &mut Commands) {
if !cfg!(target_arch = "wasm32") {
commands.spawn_scene(bsn! {
bottom_left_scene()
Children [
feathers_option_checkbox("ROTATE", Some(CheckboxInput::Rotation)),
feathers_option_checkbox("WIREFRAME", Some(CheckboxInput::Wireframe)),
]
});
} else {
commands.spawn_scene(bsn! {
top_left_scene() // so the user can immediately see the control in browser w/o scrolling
Children [
feathers_option_checkbox("ROTATE", Some(CheckboxInput::Rotation)),
]
});
}
}

#[cfg(not(target_arch = "wasm32"))]
fn toggle_wireframe(mut wireframe_config: ResMut<Wireframe2dConfig>) {
wireframe_config.global = !wireframe_config.global;
fn handle_value_change_checkbox(
event: On<ValueChange<bool>>,
#[cfg(not(target_arch = "wasm32"))] mut wireframe_config: ResMut<Wireframe2dConfig>,
mut app_status: ResMut<AppStatus>,
checkbox_input_q: Query<&CheckboxInput, With<FeathersCheckbox>>,
) {
if let Ok(checkbox_input) = checkbox_input_q.get(event.source) {
match checkbox_input {
CheckboxInput::Rotation => {
app_status.rotation = event.value;
}
#[cfg(target_arch = "wasm32")]
CheckboxInput::Wireframe => {}
#[cfg(not(target_arch = "wasm32"))]

@kfc35 kfc35 Jul 27, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can be simplified to just one cfg call within the CheckboxInput::Wireframe match itself for #[cfg(not(target_arch = "wasm32"))]

i.e.

            CheckboxInput::Wireframe => {
                if !cfg!(target_arch = "wasm32") {
                    wireframe_config.global = !wireframe_config.global;
                }
            }

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm that throws an error since the Wireframe2dConfig is removed at compile time by the #[cfg(...)] gate on use bevy::sprite_render and since the cfg macro doesn't remove any code at compile time (TIL) the compiler still requires wireframe_config to be defined somewhere

CheckboxInput::Wireframe => {
wireframe_config.global = event.value;
}
}
}
}

fn rotate_checkbox_checked(app_status: Res<AppStatus>) -> bool {
app_status.rotation
}

fn rotate(mut query: Query<&mut Transform, With<Mesh2d>>, time: Res<Time>) {
Expand Down
53 changes: 53 additions & 0 deletions examples/helpers/checkbox.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/// Helpers to create an option menu using Feathers Checkboxes.
/// Using these helpers requires the `bevy_feathers` feature to be enabled.
use bevy::{
feathers::{controls::FeathersCheckbox, display::caption},
picking::hover::Hovered,
prelude::*,
ui_widgets::checkbox_self_update,
};

/// Creates a single feathers checkbox that allows configuration of a setting.
///
/// Examples that use this to create a checkbox should handle its `ValueChange<bool>` events.
/// If there is a need to identify the checkbox that originated the value change,
/// query which `checkbox_identifier` with the `FeathersCheckbox` is the value change's
/// source entity.
pub fn feathers_option_checkbox<T>(
option_name: &str,
checkbox_identifier: Option<T>,
) -> Box<dyn Scene>
where
T: Template<Output: Component> + Clone + Default + Send + Sync + Unpin + 'static,
{
if let Some(identifier) = checkbox_identifier {
Box::new(bsn! {
Node {
align_items: AlignItems::Center,
column_gap: px(5),
}
Children [
@FeathersCheckbox {
@caption: bsn! { caption(option_name) }
}
Hovered::default()
template_value(identifier)
on(checkbox_self_update)
]
})
} else {
Box::new(bsn! {
Node {
align_items: AlignItems::Center,
column_gap: px(5),
}
Children [
@FeathersCheckbox {
@caption: bsn! { caption(option_name) }
}
Hovered::default()
on(checkbox_self_update)
]
})
}
}
32 changes: 32 additions & 0 deletions examples/helpers/scene.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/// Helpers to create a [`Node`] appropriate for the outer main UI node as a `Scene`.
use bevy::prelude::*;

/// Returns a [`Node`] appropriate for the outer main UI node as a `Scene`.
///
/// This UI is in the bottom left corner and has flex column support
pub fn bottom_left_scene() -> impl Scene {
bsn! {
Node {
flex_direction: FlexDirection::Column,
position_type: PositionType::Absolute,
row_gap: px(6),
left: px(10),
bottom: px(10),
}
}
}

/// Returns a [`Node`] appropriate for the outer main UI node as a `Scene`.
///
/// This UI is in the top left corner and has flex column support
pub fn top_left_scene() -> impl Scene {
bsn! {
Node {
flex_direction: FlexDirection::Column,
position_type: PositionType::Absolute,
row_gap: px(6),
left: px(10),
top: px(10),
}
}
}
39 changes: 39 additions & 0 deletions examples/helpers/theme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,45 @@ pub fn basic_example_theme(text_color: Color) -> ThemeProps {
bevy::feathers::palette::TRANSPARENT,
);

// Checkbox tokens
color.insert(bevy::feathers::tokens::CHECKBOX_TEXT, text_color);
color.insert(bevy::feathers::tokens::CHECKBOX_BG, Color::BLACK);
color.insert(bevy::feathers::tokens::CHECKBOX_MARK, Color::WHITE);
color.insert(bevy::feathers::tokens::CHECKBOX_BORDER, Color::BLACK);
color.insert(
bevy::feathers::tokens::CHECKBOX_BORDER_HOVER,
bevy::feathers::palette::GRAY_2,
);
color.insert(
bevy::feathers::tokens::CHECKBOX_BORDER_CHECKED_HOVER,
bevy::feathers::palette::GRAY_0,
);
color.insert(
bevy::feathers::tokens::CHECKBOX_BORDER_PRESSED,
bevy::feathers::palette::GRAY_1,
);
color.insert(
bevy::feathers::tokens::CHECKBOX_BORDER_CHECKED_PRESSED,
bevy::feathers::palette::GRAY_1,
);
color.insert(
bevy::feathers::tokens::CHECKBOX_BORDER_CHECKED,
Color::BLACK,
);
color.insert(
bevy::feathers::tokens::CHECKBOX_BG_HOVER,
bevy::feathers::palette::GRAY_0,
);
color.insert(bevy::feathers::tokens::CHECKBOX_BG_CHECKED, Color::BLACK);
color.insert(
bevy::feathers::tokens::CHECKBOX_BG_CHECKED_HOVER,
Color::BLACK,
);
color.insert(
bevy::feathers::tokens::CHECKBOX_BG_CHECKED_PRESSED,
bevy::feathers::palette::GRAY_1,
);
color.insert(bevy::feathers::tokens::CHECKBOX_BG_PRESSED, Color::BLACK);
// Feathers Button / Select
color.insert(
bevy::feathers::tokens::BUTTON_BG,
Expand Down