repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/ghost_nodes.rs | examples/ui/ghost_nodes.rs | //! This example demonstrates the use of Ghost Nodes.
//!
//! UI layout will ignore ghost nodes, and treat their children as if they were direct descendants of the first non-ghost ancestor.
//!
//! # Warning
//!
//! This is an experimental feature, and should be used with caution,
//! especially in concert with 3rd party plugins or systems that may not be aware of ghost nodes.
//!
//! In order to use [`GhostNode`]s you must enable the `ghost_nodes` feature flag.
use bevy::{prelude::*, ui::experimental::GhostNode};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, button_system)
.run();
}
#[derive(Component)]
struct Counter(i32);
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let font_handle = asset_server.load("fonts/FiraSans-Bold.ttf");
commands.spawn(Camera2d);
// Ghost UI root
commands.spawn(GhostNode).with_children(|ghost_root| {
ghost_root.spawn(Node::default()).with_child(create_label(
"This text node is rendered under a ghost root",
font_handle.clone(),
));
});
// Normal UI root
commands
.spawn(Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
})
.with_children(|parent| {
parent
.spawn((Node::default(), Counter(0)))
.with_children(|layout_parent| {
layout_parent
.spawn((GhostNode, Counter(0)))
.with_children(|ghost_parent| {
// Ghost children using a separate counter state
// These buttons are being treated as children of layout_parent in the context of UI
ghost_parent
.spawn(create_button())
.with_child(create_label("0", font_handle.clone()));
ghost_parent
.spawn(create_button())
.with_child(create_label("0", font_handle.clone()));
});
// A normal child using the layout parent counter
layout_parent
.spawn(create_button())
.with_child(create_label("0", font_handle.clone()));
});
});
}
fn create_button() -> impl Bundle {
(
Button,
Node {
width: px(150),
height: px(65),
border: UiRect::all(px(5)),
// horizontally center child text
justify_content: JustifyContent::Center,
// vertically center child text
align_items: AlignItems::Center,
border_radius: BorderRadius::MAX,
..default()
},
BorderColor::all(Color::BLACK),
BackgroundColor(Color::srgb(0.15, 0.15, 0.15)),
)
}
fn create_label(text: &str, font: Handle<Font>) -> (Text, TextFont, TextColor) {
(
Text::new(text),
TextFont {
font: font.into(),
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
)
}
fn button_system(
mut interaction_query: Query<(&Interaction, &ChildOf), (Changed<Interaction>, With<Button>)>,
labels_query: Query<(&Children, &ChildOf), With<Button>>,
mut text_query: Query<&mut Text>,
mut counter_query: Query<&mut Counter>,
) {
// Update parent counter on click
for (interaction, child_of) in &mut interaction_query {
if matches!(interaction, Interaction::Pressed) {
let mut counter = counter_query.get_mut(child_of.parent()).unwrap();
counter.0 += 1;
}
}
// Update button labels to match their parent counter
for (children, child_of) in &labels_query {
let counter = counter_query.get(child_of.parent()).unwrap();
let mut text = text_query.get_mut(children[0]).unwrap();
**text = counter.0.to_string();
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/borders.rs | examples/ui/borders.rs | //! Example demonstrating bordered UI nodes
use bevy::{color::palettes::css::*, ecs::spawn::SpawnIter, prelude::*};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
// labels for the different border edges
let border_labels = [
"None",
"All",
"Left",
"Right",
"Top",
"Bottom",
"Horizontal",
"Vertical",
"Top Left",
"Bottom Left",
"Top Right",
"Bottom Right",
"Top Bottom Right",
"Top Bottom Left",
"Top Left Right",
"Bottom Left Right",
];
// all the different combinations of border edges
// these correspond to the labels above
let borders = [
UiRect::default(),
UiRect::all(px(10)),
UiRect::left(px(10)),
UiRect::right(px(10)),
UiRect::top(px(10)),
UiRect::bottom(px(10)),
UiRect::horizontal(px(10)),
UiRect::vertical(px(10)),
UiRect {
left: px(20),
top: px(10),
..default()
},
UiRect {
left: px(10),
bottom: px(20),
..default()
},
UiRect {
right: px(20),
top: px(10),
..default()
},
UiRect {
right: px(10),
bottom: px(10),
..default()
},
UiRect {
right: px(10),
top: px(20),
bottom: px(10),
..default()
},
UiRect {
left: px(10),
top: px(10),
bottom: px(10),
..default()
},
UiRect {
left: px(20),
right: px(10),
top: px(10),
..default()
},
UiRect {
left: px(10),
right: px(10),
bottom: px(20),
..default()
},
];
let borders_examples = (
Node {
margin: px(25).all(),
flex_wrap: FlexWrap::Wrap,
..default()
},
Children::spawn(SpawnIter(border_labels.into_iter().zip(borders).map(
|(label, border)| {
(
Node {
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
..default()
},
children![
(
Node {
width: px(50),
height: px(50),
border,
margin: px(20).all(),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
BackgroundColor(MAROON.into()),
BorderColor {
top: RED.into(),
bottom: YELLOW.into(),
left: GREEN.into(),
right: BLUE.into(),
},
Outline {
width: px(6),
offset: px(6),
color: Color::WHITE,
},
children![(
Node {
width: px(10),
height: px(10),
..default()
},
BackgroundColor(YELLOW.into()),
)]
),
(Text::new(label), TextFont::from_font_size(9.0))
],
)
},
))),
);
let non_zero = |x, y| x != px(0) && y != px(0);
let border_size = move |x, y| {
if non_zero(x, y) {
f32::MAX
} else {
0.
}
};
let borders_examples_rounded = (
Node {
margin: px(25).all(),
flex_wrap: FlexWrap::Wrap,
..default()
},
Children::spawn(SpawnIter(border_labels.into_iter().zip(borders).map(
move |(label, border)| {
(
Node {
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
..default()
},
children![
(
Node {
width: px(50),
height: px(50),
border,
margin: px(20).all(),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
border_radius: BorderRadius::px(
border_size(border.left, border.top),
border_size(border.right, border.top),
border_size(border.right, border.bottom,),
border_size(border.left, border.bottom),
),
..default()
},
BackgroundColor(MAROON.into()),
BorderColor {
top: RED.into(),
bottom: YELLOW.into(),
left: GREEN.into(),
right: BLUE.into(),
},
Outline {
width: px(6),
offset: px(6),
color: Color::WHITE,
},
children![(
Node {
width: px(10),
height: px(10),
border_radius: BorderRadius::MAX,
..default()
},
BackgroundColor(YELLOW.into()),
)],
),
(Text::new(label), TextFont::from_font_size(9.0))
],
)
},
))),
);
commands.spawn((
Node {
margin: px(25).all(),
flex_direction: FlexDirection::Column,
align_self: AlignSelf::Stretch,
justify_self: JustifySelf::Stretch,
..default()
},
BackgroundColor(Color::srgb(0.25, 0.25, 0.25)),
children![
label("Borders"),
borders_examples,
label("Borders Rounded"),
borders_examples_rounded
],
));
}
// A label widget that accepts a &str and returns
// a Bundle that can be spawned
fn label(text: &str) -> impl Bundle {
(
Node {
margin: px(25).all(),
..default()
},
children![(Text::new(text), TextFont::from_font_size(20.0))],
)
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/strikethrough_and_underline.rs | examples/ui/strikethrough_and_underline.rs | //! This example illustrates UI text with strikethrough and underline decorations
use bevy::{
color::palettes::css::{GREEN, NAVY, RED, YELLOW},
prelude::*,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands.spawn((
Text::new("struck\nstruck"),
// Just add the `Strikethrough` component to any `Text`, `Text2d` or `TextSpan` and its text will be struck through
Strikethrough,
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 67.0,
..default()
},
TextLayout::new_with_justify(Justify::Center),
Node {
position_type: PositionType::Absolute,
bottom: px(5),
right: px(5),
..default()
},
TextBackgroundColor::BLACK,
));
commands.spawn((
Node {
flex_direction: FlexDirection::Column,
width: Val::Percent(100.),
height: Val::Percent(100.),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..Default::default()
},
children![
(
Text::new("struck\nstruckstruck\nstruckstuckstruck"),
Strikethrough,
StrikethroughColor(RED.into()),
TextBackgroundColor(GREEN.into()),
),
// Text entities with the `Underline` component will drawn with underline
(Text::new("underline"), Underline),
(
Text::new("struck"),
Strikethrough,
TextBackgroundColor(GREEN.into()),
children![
(TextSpan::new("underline"), Underline),
(TextSpan::new("struck"), Strikethrough,)
],
),
(
Text::new("struck struck"),
Strikethrough,
TextFont {
font_size: 67.0,
..default()
},
),
(
Text::new("2struck\nstruck"),
Strikethrough,
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 67.0,
..default()
},
BackgroundColor(NAVY.into())
),
(
Text::new(""),
children![
(
TextSpan::new("struck"),
Strikethrough,
TextFont {
font_size: 15.,
..default()
},
TextColor(RED.into()),
TextBackgroundColor(Color::BLACK)
),
(
TextSpan::new("\nunderline"),
Underline,
UnderlineColor(YELLOW.into()),
TextFont {
font_size: 30.,
..default()
},
TextColor(RED.into()),
TextBackgroundColor(GREEN.into())
),
(
TextSpan::new("\nstruck"),
TextFont {
font_size: 50.,
..default()
},
Strikethrough,
TextColor(RED.into()),
TextBackgroundColor(NAVY.into())
),
(
TextSpan::new("underlined and struck"),
TextFont {
font_size: 70.,
..default()
},
Strikethrough,
Underline,
TextColor(RED.into()),
TextBackgroundColor(NAVY.into()),
StrikethroughColor(Color::WHITE),
UnderlineColor(Color::WHITE),
)
]
),
],
));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/text_wrap_debug.rs | examples/ui/text_wrap_debug.rs | //! This example demonstrates text wrapping and use of the `LineBreakOn` property.
use argh::FromArgs;
use bevy::{prelude::*, text::LineBreak, window::WindowResolution};
#[derive(FromArgs, Resource)]
/// `text_wrap_debug` demonstrates text wrapping and use of the `LineBreakOn` property
struct Args {
#[argh(option)]
/// window scale factor
scale_factor: Option<f32>,
#[argh(option, default = "1.")]
/// ui scale factor
ui_scale: f32,
}
fn main() {
// `from_env` panics on the web
#[cfg(not(target_arch = "wasm32"))]
let args: Args = argh::from_env();
#[cfg(target_arch = "wasm32")]
let args = Args::from_args(&[], &[]).unwrap();
let window = if let Some(scale_factor) = args.scale_factor {
Window {
resolution: WindowResolution::default().with_scale_factor_override(scale_factor),
..Default::default()
}
} else {
Window::default()
};
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(window),
..Default::default()
}))
.insert_resource(UiScale(args.ui_scale))
.add_systems(Startup, spawn)
.run();
}
fn spawn(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let text_font = TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 12.0,
..default()
};
let root = commands
.spawn((
Node {
width: percent(100),
height: percent(100),
flex_direction: FlexDirection::Column,
..default()
},
BackgroundColor(Color::BLACK),
))
.id();
for linebreak in [
LineBreak::AnyCharacter,
LineBreak::WordBoundary,
LineBreak::WordOrCharacter,
LineBreak::NoWrap,
] {
let row_id = commands
.spawn(Node {
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::SpaceAround,
align_items: AlignItems::Center,
width: percent(100),
height: percent(50),
..default()
})
.id();
let justifications = vec![
JustifyContent::Center,
JustifyContent::FlexStart,
JustifyContent::FlexEnd,
JustifyContent::SpaceAround,
JustifyContent::SpaceBetween,
JustifyContent::SpaceEvenly,
];
for (i, justification) in justifications.into_iter().enumerate() {
let c = 0.3 + i as f32 * 0.1;
let column_id = commands
.spawn((
Node {
justify_content: justification,
flex_direction: FlexDirection::Column,
width: percent(16),
height: percent(95),
overflow: Overflow::clip_x(),
..default()
},
BackgroundColor(Color::srgb(0.5, c, 1.0 - c)),
))
.id();
let messages = [
format!("JustifyContent::{justification:?}"),
format!("LineBreakOn::{linebreak:?}"),
"Line 1\nLine 2".to_string(),
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas auctor, nunc ac faucibus fringilla.".to_string(),
"pneumonoultramicroscopicsilicovolcanoconiosis".to_string()
];
for (j, message) in messages.into_iter().enumerate() {
commands.entity(column_id).with_child((
Text(message.clone()),
text_font.clone(),
TextLayout::new(Justify::Left, linebreak),
BackgroundColor(Color::srgb(0.8 - j as f32 * 0.2, 0., 0.)),
));
}
commands.entity(row_id).add_child(column_id);
}
commands.entity(root).add_child(row_id);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/size_constraints.rs | examples/ui/size_constraints.rs | //! Demonstrates how the to use the size constraints to control the size of a UI node.
use bevy::{color::palettes::css::*, prelude::*};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_message::<ButtonActivated>()
.add_systems(Startup, setup)
.add_systems(Update, (update_buttons, update_radio_buttons_colors))
.run();
}
const ACTIVE_BORDER_COLOR: Color = Color::Srgba(ANTIQUE_WHITE);
const INACTIVE_BORDER_COLOR: Color = Color::BLACK;
const ACTIVE_INNER_COLOR: Color = Color::WHITE;
const INACTIVE_INNER_COLOR: Color = Color::Srgba(NAVY);
const ACTIVE_TEXT_COLOR: Color = Color::BLACK;
const HOVERED_TEXT_COLOR: Color = Color::WHITE;
const UNHOVERED_TEXT_COLOR: Color = Color::srgb(0.5, 0.5, 0.5);
#[derive(Component)]
struct Bar;
#[derive(Copy, Clone, Debug, Component, PartialEq)]
enum Constraint {
FlexBasis,
Width,
MinWidth,
MaxWidth,
}
#[derive(Copy, Clone, Component)]
struct ButtonValue(Val);
#[derive(Message)]
struct ButtonActivated(Entity);
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// ui camera
commands.spawn(Camera2d);
let text_font = (
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 33.0,
..Default::default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
);
commands
.spawn((
Node {
width: percent(100),
height: percent(100),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::BLACK),
))
.with_children(|parent| {
parent
.spawn(Node {
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
})
.with_children(|parent| {
parent.spawn((
Text::new("Size Constraints Example"),
text_font.clone(),
Node {
margin: UiRect::bottom(px(25)),
..Default::default()
},
));
spawn_bar(parent);
parent
.spawn((
Node {
flex_direction: FlexDirection::Column,
align_items: AlignItems::Stretch,
padding: UiRect::all(px(10)),
margin: UiRect::top(px(50)),
..default()
},
BackgroundColor(YELLOW.into()),
))
.with_children(|parent| {
for constraint in [
Constraint::MinWidth,
Constraint::FlexBasis,
Constraint::Width,
Constraint::MaxWidth,
] {
spawn_button_row(parent, constraint, text_font.clone());
}
});
});
});
}
fn spawn_bar(parent: &mut ChildSpawnerCommands) {
parent
.spawn((
Node {
flex_basis: percent(100),
align_self: AlignSelf::Stretch,
padding: UiRect::all(px(10)),
..default()
},
BackgroundColor(YELLOW.into()),
))
.with_children(|parent| {
parent
.spawn((
Node {
align_items: AlignItems::Stretch,
width: percent(100),
height: px(100),
padding: UiRect::all(px(4)),
..default()
},
BackgroundColor(Color::BLACK),
))
.with_children(|parent| {
parent.spawn((Node::default(), BackgroundColor(Color::WHITE), Bar));
});
});
}
fn spawn_button_row(
parent: &mut ChildSpawnerCommands,
constraint: Constraint,
text_style: (TextFont, TextColor),
) {
let label = match constraint {
Constraint::FlexBasis => "flex_basis",
Constraint::Width => "size",
Constraint::MinWidth => "min_size",
Constraint::MaxWidth => "max_size",
};
parent
.spawn((
Node {
flex_direction: FlexDirection::Column,
padding: UiRect::all(px(2)),
align_items: AlignItems::Stretch,
..default()
},
BackgroundColor(Color::BLACK),
))
.with_children(|parent| {
parent
.spawn(Node {
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::End,
padding: UiRect::all(px(2)),
..default()
})
.with_children(|parent| {
// spawn row label
parent
.spawn((Node {
min_width: px(200),
max_width: px(200),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},))
.with_child((Text::new(label), text_style.clone()));
// spawn row buttons
parent.spawn(Node::default()).with_children(|parent| {
spawn_button(
parent,
constraint,
ButtonValue(auto()),
"Auto".to_string(),
text_style.clone(),
true,
);
for percent_value in [0, 25, 50, 75, 100, 125] {
spawn_button(
parent,
constraint,
ButtonValue(percent(percent_value)),
format!("{percent_value}%"),
text_style.clone(),
false,
);
}
});
});
});
}
fn spawn_button(
parent: &mut ChildSpawnerCommands,
constraint: Constraint,
action: ButtonValue,
label: String,
text_style: (TextFont, TextColor),
active: bool,
) {
parent
.spawn((
Button,
Node {
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
border: UiRect::all(px(2)),
margin: UiRect::horizontal(px(2)),
..Default::default()
},
BorderColor::all(if active {
ACTIVE_BORDER_COLOR
} else {
INACTIVE_BORDER_COLOR
}),
constraint,
action,
))
.with_children(|parent| {
parent
.spawn((
Node {
width: px(100),
justify_content: JustifyContent::Center,
..default()
},
BackgroundColor(if active {
ACTIVE_INNER_COLOR
} else {
INACTIVE_INNER_COLOR
}),
))
.with_child((
Text::new(label),
text_style.0,
TextColor(if active {
ACTIVE_TEXT_COLOR
} else {
UNHOVERED_TEXT_COLOR
}),
TextLayout::new_with_justify(Justify::Center),
));
});
}
fn update_buttons(
mut button_query: Query<
(Entity, &Interaction, &Constraint, &ButtonValue),
Changed<Interaction>,
>,
mut bar_node: Single<&mut Node, With<Bar>>,
mut text_query: Query<&mut TextColor>,
children_query: Query<&Children>,
mut button_activated_writer: MessageWriter<ButtonActivated>,
) {
for (button_id, interaction, constraint, value) in button_query.iter_mut() {
match interaction {
Interaction::Pressed => {
button_activated_writer.write(ButtonActivated(button_id));
match constraint {
Constraint::FlexBasis => {
bar_node.flex_basis = value.0;
}
Constraint::Width => {
bar_node.width = value.0;
}
Constraint::MinWidth => {
bar_node.min_width = value.0;
}
Constraint::MaxWidth => {
bar_node.max_width = value.0;
}
}
}
Interaction::Hovered => {
if let Ok(children) = children_query.get(button_id) {
for &child in children {
if let Ok(grand_children) = children_query.get(child) {
for &grandchild in grand_children {
if let Ok(mut text_color) = text_query.get_mut(grandchild)
&& text_color.0 != ACTIVE_TEXT_COLOR
{
text_color.0 = HOVERED_TEXT_COLOR;
}
}
}
}
}
}
Interaction::None => {
if let Ok(children) = children_query.get(button_id) {
for &child in children {
if let Ok(grand_children) = children_query.get(child) {
for &grandchild in grand_children {
if let Ok(mut text_color) = text_query.get_mut(grandchild)
&& text_color.0 != ACTIVE_TEXT_COLOR
{
text_color.0 = UNHOVERED_TEXT_COLOR;
}
}
}
}
}
}
}
}
}
fn update_radio_buttons_colors(
mut button_activated_reader: MessageReader<ButtonActivated>,
button_query: Query<(Entity, &Constraint, &Interaction)>,
mut border_query: Query<&mut BorderColor>,
mut color_query: Query<&mut BackgroundColor>,
mut text_query: Query<&mut TextColor>,
children_query: Query<&Children>,
) {
for &ButtonActivated(button_id) in button_activated_reader.read() {
let (_, target_constraint, _) = button_query.get(button_id).unwrap();
for (id, constraint, interaction) in button_query.iter() {
if target_constraint == constraint {
let (border_color, inner_color, label_color) = if id == button_id {
(ACTIVE_BORDER_COLOR, ACTIVE_INNER_COLOR, ACTIVE_TEXT_COLOR)
} else {
(
INACTIVE_BORDER_COLOR,
INACTIVE_INNER_COLOR,
if matches!(interaction, Interaction::Hovered) {
HOVERED_TEXT_COLOR
} else {
UNHOVERED_TEXT_COLOR
},
)
};
*border_query.get_mut(id).unwrap() = BorderColor::all(border_color);
for &child in children_query.get(id).into_iter().flatten() {
color_query.get_mut(child).unwrap().0 = inner_color;
for &grandchild in children_query.get(child).into_iter().flatten() {
if let Ok(mut text_color) = text_query.get_mut(grandchild) {
text_color.0 = label_color;
}
}
}
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/ui_material.rs | examples/ui/ui_material.rs | //! Demonstrates the use of [`UiMaterials`](UiMaterial) and how to change material values
use bevy::{
color::palettes::css::DARK_BLUE, prelude::*, reflect::TypePath, render::render_resource::*,
shader::ShaderRef,
};
/// This example uses a shader source file from the assets subdirectory
const SHADER_ASSET_PATH: &str = "shaders/custom_ui_material.wgsl";
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(UiMaterialPlugin::<CustomUiMaterial>::default())
.add_systems(Startup, setup)
.add_systems(Update, animate)
.run();
}
fn setup(
mut commands: Commands,
mut ui_materials: ResMut<Assets<CustomUiMaterial>>,
asset_server: Res<AssetServer>,
) {
// Camera so we can see UI
commands.spawn(Camera2d);
commands
.spawn(Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
})
.with_children(|parent| {
let banner_scale_factor = 0.5;
parent.spawn((
Node {
position_type: PositionType::Absolute,
width: px(905.0 * banner_scale_factor),
height: px(363.0 * banner_scale_factor),
border: UiRect::all(px(20)),
border_radius: BorderRadius::all(px(20)),
..default()
},
MaterialNode(ui_materials.add(CustomUiMaterial {
color: LinearRgba::WHITE.to_f32_array().into(),
slider: Vec4::splat(0.5),
color_texture: asset_server.load("branding/banner.png"),
border_color: LinearRgba::WHITE.to_f32_array().into(),
})),
// UI material nodes can have outlines and shadows like any other UI node
Outline {
width: px(2),
offset: px(100),
color: DARK_BLUE.into(),
},
));
});
}
#[derive(AsBindGroup, Asset, TypePath, Debug, Clone)]
struct CustomUiMaterial {
/// Color multiplied with the image
#[uniform(0)]
color: Vec4,
/// Represents how much of the image is visible
/// Goes from 0 to 1
/// A `Vec4` is used here because Bevy with webgl2 requires that uniforms are 16-byte aligned but only the first component is read.
#[uniform(1)]
slider: Vec4,
/// Image used to represent the slider
#[texture(2)]
#[sampler(3)]
color_texture: Handle<Image>,
/// Color of the image's border
#[uniform(4)]
border_color: Vec4,
}
impl UiMaterial for CustomUiMaterial {
fn fragment_shader() -> ShaderRef {
SHADER_ASSET_PATH.into()
}
}
// Fills the slider slowly over 2 seconds and resets it
// Also updates the color of the image to a rainbow color
fn animate(
mut materials: ResMut<Assets<CustomUiMaterial>>,
q: Query<&MaterialNode<CustomUiMaterial>>,
time: Res<Time>,
) {
let duration = 2.0;
for handle in &q {
if let Some(material) = materials.get_mut(handle) {
// rainbow color effect
let new_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 1., 0.5);
let border_color = Color::hsl((time.elapsed_secs() * 60.0) % 360.0, 0.75, 0.75);
material.color = new_color.to_linear().to_vec4();
material.slider.x =
((time.elapsed_secs() % (duration * 2.0)) - duration).abs() / duration;
material.border_color = border_color.to_linear().to_vec4();
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/text_debug.rs | examples/ui/text_debug.rs | //! Shows various text layout options.
use std::{collections::VecDeque, time::Duration};
use bevy::{
color::palettes::css::*,
diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin},
prelude::*,
ui::widget::TextUiWriter,
window::PresentMode,
};
fn main() {
App::new()
.add_plugins((
DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
present_mode: PresentMode::AutoNoVsync,
..default()
}),
..default()
}),
FrameTimeDiagnosticsPlugin::default(),
))
.add_systems(Startup, infotext_system)
.add_systems(Update, change_text_system)
.run();
}
#[derive(Component)]
struct TextChanges;
fn infotext_system(mut commands: Commands, asset_server: Res<AssetServer>) {
let font = FontSource::from(asset_server.load("fonts/FiraSans-Bold.ttf"));
let background_color = MAROON.into();
commands.spawn(Camera2d);
let root_uinode = commands
.spawn(Node {
width: percent(100),
height: percent(100),
justify_content: JustifyContent::SpaceBetween,
..default()
})
.id();
let left_column = commands
.spawn(Node {
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::SpaceBetween,
align_items: AlignItems::Start,
flex_grow: 1.,
margin: UiRect::axes(px(15), px(5)),
..default()
}).with_children(|builder| {
builder.spawn((
Text::new("This is\ntext with\nline breaks\nin the top left."),
TextFont {
font: font.clone(),
font_size: 25.0,
..default()
},
BackgroundColor(background_color)
));
builder.spawn((
Text::new(
"This text is right-justified. The `Justify` component controls the horizontal alignment of the lines of multi-line text relative to each other, and does not affect the text node's position in the UI layout.",
),
TextFont {
font: font.clone(),
font_size: 25.0,
..default()
},
TextColor(YELLOW.into()),
TextLayout::new_with_justify(Justify::Right),
Node {
max_width: px(300),
..default()
},
BackgroundColor(background_color)
));
builder.spawn((
Text::new(
"This\ntext has\nline breaks and also a set width in the bottom left."),
TextFont {
font: font.clone(),
font_size: 25.0,
..default()
},
Node {
max_width: px(300),
..default()
},
BackgroundColor(background_color)
)
);
}).id();
let right_column = commands
.spawn(Node {
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::SpaceBetween,
align_items: AlignItems::End,
flex_grow: 1.,
margin: UiRect::axes(px(15), px(5)),
..default()
})
.with_children(|builder| {
builder.spawn((
Text::new("This text is very long, has a limited width, is center-justified, is positioned in the top right and is also colored pink."),
TextFont {
font: font.clone(),
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.8, 0.2, 0.7)),
TextLayout::new_with_justify(Justify::Center),
Node {
max_width: px(400),
..default()
},
BackgroundColor(background_color),
));
builder.spawn((
Text::new("This text is left-justified and is vertically positioned to distribute the empty space equally above and below it."),
TextFont {
font: font.clone(),
font_size: 29.0,
..default()
},
TextColor(YELLOW.into()),
TextLayout::new_with_justify(Justify::Left),
Node {
max_width: px(300),
..default()
},
BackgroundColor(background_color),
));
builder.spawn((
Text::new("This text is fully justified and is positioned in the same way."),
TextFont {
font: font.clone(),
font_size: 29.0,
..default()
},
TextLayout::new_with_justify(Justify::Justified),
TextColor(GREEN_YELLOW.into()),
Node {
max_width: px(300),
..default()
},
BackgroundColor(background_color),
));
builder
.spawn((
Text::default(),
TextFont {
font: font.clone(),
font_size: 21.0,
..default()
},
TextChanges,
BackgroundColor(background_color),
))
.with_children(|p| {
p.spawn((
TextSpan::new("\nThis text changes in the bottom right"),
TextFont {
font: font.clone(),
font_size: 21.0,
..default()
},
));
p.spawn((
TextSpan::new(" this text has zero font size"),
TextFont {
font: font.clone(),
font_size: 0.0,
..default()
},
TextColor(BLUE.into()),
));
p.spawn((
TextSpan::new("\nThis text changes in the bottom right - "),
TextFont {
font: font.clone(),
font_size: 21.0,
..default()
},
TextColor(RED.into()),
));
p.spawn((
TextSpan::default(),
TextFont {
font: font.clone(),
font_size: 21.0,
..default()
},
TextColor(ORANGE_RED.into()),
));
p.spawn((
TextSpan::new(" fps, "),
TextFont {
font: font.clone(),
font_size: 10.0,
..default()
},
TextColor(YELLOW.into()),
));
p.spawn((
TextSpan::default(),
TextFont {
font: font.clone(),
font_size: 21.0,
..default()
},
TextColor(LIME.into()),
));
p.spawn((
TextSpan::new(" ms/frame"),
TextFont {
font: font.clone(),
font_size: 42.0,
..default()
},
TextColor(BLUE.into()),
));
p.spawn((
TextSpan::new(" this text has negative font size"),
TextFont {
font: font.clone(),
font_size: -42.0,
..default()
},
TextColor(BLUE.into()),
));
});
})
.id();
commands
.entity(root_uinode)
.add_children(&[left_column, right_column]);
}
fn change_text_system(
mut fps_history: Local<VecDeque<f64>>,
mut time_history: Local<VecDeque<Duration>>,
time: Res<Time>,
diagnostics: Res<DiagnosticsStore>,
query: Query<Entity, With<TextChanges>>,
mut writer: TextUiWriter,
) {
time_history.push_front(time.elapsed());
time_history.truncate(120);
let avg_fps = (time_history.len() as f64)
/ (time_history.front().copied().unwrap_or_default()
- time_history.back().copied().unwrap_or_default())
.as_secs_f64()
.max(0.0001);
fps_history.push_front(avg_fps);
fps_history.truncate(120);
let fps_variance = std_deviation(fps_history.make_contiguous()).unwrap_or_default();
for entity in &query {
let mut fps = 0.0;
if let Some(fps_diagnostic) = diagnostics.get(&FrameTimeDiagnosticsPlugin::FPS)
&& let Some(fps_smoothed) = fps_diagnostic.smoothed()
{
fps = fps_smoothed;
}
let mut frame_time = time.delta_secs_f64();
if let Some(frame_time_diagnostic) =
diagnostics.get(&FrameTimeDiagnosticsPlugin::FRAME_TIME)
&& let Some(frame_time_smoothed) = frame_time_diagnostic.smoothed()
{
frame_time = frame_time_smoothed;
}
*writer.text(entity, 0) =
format!("{avg_fps:.1} avg fps, {fps_variance:.1} frametime variance",);
*writer.text(entity, 1) = format!(
"\nThis text changes in the bottom right - {fps:.1} fps, {frame_time:.3} ms/frame",
);
*writer.text(entity, 4) = format!("{fps:.1}");
*writer.text(entity, 6) = format!("{frame_time:.3}");
}
}
fn mean(data: &[f64]) -> Option<f64> {
let sum = data.iter().sum::<f64>();
let count = data.len();
match count {
positive if positive > 0 => Some(sum / count as f64),
_ => None,
}
}
fn std_deviation(data: &[f64]) -> Option<f64> {
match (mean(data), data.len()) {
(Some(data_mean), count) if count > 0 => {
let variance = data
.iter()
.map(|value| {
let diff = data_mean - *value;
diff * diff
})
.sum::<f64>()
/ count as f64;
Some(variance.sqrt())
}
_ => None,
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/ui_scaling.rs | examples/ui/ui_scaling.rs | //! This example illustrates the [`UiScale`] resource from `bevy_ui`.
use bevy::{color::palettes::css::*, prelude::*};
use core::time::Duration;
const SCALE_TIME: u64 = 400;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(TargetScale {
start_scale: 1.0,
target_scale: 1.0,
target_time: Timer::new(Duration::from_millis(SCALE_TIME), TimerMode::Once),
})
.add_systems(Startup, setup)
.add_systems(
Update,
(change_scaling, apply_scaling.after(change_scaling)),
)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let text_font = TextFont {
font_size: 13.,
..default()
};
commands
.spawn((
Node {
width: percent(50),
height: percent(50),
position_type: PositionType::Absolute,
left: percent(25),
top: percent(25),
justify_content: JustifyContent::SpaceAround,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(ANTIQUE_WHITE.into()),
))
.with_children(|parent| {
parent
.spawn((
Node {
width: px(40),
height: px(40),
..default()
},
BackgroundColor(RED.into()),
))
.with_children(|parent| {
parent.spawn((Text::new("Size!"), text_font, TextColor::BLACK));
});
parent.spawn((
Node {
width: percent(15),
height: percent(15),
..default()
},
BackgroundColor(BLUE.into()),
));
parent.spawn((
ImageNode::new(asset_server.load("branding/icon.png")),
Node {
width: px(30),
height: px(30),
..default()
},
));
});
}
/// System that changes the scale of the ui when pressing up or down on the keyboard.
fn change_scaling(input: Res<ButtonInput<KeyCode>>, mut ui_scale: ResMut<TargetScale>) {
if input.just_pressed(KeyCode::ArrowUp) {
let scale = (ui_scale.target_scale * 2.0).min(8.);
ui_scale.set_scale(scale);
info!("Scaling up! Scale: {}", ui_scale.target_scale);
}
if input.just_pressed(KeyCode::ArrowDown) {
let scale = (ui_scale.target_scale / 2.0).max(1. / 8.);
ui_scale.set_scale(scale);
info!("Scaling down! Scale: {}", ui_scale.target_scale);
}
}
#[derive(Resource)]
struct TargetScale {
start_scale: f32,
target_scale: f32,
target_time: Timer,
}
impl TargetScale {
fn set_scale(&mut self, scale: f32) {
self.start_scale = self.current_scale();
self.target_scale = scale;
self.target_time.reset();
}
fn current_scale(&self) -> f32 {
let completion = self.target_time.fraction();
let t = ease_in_expo(completion);
self.start_scale.lerp(self.target_scale, t)
}
fn tick(&mut self, delta: Duration) -> &Self {
self.target_time.tick(delta);
self
}
fn already_completed(&self) -> bool {
self.target_time.is_finished() && !self.target_time.just_finished()
}
}
fn apply_scaling(
time: Res<Time>,
mut target_scale: ResMut<TargetScale>,
mut ui_scale: ResMut<UiScale>,
) {
if target_scale.tick(time.delta()).already_completed() {
return;
}
ui_scale.0 = target_scale.current_scale();
}
fn ease_in_expo(x: f32) -> f32 {
if x == 0. {
0.
} else {
ops::powf(2.0f32, 5. * x - 5.)
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/relative_cursor_position.rs | examples/ui/relative_cursor_position.rs | //! Showcases the [`RelativeCursorPosition`] component, used to check the position of the cursor relative to a UI node.
use bevy::{camera::Viewport, prelude::*, ui::RelativeCursorPosition};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, relative_cursor_position_system)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn((
Camera2d,
Camera {
// Cursor position will take the viewport offset into account
viewport: Some(Viewport {
physical_position: [200, 100].into(),
physical_size: [600, 600].into(),
..default()
}),
..default()
},
));
commands
.spawn(Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
flex_direction: FlexDirection::Column,
..default()
})
.with_children(|parent| {
parent
.spawn((
Node {
width: px(250),
height: px(250),
margin: UiRect::bottom(px(15)),
..default()
},
BackgroundColor(Color::srgb(0.92, 0.14, 0.05)),
))
.insert(RelativeCursorPosition::default());
parent.spawn((
Text::new("(0.0, 0.0)"),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
));
});
}
/// This systems polls the relative cursor position and displays its value in a text component.
fn relative_cursor_position_system(
relative_cursor_position: Single<&RelativeCursorPosition>,
output_query: Single<(&mut Text, &mut TextColor)>,
) {
let (mut output, mut text_color) = output_query.into_inner();
**output = if let Some(relative_cursor_position) = relative_cursor_position.normalized {
format!(
"({:.1}, {:.1})",
relative_cursor_position.x, relative_cursor_position.y
)
} else {
"unknown".to_string()
};
text_color.0 = if relative_cursor_position.cursor_over() {
Color::srgb(0.1, 0.9, 0.1)
} else {
Color::srgb(0.9, 0.1, 0.1)
};
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/ui_texture_slice.rs | examples/ui/ui_texture_slice.rs | //! This example illustrates how to create buttons with their textures sliced
//! and kept in proportion instead of being stretched by the button dimensions
use bevy::{
color::palettes::css::{GOLD, ORANGE},
prelude::*,
ui::widget::NodeImageMode,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, button_system)
.run();
}
fn button_system(
mut interaction_query: Query<
(&Interaction, &Children, &mut ImageNode),
(Changed<Interaction>, With<Button>),
>,
mut text_query: Query<&mut Text>,
) {
for (interaction, children, mut image) in &mut interaction_query {
let mut text = text_query.get_mut(children[0]).unwrap();
match *interaction {
Interaction::Pressed => {
**text = "Press".to_string();
image.color = GOLD.into();
}
Interaction::Hovered => {
**text = "Hover".to_string();
image.color = ORANGE.into();
}
Interaction::None => {
**text = "Button".to_string();
image.color = Color::WHITE;
}
}
}
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let image = asset_server.load("textures/fantasy_ui_borders/panel-border-010.png");
let slicer = TextureSlicer {
border: BorderRect::all(22.0),
center_scale_mode: SliceScaleMode::Stretch,
sides_scale_mode: SliceScaleMode::Stretch,
max_corner_scale: 1.0,
};
// ui camera
commands.spawn(Camera2d);
commands
.spawn(Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
})
.with_children(|parent| {
for [w, h] in [[150.0, 150.0], [300.0, 150.0], [150.0, 300.0]] {
parent
.spawn((
Button,
ImageNode {
image: image.clone(),
image_mode: NodeImageMode::Sliced(slicer.clone()),
..default()
},
Node {
width: px(w),
height: px(h),
// horizontally center child text
justify_content: JustifyContent::Center,
// vertically center child text
align_items: AlignItems::Center,
margin: UiRect::all(px(20)),
..default()
},
))
.with_child((
Text::new("Button"),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
));
}
});
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/z_index.rs | examples/ui/z_index.rs | //! Demonstrates how to use the z-index component on UI nodes to control their relative depth
//!
//! It uses colored boxes with different z-index values to demonstrate how it can affect the order of
//! depth of nodes compared to their siblings, but also compared to the entire UI.
use bevy::{
color::palettes::basic::{BLUE, GRAY, LIME, PURPLE, RED, YELLOW},
prelude::*,
};
fn main() {
App::new()
.insert_resource(ClearColor(Color::BLACK))
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
// spawn the container with default z-index.
// the default z-index value is `ZIndex(0)`.
// because this is a root UI node, using local or global values will do the same thing.
commands
.spawn(Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
})
.with_children(|parent| {
parent
.spawn((
Node {
width: px(180),
height: px(100),
..default()
},
BackgroundColor(GRAY.into()),
))
.with_children(|parent| {
// spawn a node with default z-index.
parent.spawn((
Node {
position_type: PositionType::Absolute,
left: px(10),
bottom: px(40),
width: px(100),
height: px(50),
..default()
},
BackgroundColor(RED.into()),
));
// spawn a node with a positive local z-index of 2.
// it will show above other nodes in the gray container.
parent.spawn((
Node {
position_type: PositionType::Absolute,
left: px(45),
bottom: px(30),
width: px(100),
height: px(50),
..default()
},
ZIndex(2),
BackgroundColor(BLUE.into()),
));
// spawn a node with a negative local z-index.
// it will show under other nodes in the gray container.
parent.spawn((
Node {
position_type: PositionType::Absolute,
left: px(70),
bottom: px(20),
width: px(100),
height: px(75),
..default()
},
ZIndex(-1),
BackgroundColor(LIME.into()),
));
// spawn a node with a positive global z-index of 1.
// it will show above all other nodes, because it's the highest global z-index in this example.
// by default, boxes all share the global z-index of 0 that the gray container is added to.
parent.spawn((
Node {
position_type: PositionType::Absolute,
left: px(15),
bottom: px(10),
width: px(100),
height: px(60),
..default()
},
BackgroundColor(PURPLE.into()),
GlobalZIndex(1),
));
// spawn a node with a negative global z-index of -1.
// this will show under all other nodes including its parent, because it's the lowest global z-index
// in this example.
parent.spawn((
Node {
position_type: PositionType::Absolute,
left: px(-15),
bottom: px(-15),
width: px(100),
height: px(125),
..default()
},
BackgroundColor(YELLOW.into()),
GlobalZIndex(-1),
));
});
});
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/viewport_node.rs | examples/ui/viewport_node.rs | //! A simple scene to demonstrate spawning a viewport widget. The example will demonstrate how to
//! pick entities visible in the widget's view.
use bevy::{
asset::RenderAssetUsages,
camera::RenderTarget,
picking::pointer::PointerInteraction,
prelude::*,
render::render_resource::{TextureDimension, TextureFormat, TextureUsages},
ui::widget::ViewportNode,
};
fn main() {
App::new()
.add_plugins((DefaultPlugins, MeshPickingPlugin))
.add_systems(Startup, test)
.add_systems(Update, draw_mesh_intersections)
.run();
}
#[derive(Component, Reflect, Debug)]
#[reflect(Component)]
struct Shape;
fn test(
mut commands: Commands,
mut images: ResMut<Assets<Image>>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Spawn a UI camera
commands.spawn(Camera3d::default());
// Set up an texture for the 3D camera to render to.
// The size of the texture will be based on the viewport's ui size.
let mut image = Image::new_uninit(
default(),
TextureDimension::D2,
TextureFormat::Bgra8UnormSrgb,
RenderAssetUsages::all(),
);
image.texture_descriptor.usage =
TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST | TextureUsages::RENDER_ATTACHMENT;
let image_handle = images.add(image);
// Spawn the 3D camera
let camera = commands
.spawn((
Camera3d::default(),
Camera {
// Render this camera before our UI camera
order: -1,
..default()
},
RenderTarget::Image(image_handle.clone().into()),
))
.id();
// Spawn something for the 3D camera to look at
commands
.spawn((
Mesh3d(meshes.add(Cuboid::new(5.0, 5.0, 5.0))),
MeshMaterial3d(materials.add(Color::WHITE)),
Transform::from_xyz(0.0, 0.0, -10.0),
Shape,
))
// We can observe pointer events on our objects as normal, the
// `bevy::ui::widget::viewport_picking` system will take care of ensuring our viewport
// clicks pass through
.observe(on_drag_cuboid);
// Spawn our viewport widget
commands
.spawn((
Node {
position_type: PositionType::Absolute,
top: px(50),
left: px(50),
width: px(200),
height: px(200),
border: UiRect::all(px(5)),
..default()
},
BorderColor::all(Color::WHITE),
ViewportNode::new(camera),
))
.observe(on_drag_viewport);
}
fn on_drag_viewport(drag: On<Pointer<Drag>>, mut node_query: Query<&mut Node>) {
if matches!(drag.button, PointerButton::Secondary) {
let mut node = node_query.get_mut(drag.entity).unwrap();
if let (Val::Px(top), Val::Px(left)) = (node.top, node.left) {
node.left = px(left + drag.delta.x);
node.top = px(top + drag.delta.y);
};
}
}
fn on_drag_cuboid(drag: On<Pointer<Drag>>, mut transform_query: Query<&mut Transform>) {
if matches!(drag.button, PointerButton::Primary) {
let mut transform = transform_query.get_mut(drag.entity).unwrap();
transform.rotate_y(drag.delta.x * 0.02);
transform.rotate_x(drag.delta.y * 0.02);
}
}
fn draw_mesh_intersections(
pointers: Query<&PointerInteraction>,
untargetable: Query<Entity, Without<Shape>>,
mut gizmos: Gizmos,
) {
for (point, normal) in pointers
.iter()
.flat_map(|interaction| interaction.iter())
.filter_map(|(entity, hit)| {
if !untargetable.contains(*entity) {
hit.position.zip(hit.normal)
} else {
None
}
})
{
gizmos.arrow(point, point + normal.normalize() * 0.5, Color::WHITE);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/standard_widgets_observers.rs | examples/ui/standard_widgets_observers.rs | //! This experimental example illustrates how to create widgets using the `bevy_ui_widgets` widget set.
//!
//! The patterns shown here are likely to change substantially as the `bevy_ui_widgets` crate
//! matures, so please exercise caution if you are using this as a reference for your own code,
//! and note that there are still "user experience" issues with this API.
use bevy::{
color::palettes::basic::*,
input_focus::{
tab_navigation::{TabGroup, TabIndex, TabNavigationPlugin},
InputDispatchPlugin,
},
picking::hover::Hovered,
prelude::*,
reflect::Is,
ui::{Checked, InteractionDisabled, Pressed},
ui_widgets::{
checkbox_self_update, observe, Activate, Button, Checkbox, Slider, SliderRange,
SliderThumb, SliderValue, UiWidgetsPlugins, ValueChange,
},
};
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
UiWidgetsPlugins,
InputDispatchPlugin,
TabNavigationPlugin,
))
.insert_resource(DemoWidgetStates { slider_value: 50.0 })
.add_systems(Startup, setup)
.add_observer(button_on_interaction::<Add, Pressed>)
.add_observer(button_on_interaction::<Remove, Pressed>)
.add_observer(button_on_interaction::<Add, InteractionDisabled>)
.add_observer(button_on_interaction::<Remove, InteractionDisabled>)
.add_observer(button_on_interaction::<Insert, Hovered>)
.add_observer(slider_on_interaction::<Add, InteractionDisabled>)
.add_observer(slider_on_interaction::<Remove, InteractionDisabled>)
.add_observer(slider_on_interaction::<Insert, Hovered>)
.add_observer(slider_on_change_value::<SliderValue>)
.add_observer(slider_on_change_value::<SliderRange>)
.add_observer(checkbox_on_interaction::<Add, InteractionDisabled>)
.add_observer(checkbox_on_interaction::<Remove, InteractionDisabled>)
.add_observer(checkbox_on_interaction::<Insert, Hovered>)
.add_observer(checkbox_on_interaction::<Add, Checked>)
.add_observer(checkbox_on_interaction::<Remove, Checked>)
.add_systems(Update, (update_widget_values, toggle_disabled))
.run();
}
const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
const SLIDER_TRACK: Color = Color::srgb(0.05, 0.05, 0.05);
const SLIDER_THUMB: Color = Color::srgb(0.35, 0.75, 0.35);
const CHECKBOX_OUTLINE: Color = Color::srgb(0.45, 0.45, 0.45);
const CHECKBOX_CHECK: Color = Color::srgb(0.35, 0.75, 0.35);
/// Marker which identifies buttons with a particular style, in this case the "Demo style".
#[derive(Component)]
struct DemoButton;
/// Marker which identifies sliders with a particular style.
#[derive(Component, Default)]
struct DemoSlider;
/// Marker which identifies the slider's thumb element.
#[derive(Component, Default)]
struct DemoSliderThumb;
/// Marker which identifies checkboxes with a particular style.
#[derive(Component, Default)]
struct DemoCheckbox;
/// A struct to hold the state of various widgets shown in the demo.
///
/// While it is possible to use the widget's own state components as the source of truth,
/// in many cases widgets will be used to display dynamic data coming from deeper within the app,
/// using some kind of data-binding. This example shows how to maintain an external source of
/// truth for widget states.
#[derive(Resource)]
struct DemoWidgetStates {
slider_value: f32,
}
fn setup(mut commands: Commands, assets: Res<AssetServer>) {
// ui camera
commands.spawn(Camera2d);
commands.spawn(demo_root(&assets));
}
fn demo_root(asset_server: &AssetServer) -> impl Bundle {
(
Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
display: Display::Flex,
flex_direction: FlexDirection::Column,
row_gap: px(10),
..default()
},
TabGroup::default(),
children![
(
button(asset_server),
observe(|_activate: On<Activate>| {
info!("Button clicked!");
}),
),
(
slider(0.0, 100.0, 50.0),
observe(
|value_change: On<ValueChange<f32>>,
mut widget_states: ResMut<DemoWidgetStates>| {
widget_states.slider_value = value_change.value;
},
)
),
(
checkbox(asset_server, "Checkbox"),
observe(checkbox_self_update),
),
Text::new("Press 'D' to toggle widget disabled states"),
],
)
}
fn button(asset_server: &AssetServer) -> impl Bundle {
(
Node {
width: px(150),
height: px(65),
border: UiRect::all(px(5)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
border_radius: BorderRadius::MAX,
..default()
},
DemoButton,
Button,
Hovered::default(),
TabIndex(0),
BorderColor::all(Color::BLACK),
BackgroundColor(NORMAL_BUTTON),
children![(
Text::new("Button"),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
TextShadow::default(),
)],
)
}
fn button_on_interaction<E: EntityEvent, C: Component>(
event: On<E, C>,
mut buttons: Query<
(
&Hovered,
Has<InteractionDisabled>,
Has<Pressed>,
&mut BackgroundColor,
&mut BorderColor,
&Children,
),
With<DemoButton>,
>,
mut text_query: Query<&mut Text>,
) {
if let Ok((hovered, disabled, pressed, mut color, mut border_color, children)) =
buttons.get_mut(event.event_target())
{
if children.is_empty() {
return;
}
let Ok(mut text) = text_query.get_mut(children[0]) else {
return;
};
let hovered = hovered.get();
// These "removal event checks" exist because the `Remove` event is triggered _before_ the component is actually
// removed, meaning it still shows up in the query. We're investigating the best way to improve this scenario.
let pressed = pressed && !(E::is::<Remove>() && C::is::<Pressed>());
let disabled = disabled && !(E::is::<Remove>() && C::is::<InteractionDisabled>());
match (disabled, hovered, pressed) {
// Disabled button
(true, _, _) => {
**text = "Disabled".to_string();
*color = NORMAL_BUTTON.into();
border_color.set_all(GRAY);
}
// Pressed and hovered button
(false, true, true) => {
**text = "Press".to_string();
*color = PRESSED_BUTTON.into();
border_color.set_all(RED);
}
// Hovered, unpressed button
(false, true, false) => {
**text = "Hover".to_string();
*color = HOVERED_BUTTON.into();
border_color.set_all(WHITE);
}
// Unhovered button (either pressed or not).
(false, false, _) => {
**text = "Button".to_string();
*color = NORMAL_BUTTON.into();
border_color.set_all(BLACK);
}
}
}
}
/// Create a demo slider
fn slider(min: f32, max: f32, value: f32) -> impl Bundle {
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Stretch,
justify_items: JustifyItems::Center,
column_gap: px(4),
height: px(12),
width: percent(30),
..default()
},
Name::new("Slider"),
Hovered::default(),
DemoSlider,
Slider::default(),
SliderValue(value),
SliderRange::new(min, max),
TabIndex(0),
Children::spawn((
// Slider background rail
Spawn((
Node {
height: px(6),
border_radius: BorderRadius::all(px(3)),
..default()
},
BackgroundColor(SLIDER_TRACK), // Border color for the checkbox
)),
// Invisible track to allow absolute placement of thumb entity. This is narrower than
// the actual slider, which allows us to position the thumb entity using simple
// percentages, without having to measure the actual width of the slider thumb.
Spawn((
Node {
display: Display::Flex,
position_type: PositionType::Absolute,
left: px(0),
// Track is short by 12px to accommodate the thumb.
right: px(12),
top: px(0),
bottom: px(0),
..default()
},
children![(
// Thumb
DemoSliderThumb,
SliderThumb,
Node {
display: Display::Flex,
width: px(12),
height: px(12),
position_type: PositionType::Absolute,
left: percent(0), // This will be updated by the slider's value
border_radius: BorderRadius::MAX,
..default()
},
BackgroundColor(SLIDER_THUMB),
)],
)),
)),
)
}
fn slider_on_interaction<E: EntityEvent, C: Component>(
event: On<E, C>,
sliders: Query<(Entity, &Hovered, Has<InteractionDisabled>), With<DemoSlider>>,
children: Query<&Children>,
mut thumbs: Query<(&mut BackgroundColor, Has<DemoSliderThumb>), Without<DemoSlider>>,
) {
if let Ok((slider_ent, hovered, disabled)) = sliders.get(event.event_target()) {
// These "removal event checks" exist because the `Remove` event is triggered _before_ the component is actually
// removed, meaning it still shows up in the query. We're investigating the best way to improve this scenario.
let disabled = disabled && !(E::is::<Remove>() && C::is::<InteractionDisabled>());
for child in children.iter_descendants(slider_ent) {
if let Ok((mut thumb_bg, is_thumb)) = thumbs.get_mut(child)
&& is_thumb
{
thumb_bg.0 = thumb_color(disabled, hovered.0);
}
}
}
}
fn slider_on_change_value<C: Component>(
insert: On<Insert, C>,
sliders: Query<(Entity, &SliderValue, &SliderRange), With<DemoSlider>>,
children: Query<&Children>,
mut thumbs: Query<(&mut Node, Has<DemoSliderThumb>), Without<DemoSlider>>,
) {
if let Ok((slider_ent, value, range)) = sliders.get(insert.entity) {
for child in children.iter_descendants(slider_ent) {
if let Ok((mut thumb_node, is_thumb)) = thumbs.get_mut(child)
&& is_thumb
{
thumb_node.left = percent(range.thumb_position(value.0) * 100.0);
}
}
}
}
fn thumb_color(disabled: bool, hovered: bool) -> Color {
match (disabled, hovered) {
(true, _) => GRAY.into(),
(false, true) => SLIDER_THUMB.lighter(0.3),
_ => SLIDER_THUMB,
}
}
/// Create a demo checkbox
fn checkbox(asset_server: &AssetServer, caption: &str) -> impl Bundle {
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::FlexStart,
align_items: AlignItems::Center,
align_content: AlignContent::Center,
column_gap: px(4),
..default()
},
Name::new("Checkbox"),
Hovered::default(),
DemoCheckbox,
Checkbox,
TabIndex(0),
Children::spawn((
Spawn((
// Checkbox outer
Node {
display: Display::Flex,
width: px(16),
height: px(16),
border: UiRect::all(px(2)),
border_radius: BorderRadius::all(px(3)),
..default()
},
BorderColor::all(CHECKBOX_OUTLINE), // Border color for the checkbox
children![
// Checkbox inner
(
Node {
display: Display::Flex,
width: px(8),
height: px(8),
position_type: PositionType::Absolute,
left: px(2),
top: px(2),
..default()
},
BackgroundColor(Srgba::NONE.into()),
),
],
)),
Spawn((
Text::new(caption),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 20.0,
..default()
},
)),
)),
)
}
fn checkbox_on_interaction<E: EntityEvent, C: Component>(
event: On<E, C>,
checkboxes: Query<
(&Hovered, Has<InteractionDisabled>, Has<Checked>, &Children),
With<DemoCheckbox>,
>,
mut borders: Query<(&mut BorderColor, &mut Children), Without<DemoCheckbox>>,
mut marks: Query<&mut BackgroundColor, (Without<DemoCheckbox>, Without<Children>)>,
) {
if let Ok((hovered, disabled, checked, children)) = checkboxes.get(event.event_target()) {
let hovered = hovered.get();
// These "removal event checks" exist because the `Remove` event is triggered _before_ the component is actually
// removed, meaning it still shows up in the query. We're investigating the best way to improve this scenario.
let checked = checked && !(E::is::<Remove>() && C::is::<Checked>());
let disabled = disabled && !(E::is::<Remove>() && C::is::<InteractionDisabled>());
let Some(border_id) = children.first() else {
return;
};
let Ok((mut border_color, border_children)) = borders.get_mut(*border_id) else {
return;
};
let Some(mark_id) = border_children.first() else {
warn!("Checkbox does not have a mark entity.");
return;
};
let Ok(mut mark_bg) = marks.get_mut(*mark_id) else {
warn!("Checkbox mark entity lacking a background color.");
return;
};
let color: Color = if disabled {
// If the checkbox is disabled, use a lighter color
CHECKBOX_OUTLINE.with_alpha(0.2)
} else if hovered {
// If hovering, use a lighter color
CHECKBOX_OUTLINE.lighter(0.2)
} else {
// Default color for the checkbox
CHECKBOX_OUTLINE
};
// Update the background color of the check mark
border_color.set_all(color);
let mark_color: Color = match (disabled, checked) {
(true, true) => CHECKBOX_CHECK.with_alpha(0.5),
(false, true) => CHECKBOX_CHECK,
(_, false) => Srgba::NONE.into(),
};
if mark_bg.0 != mark_color {
// Update the color of the check mark
mark_bg.0 = mark_color;
}
}
}
/// Update the widget states based on the changing resource.
fn update_widget_values(
res: Res<DemoWidgetStates>,
mut sliders: Query<Entity, With<DemoSlider>>,
mut commands: Commands,
) {
if res.is_changed() {
for slider_ent in sliders.iter_mut() {
commands
.entity(slider_ent)
.insert(SliderValue(res.slider_value));
}
}
}
fn toggle_disabled(
input: Res<ButtonInput<KeyCode>>,
mut interaction_query: Query<
(Entity, Has<InteractionDisabled>),
Or<(With<Button>, With<Slider>, With<Checkbox>)>,
>,
mut commands: Commands,
) {
if input.just_pressed(KeyCode::KeyD) {
for (entity, disabled) in &mut interaction_query {
if disabled {
info!("Widget enabled");
commands.entity(entity).remove::<InteractionDisabled>();
} else {
info!("Widget disabled");
commands.entity(entity).insert(InteractionDisabled);
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/feathers.rs | examples/ui/feathers.rs | //! This example shows off the various Bevy Feathers widgets.
use bevy::{
color::palettes,
feathers::{
controls::{
button, checkbox, color_plane, color_slider, color_swatch, radio, slider,
toggle_switch, ButtonProps, ButtonVariant, ColorChannel, ColorPlane, ColorPlaneValue,
ColorSlider, ColorSliderProps, ColorSwatch, ColorSwatchValue, SliderBaseColor,
SliderProps,
},
cursor::{EntityCursor, OverrideCursor},
dark_theme::create_dark_theme,
rounded_corners::RoundedCorners,
theme::{ThemeBackgroundColor, ThemedText, UiTheme},
tokens, FeathersPlugins,
},
input_focus::tab_navigation::TabGroup,
prelude::*,
ui::{Checked, InteractionDisabled},
ui_widgets::{
checkbox_self_update, observe, slider_self_update, Activate, RadioButton, RadioGroup,
SliderPrecision, SliderStep, SliderValue, ValueChange,
},
window::SystemCursorIcon,
};
/// A struct to hold the state of various widgets shown in the demo.
#[derive(Resource)]
struct DemoWidgetStates {
rgb_color: Srgba,
hsl_color: Hsla,
}
#[derive(Component, Clone, Copy, PartialEq)]
enum SwatchType {
Rgb,
Hsl,
}
#[derive(Component, Clone, Copy)]
struct DemoDisabledButton;
fn main() {
App::new()
.add_plugins((DefaultPlugins, FeathersPlugins))
.insert_resource(UiTheme(create_dark_theme()))
.insert_resource(DemoWidgetStates {
rgb_color: palettes::tailwind::EMERALD_800.with_alpha(0.7),
hsl_color: palettes::tailwind::AMBER_800.into(),
})
.add_systems(Startup, setup)
.add_systems(Update, update_colors)
.run();
}
fn setup(mut commands: Commands) {
// ui camera
commands.spawn(Camera2d);
commands.spawn(demo_root());
}
fn demo_root() -> impl Bundle {
(
Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Start,
justify_content: JustifyContent::Start,
display: Display::Flex,
flex_direction: FlexDirection::Column,
row_gap: px(10),
..default()
},
TabGroup::default(),
ThemeBackgroundColor(tokens::WINDOW_BG),
children![(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Column,
align_items: AlignItems::Stretch,
justify_content: JustifyContent::Start,
padding: UiRect::all(px(8)),
row_gap: px(8),
width: percent(30),
min_width: px(200),
..default()
},
children![
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Row,
align_items: AlignItems::Center,
justify_content: JustifyContent::Start,
column_gap: px(8),
..default()
},
children![
(
button(
ButtonProps::default(),
(),
Spawn((Text::new("Normal"), ThemedText))
),
observe(|_activate: On<Activate>| {
info!("Normal button clicked!");
})
),
(
button(
ButtonProps::default(),
(InteractionDisabled, DemoDisabledButton),
Spawn((Text::new("Disabled"), ThemedText))
),
observe(|_activate: On<Activate>| {
info!("Disabled button clicked!");
})
),
(
button(
ButtonProps {
variant: ButtonVariant::Primary,
..default()
},
(),
Spawn((Text::new("Primary"), ThemedText))
),
observe(|_activate: On<Activate>| {
info!("Disabled button clicked!");
})
),
]
),
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Row,
align_items: AlignItems::Center,
justify_content: JustifyContent::Start,
column_gap: px(1),
..default()
},
children![
(
button(
ButtonProps {
corners: RoundedCorners::Left,
..default()
},
(),
Spawn((Text::new("Left"), ThemedText))
),
observe(|_activate: On<Activate>| {
info!("Left button clicked!");
})
),
(
button(
ButtonProps {
corners: RoundedCorners::None,
..default()
},
(),
Spawn((Text::new("Center"), ThemedText))
),
observe(|_activate: On<Activate>| {
info!("Center button clicked!");
})
),
(
button(
ButtonProps {
variant: ButtonVariant::Primary,
corners: RoundedCorners::Right,
},
(),
Spawn((Text::new("Right"), ThemedText))
),
observe(|_activate: On<Activate>| {
info!("Right button clicked!");
})
),
]
),
(
button(
ButtonProps::default(),
(),
Spawn((Text::new("Toggle override"), ThemedText))
),
observe(|_activate: On<Activate>, mut ovr: ResMut<OverrideCursor>| {
ovr.0 = if ovr.0.is_some() {
None
} else {
Some(EntityCursor::System(SystemCursorIcon::Wait))
};
info!("Override cursor button clicked!");
})
),
(
checkbox(Checked, Spawn((Text::new("Checkbox"), ThemedText))),
observe(
|change: On<ValueChange<bool>>,
query: Query<Entity, With<DemoDisabledButton>>,
mut commands: Commands| {
info!("Checkbox clicked!");
let mut button = commands.entity(query.single().unwrap());
if change.value {
button.insert(InteractionDisabled);
} else {
button.remove::<InteractionDisabled>();
}
let mut checkbox = commands.entity(change.source);
if change.value {
checkbox.insert(Checked);
} else {
checkbox.remove::<Checked>();
}
}
)
),
(
checkbox(
InteractionDisabled,
Spawn((Text::new("Disabled"), ThemedText))
),
observe(|_change: On<ValueChange<bool>>| {
warn!("Disabled checkbox clicked!");
})
),
(
checkbox(
(InteractionDisabled, Checked),
Spawn((Text::new("Disabled+Checked"), ThemedText))
),
observe(|_change: On<ValueChange<bool>>| {
warn!("Disabled checkbox clicked!");
})
),
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Column,
row_gap: px(4),
..default()
},
RadioGroup,
observe(
|value_change: On<ValueChange<Entity>>,
q_radio: Query<Entity, With<RadioButton>>,
mut commands: Commands| {
for radio in q_radio.iter() {
if radio == value_change.value {
commands.entity(radio).insert(Checked);
} else {
commands.entity(radio).remove::<Checked>();
}
}
}
),
children![
radio(Checked, Spawn((Text::new("One"), ThemedText))),
radio((), Spawn((Text::new("Two"), ThemedText))),
radio((), Spawn((Text::new("Three"), ThemedText))),
radio(
InteractionDisabled,
Spawn((Text::new("Disabled"), ThemedText))
),
]
),
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Row,
align_items: AlignItems::Center,
justify_content: JustifyContent::Start,
column_gap: px(8),
..default()
},
children![
(toggle_switch((),), observe(checkbox_self_update)),
(
toggle_switch(InteractionDisabled,),
observe(checkbox_self_update)
),
(
toggle_switch((InteractionDisabled, Checked),),
observe(checkbox_self_update)
),
]
),
(
slider(
SliderProps {
max: 100.0,
value: 20.0,
..default()
},
(SliderStep(10.), SliderPrecision(2)),
),
observe(slider_self_update)
),
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::SpaceBetween,
..default()
},
children![Text("Srgba".to_owned()), color_swatch(SwatchType::Rgb),]
),
(
color_plane(ColorPlane::RedBlue, ()),
observe(
|change: On<ValueChange<Vec2>>, mut color: ResMut<DemoWidgetStates>| {
color.rgb_color.red = change.value.x;
color.rgb_color.blue = change.value.y;
}
)
),
(
color_slider(
ColorSliderProps {
value: 0.5,
channel: ColorChannel::Red
},
()
),
observe(
|change: On<ValueChange<f32>>, mut color: ResMut<DemoWidgetStates>| {
color.rgb_color.red = change.value;
}
)
),
(
color_slider(
ColorSliderProps {
value: 0.5,
channel: ColorChannel::Green
},
()
),
observe(
|change: On<ValueChange<f32>>, mut color: ResMut<DemoWidgetStates>| {
color.rgb_color.green = change.value;
},
)
),
(
color_slider(
ColorSliderProps {
value: 0.5,
channel: ColorChannel::Blue
},
()
),
observe(
|change: On<ValueChange<f32>>, mut color: ResMut<DemoWidgetStates>| {
color.rgb_color.blue = change.value;
},
)
),
(
color_slider(
ColorSliderProps {
value: 0.5,
channel: ColorChannel::Alpha
},
()
),
observe(
|change: On<ValueChange<f32>>, mut color: ResMut<DemoWidgetStates>| {
color.rgb_color.alpha = change.value;
},
)
),
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::SpaceBetween,
..default()
},
children![Text("Hsl".to_owned()), color_swatch(SwatchType::Hsl),]
),
(
color_slider(
ColorSliderProps {
value: 0.5,
channel: ColorChannel::HslHue
},
()
),
observe(
|change: On<ValueChange<f32>>, mut color: ResMut<DemoWidgetStates>| {
color.hsl_color.hue = change.value;
},
)
),
(
color_slider(
ColorSliderProps {
value: 0.5,
channel: ColorChannel::HslSaturation
},
()
),
observe(
|change: On<ValueChange<f32>>, mut color: ResMut<DemoWidgetStates>| {
color.hsl_color.saturation = change.value;
},
)
),
(
color_slider(
ColorSliderProps {
value: 0.5,
channel: ColorChannel::HslLightness
},
()
),
observe(
|change: On<ValueChange<f32>>, mut color: ResMut<DemoWidgetStates>| {
color.hsl_color.lightness = change.value;
},
)
)
]
),],
)
}
fn update_colors(
colors: Res<DemoWidgetStates>,
mut sliders: Query<(Entity, &ColorSlider, &mut SliderBaseColor)>,
mut swatches: Query<(&mut ColorSwatchValue, &SwatchType), With<ColorSwatch>>,
mut color_planes: Query<&mut ColorPlaneValue, With<ColorPlane>>,
mut commands: Commands,
) {
if colors.is_changed() {
for (slider_ent, slider, mut base) in sliders.iter_mut() {
match slider.channel {
ColorChannel::Red => {
base.0 = colors.rgb_color.into();
commands
.entity(slider_ent)
.insert(SliderValue(colors.rgb_color.red));
}
ColorChannel::Green => {
base.0 = colors.rgb_color.into();
commands
.entity(slider_ent)
.insert(SliderValue(colors.rgb_color.green));
}
ColorChannel::Blue => {
base.0 = colors.rgb_color.into();
commands
.entity(slider_ent)
.insert(SliderValue(colors.rgb_color.blue));
}
ColorChannel::HslHue => {
base.0 = colors.hsl_color.into();
commands
.entity(slider_ent)
.insert(SliderValue(colors.hsl_color.hue));
}
ColorChannel::HslSaturation => {
base.0 = colors.hsl_color.into();
commands
.entity(slider_ent)
.insert(SliderValue(colors.hsl_color.saturation));
}
ColorChannel::HslLightness => {
base.0 = colors.hsl_color.into();
commands
.entity(slider_ent)
.insert(SliderValue(colors.hsl_color.lightness));
}
ColorChannel::Alpha => {
base.0 = colors.rgb_color.into();
commands
.entity(slider_ent)
.insert(SliderValue(colors.rgb_color.alpha));
}
}
}
for (mut swatch_value, swatch_type) in swatches.iter_mut() {
swatch_value.0 = match swatch_type {
SwatchType::Rgb => colors.rgb_color.into(),
SwatchType::Hsl => colors.hsl_color.into(),
};
}
for mut plane_value in color_planes.iter_mut() {
plane_value.0.x = colors.rgb_color.red;
plane_value.0.y = colors.rgb_color.blue;
plane_value.0.z = colors.rgb_color.green;
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/standard_widgets.rs | examples/ui/standard_widgets.rs | //! This experimental example illustrates how to create widgets using the `bevy_ui_widgets` widget set.
//!
//! These widgets have no inherent styling, so this example also shows how to implement custom styles.
//!
//! The patterns shown here are likely to change substantially as the `bevy_ui_widgets` crate
//! matures, so please exercise caution if you are using this as a reference for your own code,
//! and note that there are still "user experience" issues with this API.
use bevy::{
color::palettes::basic::*,
input_focus::{
tab_navigation::{TabGroup, TabIndex, TabNavigationPlugin},
InputDispatchPlugin, InputFocus,
},
picking::hover::Hovered,
prelude::*,
ui::{Checked, InteractionDisabled, Pressed},
ui_widgets::{
checkbox_self_update, observe,
popover::{Popover, PopoverAlign, PopoverPlacement, PopoverSide},
Activate, Button, Checkbox, CoreSliderDragState, MenuAction, MenuButton, MenuEvent,
MenuItem, MenuPopup, RadioButton, RadioGroup, Slider, SliderRange, SliderThumb,
SliderValue, TrackClick, UiWidgetsPlugins, ValueChange,
},
};
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
UiWidgetsPlugins,
InputDispatchPlugin,
TabNavigationPlugin,
))
.insert_resource(DemoWidgetStates {
slider_value: 50.0,
slider_click: TrackClick::Snap,
})
.add_systems(Startup, setup)
.add_systems(
Update,
(
update_widget_values,
update_button_style,
update_button_style2,
update_slider_style.after(update_widget_values),
update_slider_style2.after(update_widget_values),
update_checkbox_or_radio_style.after(update_widget_values),
update_checkbox_or_radio_style2.after(update_widget_values),
update_menu_item_style,
update_menu_item_style2,
toggle_disabled,
),
)
.run();
}
const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
const SLIDER_TRACK: Color = Color::srgb(0.05, 0.05, 0.05);
const SLIDER_THUMB: Color = Color::srgb(0.35, 0.75, 0.35);
const ELEMENT_OUTLINE: Color = Color::srgb(0.45, 0.45, 0.45);
const ELEMENT_FILL: Color = Color::srgb(0.35, 0.75, 0.35);
const ELEMENT_FILL_DISABLED: Color = Color::srgb(0.5019608, 0.5019608, 0.5019608);
/// Marker which identifies buttons with a particular style, in this case the "Demo style".
#[derive(Component)]
struct DemoButton;
/// Marker which identifies sliders with a particular style.
#[derive(Component, Default)]
struct DemoSlider;
/// Marker which identifies the slider's thumb element.
#[derive(Component, Default)]
struct DemoSliderThumb;
/// Marker which identifies checkboxes with a particular style.
#[derive(Component, Default)]
struct DemoCheckbox;
/// Marker which identifies a styled radio button. We'll use this to change the track click
/// behavior.
#[derive(Component, Default)]
struct DemoRadio(TrackClick);
/// Menu anchor marker
#[derive(Component)]
struct DemoMenuAnchor;
/// Menu button styling marker
#[derive(Component)]
struct DemoMenuButton;
/// Menu item styling marker
#[derive(Component)]
struct DemoMenuItem;
/// A struct to hold the state of various widgets shown in the demo.
///
/// While it is possible to use the widget's own state components as the source of truth,
/// in many cases widgets will be used to display dynamic data coming from deeper within the app,
/// using some kind of data-binding. This example shows how to maintain an external source of
/// truth for widget states.
#[derive(Resource)]
struct DemoWidgetStates {
slider_value: f32,
slider_click: TrackClick,
}
/// Update the widget states based on the changing resource.
fn update_widget_values(
res: Res<DemoWidgetStates>,
mut sliders: Query<(Entity, &mut Slider), With<DemoSlider>>,
radios: Query<(Entity, &DemoRadio, Has<Checked>)>,
mut commands: Commands,
) {
if res.is_changed() {
for (slider_ent, mut slider) in sliders.iter_mut() {
commands
.entity(slider_ent)
.insert(SliderValue(res.slider_value));
slider.track_click = res.slider_click;
}
for (radio_id, radio_value, checked) in radios.iter() {
let will_be_checked = radio_value.0 == res.slider_click;
if will_be_checked != checked {
if will_be_checked {
commands.entity(radio_id).insert(Checked);
} else {
commands.entity(radio_id).remove::<Checked>();
}
}
}
}
}
fn setup(mut commands: Commands, assets: Res<AssetServer>) {
// ui camera
commands.spawn(Camera2d);
commands.spawn(demo_root(&assets));
}
fn demo_root(asset_server: &AssetServer) -> impl Bundle {
(
Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
display: Display::Flex,
flex_direction: FlexDirection::Column,
row_gap: px(10),
..default()
},
TabGroup::default(),
children![
(
button(asset_server),
observe(|_activate: On<Activate>| {
info!("Button clicked!");
}),
),
(
slider(0.0, 100.0, 50.0),
observe(
|value_change: On<ValueChange<f32>>,
mut widget_states: ResMut<DemoWidgetStates>| {
widget_states.slider_value = value_change.value;
},
)
),
(
checkbox(asset_server, "Checkbox"),
observe(checkbox_self_update)
),
(
radio_group(asset_server),
observe(
|value_change: On<ValueChange<Entity>>,
mut widget_states: ResMut<DemoWidgetStates>,
q_radios: Query<&DemoRadio>| {
if let Ok(radio) = q_radios.get(value_change.value) {
widget_states.slider_click = radio.0;
}
},
)
),
menu_button(asset_server),
Text::new("Press 'D' to toggle widget disabled states"),
],
)
}
fn button(asset_server: &AssetServer) -> impl Bundle {
(
Node {
width: px(150),
height: px(65),
border: UiRect::all(px(5)),
border_radius: BorderRadius::MAX,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
DemoButton,
Button,
Hovered::default(),
TabIndex(0),
BorderColor::all(Color::BLACK),
BackgroundColor(NORMAL_BUTTON),
children![(
Text::new("Button"),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
TextShadow::default(),
)],
)
}
fn menu_button(asset_server: &AssetServer) -> impl Bundle {
(
Node { ..default() },
DemoMenuAnchor,
observe(on_menu_event),
children![(
Node {
width: px(200),
height: px(65),
border: UiRect::all(px(5)),
box_sizing: BoxSizing::BorderBox,
justify_content: JustifyContent::SpaceBetween,
align_items: AlignItems::Center,
padding: UiRect::axes(px(16), px(0)),
border_radius: BorderRadius::all(px(5)),
..default()
},
DemoMenuButton,
MenuButton,
Hovered::default(),
TabIndex(0),
BorderColor::all(Color::BLACK),
BackgroundColor(NORMAL_BUTTON),
children![
(
Text::new("Menu"),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
TextShadow::default(),
),
(
Node {
width: px(12),
height: px(12),
..default()
},
BackgroundColor(GRAY.into()),
)
],
)],
)
}
fn update_button_style(
mut buttons: Query<
(
Has<Pressed>,
&Hovered,
Has<InteractionDisabled>,
&mut BackgroundColor,
&mut BorderColor,
&Children,
),
(
Or<(
Changed<Pressed>,
Changed<Hovered>,
Added<InteractionDisabled>,
)>,
With<DemoButton>,
),
>,
mut text_query: Query<&mut Text>,
) {
for (pressed, hovered, disabled, mut color, mut border_color, children) in &mut buttons {
let mut text = text_query.get_mut(children[0]).unwrap();
set_button_style(
disabled,
hovered.get(),
pressed,
&mut color,
&mut border_color,
&mut text,
);
}
}
/// Supplementary system to detect removed marker components
fn update_button_style2(
mut buttons: Query<
(
Has<Pressed>,
&Hovered,
Has<InteractionDisabled>,
&mut BackgroundColor,
&mut BorderColor,
&Children,
),
With<DemoButton>,
>,
mut removed_depressed: RemovedComponents<Pressed>,
mut removed_disabled: RemovedComponents<InteractionDisabled>,
mut text_query: Query<&mut Text>,
) {
removed_depressed
.read()
.chain(removed_disabled.read())
.for_each(|entity| {
if let Ok((pressed, hovered, disabled, mut color, mut border_color, children)) =
buttons.get_mut(entity)
{
let mut text = text_query.get_mut(children[0]).unwrap();
set_button_style(
disabled,
hovered.get(),
pressed,
&mut color,
&mut border_color,
&mut text,
);
}
});
}
fn set_button_style(
disabled: bool,
hovered: bool,
pressed: bool,
color: &mut BackgroundColor,
border_color: &mut BorderColor,
text: &mut Text,
) {
match (disabled, hovered, pressed) {
// Disabled button
(true, _, _) => {
**text = "Disabled".to_string();
*color = NORMAL_BUTTON.into();
border_color.set_all(GRAY);
}
// Pressed and hovered button
(false, true, true) => {
**text = "Press".to_string();
*color = PRESSED_BUTTON.into();
border_color.set_all(RED);
}
// Hovered, unpressed button
(false, true, false) => {
**text = "Hover".to_string();
*color = HOVERED_BUTTON.into();
border_color.set_all(WHITE);
}
// Unhovered button (either pressed or not).
(false, false, _) => {
**text = "Button".to_string();
*color = NORMAL_BUTTON.into();
border_color.set_all(BLACK);
}
}
}
/// Create a demo slider
fn slider(min: f32, max: f32, value: f32) -> impl Bundle {
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Stretch,
justify_items: JustifyItems::Center,
column_gap: px(4),
height: px(12),
width: percent(30),
..default()
},
Name::new("Slider"),
Hovered::default(),
DemoSlider,
Slider {
track_click: TrackClick::Snap,
},
SliderValue(value),
SliderRange::new(min, max),
TabIndex(0),
Children::spawn((
// Slider background rail
Spawn((
Node {
height: px(6),
border_radius: BorderRadius::all(px(3)),
..default()
},
BackgroundColor(SLIDER_TRACK), // Border color for the slider
)),
// Invisible track to allow absolute placement of thumb entity. This is narrower than
// the actual slider, which allows us to position the thumb entity using simple
// percentages, without having to measure the actual width of the slider thumb.
Spawn((
Node {
display: Display::Flex,
position_type: PositionType::Absolute,
left: px(0),
// Track is short by 12px to accommodate the thumb.
right: px(12),
top: px(0),
bottom: px(0),
..default()
},
children![(
// Thumb
DemoSliderThumb,
SliderThumb,
Node {
display: Display::Flex,
width: px(12),
height: px(12),
position_type: PositionType::Absolute,
left: percent(0), // This will be updated by the slider's value
border_radius: BorderRadius::MAX,
..default()
},
BackgroundColor(SLIDER_THUMB),
)],
)),
)),
)
}
/// Update the visuals of the slider based on the slider state.
fn update_slider_style(
sliders: Query<
(
Entity,
&SliderValue,
&SliderRange,
&Hovered,
&CoreSliderDragState,
Has<InteractionDisabled>,
),
(
Or<(
Changed<SliderValue>,
Changed<SliderRange>,
Changed<Hovered>,
Changed<CoreSliderDragState>,
Added<InteractionDisabled>,
)>,
With<DemoSlider>,
),
>,
children: Query<&Children>,
mut thumbs: Query<(&mut Node, &mut BackgroundColor, Has<DemoSliderThumb>), Without<DemoSlider>>,
) {
for (slider_ent, value, range, hovered, drag_state, disabled) in sliders.iter() {
for child in children.iter_descendants(slider_ent) {
if let Ok((mut thumb_node, mut thumb_bg, is_thumb)) = thumbs.get_mut(child)
&& is_thumb
{
thumb_node.left = percent(range.thumb_position(value.0) * 100.0);
thumb_bg.0 = thumb_color(disabled, hovered.0 | drag_state.dragging);
}
}
}
}
fn update_slider_style2(
sliders: Query<
(
Entity,
&Hovered,
&CoreSliderDragState,
Has<InteractionDisabled>,
),
With<DemoSlider>,
>,
children: Query<&Children>,
mut thumbs: Query<(&mut BackgroundColor, Has<DemoSliderThumb>), Without<DemoSlider>>,
mut removed_disabled: RemovedComponents<InteractionDisabled>,
) {
removed_disabled.read().for_each(|entity| {
if let Ok((slider_ent, hovered, drag_state, disabled)) = sliders.get(entity) {
for child in children.iter_descendants(slider_ent) {
if let Ok((mut thumb_bg, is_thumb)) = thumbs.get_mut(child)
&& is_thumb
{
thumb_bg.0 = thumb_color(disabled, hovered.0 | drag_state.dragging);
}
}
}
});
}
fn thumb_color(disabled: bool, hovered: bool) -> Color {
match (disabled, hovered) {
(true, _) => ELEMENT_FILL_DISABLED,
(false, true) => SLIDER_THUMB.lighter(0.3),
_ => SLIDER_THUMB,
}
}
/// Create a demo checkbox
fn checkbox(asset_server: &AssetServer, caption: &str) -> impl Bundle {
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::FlexStart,
align_items: AlignItems::Center,
align_content: AlignContent::Center,
column_gap: px(4),
..default()
},
Name::new("Checkbox"),
Hovered::default(),
DemoCheckbox,
Checkbox,
TabIndex(0),
Children::spawn((
Spawn((
// Checkbox outer
Node {
display: Display::Flex,
width: px(16),
height: px(16),
border: UiRect::all(px(2)),
border_radius: BorderRadius::all(px(3)),
..default()
},
BorderColor::all(ELEMENT_OUTLINE), // Border color for the checkbox
children![
// Checkbox inner
(
Node {
display: Display::Flex,
width: px(8),
height: px(8),
position_type: PositionType::Absolute,
left: px(2),
top: px(2),
..default()
},
BackgroundColor(ELEMENT_FILL),
),
],
)),
Spawn((
Text::new(caption),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 20.0,
..default()
},
)),
)),
)
}
// Update the element's styles.
fn update_checkbox_or_radio_style(
mut q_checkbox: Query<
(Has<Checked>, &Hovered, Has<InteractionDisabled>, &Children),
(
Or<(With<DemoCheckbox>, With<DemoRadio>)>,
Or<(
Added<DemoCheckbox>,
Changed<Hovered>,
Added<Checked>,
Added<InteractionDisabled>,
)>,
),
>,
mut q_border_color: Query<
(&mut BorderColor, &mut Children),
(Without<DemoCheckbox>, Without<DemoRadio>),
>,
mut q_bg_color: Query<&mut BackgroundColor, (Without<DemoCheckbox>, Without<Children>)>,
) {
for (checked, Hovered(is_hovering), is_disabled, children) in q_checkbox.iter_mut() {
let Some(border_id) = children.first() else {
continue;
};
let Ok((mut border_color, border_children)) = q_border_color.get_mut(*border_id) else {
continue;
};
let Some(mark_id) = border_children.first() else {
warn!("Checkbox does not have a mark entity.");
continue;
};
let Ok(mut mark_bg) = q_bg_color.get_mut(*mark_id) else {
warn!("Checkbox mark entity lacking a background color.");
continue;
};
set_checkbox_or_radio_style(
is_disabled,
*is_hovering,
checked,
&mut border_color,
&mut mark_bg,
);
}
}
fn update_checkbox_or_radio_style2(
mut q_checkbox: Query<
(Has<Checked>, &Hovered, Has<InteractionDisabled>, &Children),
Or<(With<DemoCheckbox>, With<DemoRadio>)>,
>,
mut q_border_color: Query<
(&mut BorderColor, &mut Children),
(Without<DemoCheckbox>, Without<DemoRadio>),
>,
mut q_bg_color: Query<
&mut BackgroundColor,
(Without<DemoCheckbox>, Without<DemoRadio>, Without<Children>),
>,
mut removed_checked: RemovedComponents<Checked>,
mut removed_disabled: RemovedComponents<InteractionDisabled>,
) {
removed_checked
.read()
.chain(removed_disabled.read())
.for_each(|entity| {
if let Ok((checked, Hovered(is_hovering), is_disabled, children)) =
q_checkbox.get_mut(entity)
{
let Some(border_id) = children.first() else {
return;
};
let Ok((mut border_color, border_children)) = q_border_color.get_mut(*border_id)
else {
return;
};
let Some(mark_id) = border_children.first() else {
warn!("Checkbox does not have a mark entity.");
return;
};
let Ok(mut mark_bg) = q_bg_color.get_mut(*mark_id) else {
warn!("Checkbox mark entity lacking a background color.");
return;
};
set_checkbox_or_radio_style(
is_disabled,
*is_hovering,
checked,
&mut border_color,
&mut mark_bg,
);
}
});
}
fn set_checkbox_or_radio_style(
disabled: bool,
hovering: bool,
checked: bool,
border_color: &mut BorderColor,
mark_bg: &mut BackgroundColor,
) {
let color: Color = if disabled {
// If the element is disabled, use a lighter color
ELEMENT_OUTLINE.with_alpha(0.2)
} else if hovering {
// If hovering, use a lighter color
ELEMENT_OUTLINE.lighter(0.2)
} else {
// Default color for the element
ELEMENT_OUTLINE
};
// Update the background color of the element
border_color.set_all(color);
let mark_color: Color = match (disabled, checked) {
(true, true) => ELEMENT_FILL_DISABLED,
(false, true) => ELEMENT_FILL,
(_, false) => Srgba::NONE.into(),
};
if mark_bg.0 != mark_color {
// Update the color of the element
mark_bg.0 = mark_color;
}
}
/// Create a demo radio group
fn radio_group(asset_server: &AssetServer) -> impl Bundle {
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Column,
align_items: AlignItems::Start,
column_gap: px(4),
..default()
},
Name::new("RadioGroup"),
RadioGroup,
TabIndex::default(),
children![
(radio(asset_server, TrackClick::Drag, "Slider Drag"),),
(radio(asset_server, TrackClick::Step, "Slider Step"),),
(radio(asset_server, TrackClick::Snap, "Slider Snap"),)
],
)
}
/// Create a demo radio button
fn radio(asset_server: &AssetServer, value: TrackClick, caption: &str) -> impl Bundle {
(
Node {
display: Display::Flex,
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::FlexStart,
align_items: AlignItems::Center,
align_content: AlignContent::Center,
column_gap: px(4),
..default()
},
Name::new("RadioButton"),
Hovered::default(),
DemoRadio(value),
RadioButton,
Children::spawn((
Spawn((
// Radio outer
Node {
display: Display::Flex,
width: px(16),
height: px(16),
border: UiRect::all(px(2)),
border_radius: BorderRadius::MAX,
..default()
},
BorderColor::all(ELEMENT_OUTLINE), // Border color for the radio button
children![
// Radio inner
(
Node {
display: Display::Flex,
width: px(8),
height: px(8),
position_type: PositionType::Absolute,
left: px(2),
top: px(2),
border_radius: BorderRadius::MAX,
..default()
},
BackgroundColor(ELEMENT_FILL),
),
],
)),
Spawn((
Text::new(caption),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 20.0,
..default()
},
)),
)),
)
}
fn on_menu_event(
menu_event: On<MenuEvent>,
q_anchor: Single<(Entity, &Children), With<DemoMenuAnchor>>,
q_popup: Query<Entity, With<MenuPopup>>,
assets: Res<AssetServer>,
mut focus: ResMut<InputFocus>,
mut commands: Commands,
) {
let (anchor, children) = q_anchor.into_inner();
let popup = children.iter().find_map(|c| q_popup.get(c).ok());
info!("Menu action: {:?}", menu_event.action);
match menu_event.action {
MenuAction::Open => {
if popup.is_none() {
spawn_menu(anchor, assets, commands);
}
}
MenuAction::Toggle => match popup {
Some(popup) => commands.entity(popup).despawn(),
None => spawn_menu(anchor, assets, commands),
},
MenuAction::Close | MenuAction::CloseAll => {
if let Some(popup) = popup {
commands.entity(popup).despawn();
}
}
MenuAction::FocusRoot => {
focus.0 = Some(anchor);
}
}
}
fn spawn_menu(anchor: Entity, assets: Res<AssetServer>, mut commands: Commands) {
let menu = commands
.spawn((
Node {
display: Display::Flex,
flex_direction: FlexDirection::Column,
min_height: px(10.),
min_width: Val::Percent(100.),
border: UiRect::all(px(1)),
position_type: PositionType::Absolute,
..default()
},
MenuPopup::default(),
Visibility::Hidden, // Will be visible after positioning
BorderColor::all(GREEN),
BackgroundColor(GRAY.into()),
BoxShadow::new(
Srgba::BLACK.with_alpha(0.9).into(),
px(0),
px(0),
px(1),
px(4),
),
GlobalZIndex(100),
Popover {
positions: vec![
PopoverPlacement {
side: PopoverSide::Bottom,
align: PopoverAlign::Start,
gap: 2.0,
},
PopoverPlacement {
side: PopoverSide::Top,
align: PopoverAlign::Start,
gap: 2.0,
},
],
window_margin: 10.0,
},
OverrideClip,
children![
menu_item(&assets),
menu_item(&assets),
menu_item(&assets),
menu_item(&assets)
],
))
.id();
commands.entity(anchor).add_child(menu);
}
fn menu_item(asset_server: &AssetServer) -> impl Bundle {
(
Node {
padding: UiRect::axes(px(8), px(2)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Start,
..default()
},
DemoMenuItem,
MenuItem,
Hovered::default(),
TabIndex(0),
BackgroundColor(NORMAL_BUTTON),
children![(
Text::new("Menu Item"),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
TextShadow::default(),
)],
)
}
fn update_menu_item_style(
mut buttons: Query<
(
Has<Pressed>,
&Hovered,
Has<InteractionDisabled>,
&mut BackgroundColor,
),
(
Or<(
Changed<Pressed>,
Changed<Hovered>,
Added<InteractionDisabled>,
)>,
With<DemoMenuItem>,
),
>,
) {
for (pressed, hovered, disabled, mut color) in &mut buttons {
set_menu_item_style(disabled, hovered.get(), pressed, &mut color);
}
}
/// Supplementary system to detect removed marker components
fn update_menu_item_style2(
mut buttons: Query<
(
Has<Pressed>,
&Hovered,
Has<InteractionDisabled>,
&mut BackgroundColor,
),
With<DemoMenuItem>,
>,
mut removed_depressed: RemovedComponents<Pressed>,
mut removed_disabled: RemovedComponents<InteractionDisabled>,
) {
removed_depressed
.read()
.chain(removed_disabled.read())
.for_each(|entity| {
if let Ok((pressed, hovered, disabled, mut color)) = buttons.get_mut(entity) {
set_menu_item_style(disabled, hovered.get(), pressed, &mut color);
}
});
}
fn set_menu_item_style(disabled: bool, hovered: bool, pressed: bool, color: &mut BackgroundColor) {
match (disabled, hovered, pressed) {
// Pressed and hovered menu item
(false, true, true) => {
*color = PRESSED_BUTTON.into();
}
// Hovered, unpressed menu item
(false, true, false) => {
*color = HOVERED_BUTTON.into();
}
// Unhovered menu item (either pressed or not).
_ => {
*color = NORMAL_BUTTON.into();
}
}
}
fn toggle_disabled(
input: Res<ButtonInput<KeyCode>>,
mut interaction_query: Query<
(Entity, Has<InteractionDisabled>),
Or<(
With<Button>,
With<MenuButton>,
With<Slider>,
With<Checkbox>,
With<RadioButton>,
)>,
>,
mut commands: Commands,
) {
if input.just_pressed(KeyCode::KeyD) {
for (entity, disabled) in &mut interaction_query {
if disabled {
info!("Widget enabled");
commands.entity(entity).remove::<InteractionDisabled>();
} else {
info!("Widget disabled");
commands.entity(entity).insert(InteractionDisabled);
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/directional_navigation.rs | examples/ui/directional_navigation.rs | //! Demonstrates how to set up the directional navigation system to allow for navigation between widgets.
//!
//! Directional navigation is generally used to move between widgets in a user interface using arrow keys or gamepad input.
//! When compared to tab navigation, directional navigation is generally more direct, and less aware of the structure of the UI.
//!
//! In this example, we will set up a simple UI with a grid of buttons that can be navigated using the arrow keys or gamepad input.
//!
//! **Note:** This example shows manual graph construction for full control. For automatic graph generation
//! based on node positions, see the `auto_directional_navigation` example.
use std::time::Duration;
use bevy::{
camera::NormalizedRenderTarget,
input_focus::{
directional_navigation::{
DirectionalNavigation, DirectionalNavigationMap, DirectionalNavigationPlugin,
},
InputDispatchPlugin, InputFocus, InputFocusVisible,
},
math::CompassOctant,
picking::{
backend::HitData,
pointer::{Location, PointerId},
},
platform::collections::{HashMap, HashSet},
prelude::*,
};
fn main() {
App::new()
// Input focus is not enabled by default, so we need to add the corresponding plugins
.add_plugins((
DefaultPlugins,
InputDispatchPlugin,
DirectionalNavigationPlugin,
))
// This resource is canonically used to track whether or not to render a focus indicator
// It starts as false, but we set it to true here as we would like to see the focus indicator
.insert_resource(InputFocusVisible(true))
// We've made a simple resource to keep track of the actions that are currently being pressed for this example
.init_resource::<ActionState>()
.add_systems(Startup, setup_ui)
// Input is generally handled during PreUpdate
// We're turning inputs into actions first, then using those actions to determine navigation
.add_systems(PreUpdate, (process_inputs, navigate).chain())
.add_systems(
Update,
(
// We need to show which button is currently focused
highlight_focused_element,
// Pressing the "Interact" button while we have a focused element should simulate a click
interact_with_focused_button,
// We're doing a tiny animation when the button is interacted with,
// so we need a timer and a polling mechanism to reset it
reset_button_after_interaction,
),
)
// This observer is added globally, so it will respond to *any* trigger of the correct type.
// However, we're filtering in the observer's query to only respond to button presses
.add_observer(universal_button_click_behavior)
.run();
}
const NORMAL_BUTTON: Srgba = bevy::color::palettes::tailwind::BLUE_400;
const PRESSED_BUTTON: Srgba = bevy::color::palettes::tailwind::BLUE_500;
const FOCUSED_BORDER: Srgba = bevy::color::palettes::tailwind::BLUE_50;
// This observer will be triggered whenever a button is pressed
// In a real project, each button would also have its own unique behavior,
// to capture the actual intent of the user
fn universal_button_click_behavior(
mut click: On<Pointer<Click>>,
mut button_query: Query<(&mut BackgroundColor, &mut ResetTimer)>,
) {
let button_entity = click.entity;
if let Ok((mut color, mut reset_timer)) = button_query.get_mut(button_entity) {
// This would be a great place to play a little sound effect too!
color.0 = PRESSED_BUTTON.into();
reset_timer.0 = Timer::from_seconds(0.3, TimerMode::Once);
// Picking events propagate up the hierarchy,
// so we need to stop the propagation here now that we've handled it
click.propagate(false);
}
}
/// Resets a UI element to its default state when the timer has elapsed.
#[derive(Component, Default, Deref, DerefMut)]
struct ResetTimer(Timer);
fn reset_button_after_interaction(
time: Res<Time>,
mut query: Query<(&mut ResetTimer, &mut BackgroundColor)>,
) {
for (mut reset_timer, mut color) in query.iter_mut() {
reset_timer.tick(time.delta());
if reset_timer.just_finished() {
color.0 = NORMAL_BUTTON.into();
}
}
}
// We're spawning a simple grid of buttons and some instructions
// The buttons are just colored rectangles with text displaying the button's name
fn setup_ui(
mut commands: Commands,
mut directional_nav_map: ResMut<DirectionalNavigationMap>,
mut input_focus: ResMut<InputFocus>,
) {
const N_ROWS: u16 = 5;
const N_COLS: u16 = 3;
// Rendering UI elements requires a camera
commands.spawn(Camera2d);
// Create a full-screen background node
let root_node = commands
.spawn(Node {
width: percent(100),
height: percent(100),
..default()
})
.id();
// Add instruction to the left of the grid
let instructions = commands
.spawn((
Text::new("Use arrow keys or D-pad to navigate. \
Click the buttons, or press Enter / the South gamepad button to interact with the focused button."),
Node {
width: px(300),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
margin: UiRect::all(px(12)),
..default()
},
))
.id();
// Set up the root entity to hold the grid
let grid_root_entity = commands
.spawn(Node {
display: Display::Grid,
// Allow the grid to take up the full height and the rest of the width of the window
width: percent(100),
height: percent(100),
// Set the number of rows and columns in the grid
// allowing the grid to automatically size the cells
grid_template_columns: RepeatedGridTrack::auto(N_COLS),
grid_template_rows: RepeatedGridTrack::auto(N_ROWS),
..default()
})
.id();
// Add the instructions and grid to the root node
commands
.entity(root_node)
.add_children(&[instructions, grid_root_entity]);
let mut button_entities: HashMap<(u16, u16), Entity> = HashMap::default();
for row in 0..N_ROWS {
for col in 0..N_COLS {
let button_name = format!("Button {row}-{col}");
let button_entity = commands
.spawn((
Button,
Node {
width: px(200),
height: px(120),
// Add a border so we can show which element is focused
border: UiRect::all(px(4)),
// Center the button's text label
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
// Center the button within the grid cell
align_self: AlignSelf::Center,
justify_self: JustifySelf::Center,
border_radius: BorderRadius::all(px(16)),
..default()
},
ResetTimer::default(),
BackgroundColor::from(NORMAL_BUTTON),
Name::new(button_name.clone()),
))
// Add a text element to the button
.with_child((
Text::new(button_name),
// And center the text if it flows onto multiple lines
TextLayout {
justify: Justify::Center,
..default()
},
))
.id();
// Add the button to the grid
commands.entity(grid_root_entity).add_child(button_entity);
// Keep track of the button entities so we can set up our navigation graph
button_entities.insert((row, col), button_entity);
}
}
// Connect all of the buttons in the same row to each other,
// looping around when the edge is reached.
for row in 0..N_ROWS {
let entities_in_row: Vec<Entity> = (0..N_COLS)
.map(|col| button_entities.get(&(row, col)).unwrap())
.copied()
.collect();
directional_nav_map.add_looping_edges(&entities_in_row, CompassOctant::East);
}
// Connect all of the buttons in the same column to each other,
// but don't loop around when the edge is reached.
// While looping is a very reasonable choice, we're not doing it here to demonstrate the different options.
for col in 0..N_COLS {
let entities_in_column: Vec<Entity> = (0..N_ROWS)
.map(|row| button_entities.get(&(row, col)).unwrap())
.copied()
.collect();
directional_nav_map.add_edges(&entities_in_column, CompassOctant::South);
}
// When changing scenes, remember to set an initial focus!
let top_left_entity = *button_entities.get(&(0, 0)).unwrap();
input_focus.set(top_left_entity);
}
// The indirection between inputs and actions allows us to easily remap inputs
// and handle multiple input sources (keyboard, gamepad, etc.) in our game
#[derive(Debug, PartialEq, Eq, Hash)]
enum DirectionalNavigationAction {
Up,
Down,
Left,
Right,
Select,
}
impl DirectionalNavigationAction {
fn variants() -> Vec<Self> {
vec![
DirectionalNavigationAction::Up,
DirectionalNavigationAction::Down,
DirectionalNavigationAction::Left,
DirectionalNavigationAction::Right,
DirectionalNavigationAction::Select,
]
}
fn keycode(&self) -> KeyCode {
match self {
DirectionalNavigationAction::Up => KeyCode::ArrowUp,
DirectionalNavigationAction::Down => KeyCode::ArrowDown,
DirectionalNavigationAction::Left => KeyCode::ArrowLeft,
DirectionalNavigationAction::Right => KeyCode::ArrowRight,
DirectionalNavigationAction::Select => KeyCode::Enter,
}
}
fn gamepad_button(&self) -> GamepadButton {
match self {
DirectionalNavigationAction::Up => GamepadButton::DPadUp,
DirectionalNavigationAction::Down => GamepadButton::DPadDown,
DirectionalNavigationAction::Left => GamepadButton::DPadLeft,
DirectionalNavigationAction::Right => GamepadButton::DPadRight,
// This is the "A" button on an Xbox controller,
// and is conventionally used as the "Select" / "Interact" button in many games
DirectionalNavigationAction::Select => GamepadButton::South,
}
}
}
// This keeps track of the inputs that are currently being pressed
#[derive(Default, Resource)]
struct ActionState {
pressed_actions: HashSet<DirectionalNavigationAction>,
}
fn process_inputs(
mut action_state: ResMut<ActionState>,
keyboard_input: Res<ButtonInput<KeyCode>>,
gamepad_input: Query<&Gamepad>,
) {
// Reset the set of pressed actions each frame
// to ensure that we only process each action once
action_state.pressed_actions.clear();
for action in DirectionalNavigationAction::variants() {
// Use just_pressed to ensure that we only process each action once
// for each time it is pressed
if keyboard_input.just_pressed(action.keycode()) {
action_state.pressed_actions.insert(action);
}
}
// We're treating this like a single-player game:
// if multiple gamepads are connected, we don't care which one is being used
for gamepad in gamepad_input.iter() {
for action in DirectionalNavigationAction::variants() {
// Unlike keyboard input, gamepads are bound to a specific controller
if gamepad.just_pressed(action.gamepad_button()) {
action_state.pressed_actions.insert(action);
}
}
}
}
fn navigate(action_state: Res<ActionState>, mut directional_navigation: DirectionalNavigation) {
// If the user is pressing both left and right, or up and down,
// we should not move in either direction.
let net_east_west = action_state
.pressed_actions
.contains(&DirectionalNavigationAction::Right) as i8
- action_state
.pressed_actions
.contains(&DirectionalNavigationAction::Left) as i8;
let net_north_south = action_state
.pressed_actions
.contains(&DirectionalNavigationAction::Up) as i8
- action_state
.pressed_actions
.contains(&DirectionalNavigationAction::Down) as i8;
// Compute the direction that the user is trying to navigate in
let maybe_direction = match (net_east_west, net_north_south) {
(0, 0) => None,
(0, 1) => Some(CompassOctant::North),
(1, 1) => Some(CompassOctant::NorthEast),
(1, 0) => Some(CompassOctant::East),
(1, -1) => Some(CompassOctant::SouthEast),
(0, -1) => Some(CompassOctant::South),
(-1, -1) => Some(CompassOctant::SouthWest),
(-1, 0) => Some(CompassOctant::West),
(-1, 1) => Some(CompassOctant::NorthWest),
_ => None,
};
if let Some(direction) = maybe_direction {
match directional_navigation.navigate(direction) {
// In a real game, you would likely want to play a sound or show a visual effect
// on both successful and unsuccessful navigation attempts
Ok(entity) => {
println!("Navigated {direction:?} successfully. {entity} is now focused.");
}
Err(e) => println!("Navigation failed: {e}"),
}
}
}
fn highlight_focused_element(
input_focus: Res<InputFocus>,
// While this isn't strictly needed for the example,
// we're demonstrating how to be a good citizen by respecting the `InputFocusVisible` resource.
input_focus_visible: Res<InputFocusVisible>,
mut query: Query<(Entity, &mut BorderColor)>,
) {
for (entity, mut border_color) in query.iter_mut() {
if input_focus.0 == Some(entity) && input_focus_visible.0 {
// Don't change the border size / radius here,
// as it would result in wiggling buttons when they are focused
*border_color = BorderColor::all(FOCUSED_BORDER);
} else {
*border_color = BorderColor::DEFAULT;
}
}
}
// By sending a Pointer<Click> trigger rather than directly handling button-like interactions,
// we can unify our handling of pointer and keyboard/gamepad interactions
fn interact_with_focused_button(
action_state: Res<ActionState>,
input_focus: Res<InputFocus>,
mut commands: Commands,
) {
if action_state
.pressed_actions
.contains(&DirectionalNavigationAction::Select)
&& let Some(focused_entity) = input_focus.0
{
commands.trigger(Pointer::<Click> {
entity: focused_entity,
// We're pretending that we're a mouse
pointer_id: PointerId::Mouse,
// This field isn't used, so we're just setting it to a placeholder value
pointer_location: Location {
target: NormalizedRenderTarget::None {
width: 0,
height: 0,
},
position: Vec2::ZERO,
},
event: Click {
button: PointerButton::Primary,
// This field isn't used, so we're just setting it to a placeholder value
hit: HitData {
camera: Entity::PLACEHOLDER,
depth: 0.0,
position: None,
normal: None,
},
duration: Duration::from_secs_f32(0.1),
},
});
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/tab_navigation.rs | examples/ui/tab_navigation.rs | //! This example illustrates the use of tab navigation.
use bevy::{
color::palettes::basic::*,
input_focus::{
tab_navigation::{TabGroup, TabIndex, TabNavigationPlugin},
InputDispatchPlugin, InputFocus,
},
prelude::*,
};
fn main() {
App::new()
.add_plugins((DefaultPlugins, InputDispatchPlugin, TabNavigationPlugin))
.add_systems(Startup, setup)
.add_systems(Update, (button_system, focus_system))
.run();
}
const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
fn button_system(
mut interaction_query: Query<
(&Interaction, &mut BackgroundColor, &mut BorderColor),
(Changed<Interaction>, With<Button>),
>,
) {
for (interaction, mut color, mut border_color) in &mut interaction_query {
match *interaction {
Interaction::Pressed => {
*color = PRESSED_BUTTON.into();
*border_color = BorderColor::all(RED);
}
Interaction::Hovered => {
*color = HOVERED_BUTTON.into();
*border_color = BorderColor::all(Color::WHITE);
}
Interaction::None => {
*color = NORMAL_BUTTON.into();
*border_color = BorderColor::all(Color::BLACK);
}
}
}
}
fn focus_system(
mut commands: Commands,
focus: Res<InputFocus>,
mut query: Query<Entity, With<Button>>,
) {
if focus.is_changed() {
for button in query.iter_mut() {
if focus.0 == Some(button) {
commands.entity(button).insert(Outline {
color: Color::WHITE,
width: px(2),
offset: px(2),
});
} else {
commands.entity(button).remove::<Outline>();
}
}
}
}
fn setup(mut commands: Commands) {
// ui camera
commands.spawn(Camera2d);
commands
.spawn(Node {
width: percent(100),
height: percent(100),
display: Display::Flex,
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
row_gap: px(6),
..default()
})
.observe(
|mut event: On<Pointer<Click>>, mut focus: ResMut<InputFocus>| {
focus.0 = None;
event.propagate(false);
},
)
.with_children(|parent| {
for (label, tab_group, indices) in [
// In this group all the buttons have the same `TabIndex` so they will be visited according to their order as children.
("TabGroup 0", TabGroup::new(0), [0, 0, 0, 0]),
// In this group the `TabIndex`s are reversed so the buttons will be visited in right-to-left order.
("TabGroup 2", TabGroup::new(2), [3, 2, 1, 0]),
// In this group the orders of the indices and buttons match so the buttons will be visited in left-to-right order.
("TabGroup 1", TabGroup::new(1), [0, 1, 2, 3]),
// Visit the modal group's buttons in an arbitrary order.
("Modal TabGroup", TabGroup::modal(), [0, 3, 1, 2]),
] {
parent.spawn(Text::new(label));
parent
.spawn((
Node {
display: Display::Flex,
flex_direction: FlexDirection::Row,
column_gap: px(6),
margin: UiRect {
bottom: px(10),
..default()
},
..default()
},
tab_group,
))
.with_children(|parent| {
for i in indices {
parent
.spawn((
Button,
Node {
width: px(200),
height: px(65),
border: UiRect::all(px(5)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BorderColor::all(Color::BLACK),
BackgroundColor(NORMAL_BUTTON),
TabIndex(i),
children![(
Text::new(format!("TabIndex {i}")),
TextFont {
font_size: 20.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
)],
))
.observe(
|mut click: On<Pointer<Click>>,
mut focus: ResMut<InputFocus>| {
focus.0 = Some(click.entity);
click.propagate(false);
},
);
}
});
}
});
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/display_and_visibility.rs | examples/ui/display_and_visibility.rs | //! Demonstrates how Display and Visibility work in the UI.
use bevy::{
color::palettes::css::{DARK_CYAN, DARK_GRAY, YELLOW},
ecs::{component::Mutable, hierarchy::ChildSpawnerCommands},
prelude::*,
};
const PALETTE: [&str; 4] = ["27496D", "466B7A", "669DB3", "ADCBE3"];
const HIDDEN_COLOR: Color = Color::srgb(1.0, 0.7, 0.7);
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(
Update,
(
buttons_handler::<Display>,
buttons_handler::<Visibility>,
text_hover,
),
)
.run();
}
#[derive(Component)]
struct Target<T> {
id: Entity,
phantom: std::marker::PhantomData<T>,
}
impl<T> Target<T> {
fn new(id: Entity) -> Self {
Self {
id,
phantom: std::marker::PhantomData,
}
}
}
trait TargetUpdate {
type TargetComponent: Component<Mutability = Mutable>;
const NAME: &'static str;
fn update_target(&self, target: &mut Self::TargetComponent) -> String;
}
impl TargetUpdate for Target<Display> {
type TargetComponent = Node;
const NAME: &'static str = "Display";
fn update_target(&self, node: &mut Self::TargetComponent) -> String {
node.display = match node.display {
Display::Flex => Display::None,
Display::None => Display::Flex,
Display::Block | Display::Grid => unreachable!(),
};
format!("{}::{:?} ", Self::NAME, node.display)
}
}
impl TargetUpdate for Target<Visibility> {
type TargetComponent = Visibility;
const NAME: &'static str = "Visibility";
fn update_target(&self, visibility: &mut Self::TargetComponent) -> String {
*visibility = match *visibility {
Visibility::Inherited => Visibility::Visible,
Visibility::Visible => Visibility::Hidden,
Visibility::Hidden => Visibility::Inherited,
};
format!("{}::{visibility:?}", Self::NAME)
}
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let palette: [Color; 4] = PALETTE.map(|hex| Srgba::hex(hex).unwrap().into());
let text_font = TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
..default()
};
commands.spawn(Camera2d);
commands
.spawn((
Node {
width: percent(100),
height: percent(100),
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
justify_content: JustifyContent::SpaceEvenly,
..Default::default()
},
BackgroundColor(Color::BLACK),
))
.with_children(|parent| {
parent.spawn((
Text::new("Use the panel on the right to change the Display and Visibility properties for the respective nodes of the panel on the left"),
text_font.clone(),
TextLayout::new_with_justify(Justify::Center),
Node {
margin: UiRect::bottom(px(10)),
..Default::default()
},
));
parent
.spawn(Node {
width: percent(100),
..default()
})
.with_children(|parent| {
let mut target_ids = vec![];
parent
.spawn(Node {
width: percent(50),
height: px(520),
justify_content: JustifyContent::Center,
..default()
})
.with_children(|parent| {
target_ids = spawn_left_panel(parent, &palette);
});
parent
.spawn(Node {
width: percent(50),
justify_content: JustifyContent::Center,
..default()
})
.with_children(|parent| {
spawn_right_panel(parent, text_font, &palette, target_ids);
});
});
parent
.spawn(Node {
flex_direction: FlexDirection::Row,
align_items: AlignItems::Start,
justify_content: JustifyContent::Start,
column_gap: px(10),
..default()
})
.with_children(|builder| {
let text_font = TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
..default()
};
builder.spawn((
Text::new("Display::None\nVisibility::Hidden\nVisibility::Inherited"),
text_font.clone(),
TextColor(HIDDEN_COLOR),
TextLayout::new_with_justify(Justify::Center),
));
builder.spawn((
Text::new("-\n-\n-"),
text_font.clone(),
TextColor(DARK_GRAY.into()),
TextLayout::new_with_justify(Justify::Center),
));
builder.spawn((Text::new("The UI Node and its descendants will not be visible and will not be allotted any space in the UI layout.\nThe UI Node will not be visible but will still occupy space in the UI layout.\nThe UI node will inherit the visibility property of its parent. If it has no parent it will be visible."), text_font));
});
});
}
fn spawn_left_panel(builder: &mut ChildSpawnerCommands, palette: &[Color; 4]) -> Vec<Entity> {
let mut target_ids = vec![];
builder
.spawn((
Node {
padding: UiRect::all(px(10)),
..default()
},
BackgroundColor(Color::WHITE),
))
.with_children(|parent| {
parent
.spawn((Node::default(), BackgroundColor(Color::BLACK)))
.with_children(|parent| {
let id = parent
.spawn((
Node {
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::FlexEnd,
..default()
},
BackgroundColor(palette[0]),
Outline {
width: px(4),
color: DARK_CYAN.into(),
offset: px(10),
},
))
.with_children(|parent| {
parent.spawn(Node {
width: px(100),
height: px(500),
..default()
});
let id = parent
.spawn((
Node {
height: px(400),
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::FlexEnd,
..default()
},
BackgroundColor(palette[1]),
))
.with_children(|parent| {
parent.spawn(Node {
width: px(100),
height: px(400),
..default()
});
let id = parent
.spawn((
Node {
height: px(300),
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::FlexEnd,
..default()
},
BackgroundColor(palette[2]),
))
.with_children(|parent| {
parent.spawn(Node {
width: px(100),
height: px(300),
..default()
});
let id = parent
.spawn((
Node {
width: px(200),
height: px(200),
..default()
},
BackgroundColor(palette[3]),
))
.id();
target_ids.push(id);
})
.id();
target_ids.push(id);
})
.id();
target_ids.push(id);
})
.id();
target_ids.push(id);
});
});
target_ids
}
fn spawn_right_panel(
parent: &mut ChildSpawnerCommands,
text_font: TextFont,
palette: &[Color; 4],
mut target_ids: Vec<Entity>,
) {
let spawn_buttons = |parent: &mut ChildSpawnerCommands, target_id| {
spawn_button::<Display>(parent, text_font.clone(), target_id);
spawn_button::<Visibility>(parent, text_font.clone(), target_id);
};
parent
.spawn((
Node {
padding: UiRect::all(px(10)),
..default()
},
BackgroundColor(Color::WHITE),
))
.with_children(|parent| {
parent
.spawn((
Node {
width: px(500),
height: px(500),
flex_direction: FlexDirection::Column,
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::SpaceBetween,
padding: UiRect {
left: px(5),
top: px(5),
..default()
},
..default()
},
BackgroundColor(palette[0]),
Outline {
width: px(4),
color: DARK_CYAN.into(),
offset: px(10),
},
))
.with_children(|parent| {
spawn_buttons(parent, target_ids.pop().unwrap());
parent
.spawn((
Node {
width: px(400),
height: px(400),
flex_direction: FlexDirection::Column,
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::SpaceBetween,
padding: UiRect {
left: px(5),
top: px(5),
..default()
},
..default()
},
BackgroundColor(palette[1]),
))
.with_children(|parent| {
spawn_buttons(parent, target_ids.pop().unwrap());
parent
.spawn((
Node {
width: px(300),
height: px(300),
flex_direction: FlexDirection::Column,
align_items: AlignItems::FlexEnd,
justify_content: JustifyContent::SpaceBetween,
padding: UiRect {
left: px(5),
top: px(5),
..default()
},
..default()
},
BackgroundColor(palette[2]),
))
.with_children(|parent| {
spawn_buttons(parent, target_ids.pop().unwrap());
parent
.spawn((
Node {
width: px(200),
height: px(200),
align_items: AlignItems::FlexStart,
justify_content: JustifyContent::SpaceBetween,
flex_direction: FlexDirection::Column,
padding: UiRect {
left: px(5),
top: px(5),
..default()
},
..default()
},
BackgroundColor(palette[3]),
))
.with_children(|parent| {
spawn_buttons(parent, target_ids.pop().unwrap());
parent.spawn(Node {
width: px(100),
height: px(100),
..default()
});
});
});
});
});
});
}
fn spawn_button<T>(parent: &mut ChildSpawnerCommands, text_font: TextFont, target: Entity)
where
T: Default + std::fmt::Debug + Send + Sync + 'static,
Target<T>: TargetUpdate,
{
parent
.spawn((
Button,
Node {
align_self: AlignSelf::FlexStart,
padding: UiRect::axes(px(5), px(1)),
..default()
},
BackgroundColor(Color::BLACK.with_alpha(0.5)),
Target::<T>::new(target),
))
.with_children(|builder| {
builder.spawn((
Text(format!("{}::{:?}", Target::<T>::NAME, T::default())),
text_font,
TextLayout::new_with_justify(Justify::Center),
));
});
}
fn buttons_handler<T>(
mut left_panel_query: Query<&mut <Target<T> as TargetUpdate>::TargetComponent>,
mut visibility_button_query: Query<(&Target<T>, &Interaction, &Children), Changed<Interaction>>,
mut text_query: Query<(&mut Text, &mut TextColor)>,
) where
T: Send + Sync,
Target<T>: TargetUpdate + Component,
{
for (target, interaction, children) in visibility_button_query.iter_mut() {
if matches!(interaction, Interaction::Pressed) {
let mut target_value = left_panel_query.get_mut(target.id).unwrap();
for &child in children {
if let Ok((mut text, mut text_color)) = text_query.get_mut(child) {
**text = target.update_target(target_value.as_mut());
text_color.0 = if text.contains("None") || text.contains("Hidden") {
Color::srgb(1.0, 0.7, 0.7)
} else {
Color::WHITE
};
}
}
}
}
}
fn text_hover(
mut button_query: Query<(&Interaction, &mut BackgroundColor, &Children), Changed<Interaction>>,
mut text_query: Query<(&Text, &mut TextColor)>,
) {
for (interaction, mut color, children) in button_query.iter_mut() {
match interaction {
Interaction::Hovered => {
*color = Color::BLACK.with_alpha(0.6).into();
for &child in children {
if let Ok((_, mut text_color)) = text_query.get_mut(child) {
// Bypass change detection to avoid recomputation of the text when only changing the color
text_color.bypass_change_detection().0 = YELLOW.into();
}
}
}
_ => {
*color = Color::BLACK.with_alpha(0.5).into();
for &child in children {
if let Ok((text, mut text_color)) = text_query.get_mut(child) {
text_color.bypass_change_detection().0 =
if text.contains("None") || text.contains("Hidden") {
HIDDEN_COLOR
} else {
Color::WHITE
};
}
}
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/transparency_ui.rs | examples/ui/transparency_ui.rs | //! Demonstrates how to use transparency with UI.
//! Shows two colored buttons with transparent text.
use bevy::prelude::*;
fn main() {
App::new()
.insert_resource(ClearColor(Color::BLACK))
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let font_handle = FontSource::from(asset_server.load("fonts/FiraSans-Bold.ttf"));
commands
.spawn(Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Center,
justify_content: JustifyContent::SpaceAround,
..default()
})
.with_children(|parent| {
parent
.spawn((
Button,
Node {
width: px(150),
height: px(65),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::srgb(0.1, 0.5, 0.1)),
))
.with_children(|parent| {
parent.spawn((
Text::new("Button 1"),
TextFont {
font: font_handle.clone(),
font_size: 33.0,
..default()
},
// Alpha channel of the color controls transparency.
TextColor(Color::srgba(1.0, 1.0, 1.0, 0.2)),
));
});
// Button with a different color,
// to demonstrate the text looks different due to its transparency.
parent
.spawn((
Button,
Node {
width: px(150),
height: px(65),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::srgb(0.5, 0.1, 0.5)),
))
.with_children(|parent| {
parent.spawn((
Text::new("Button 2"),
TextFont {
font: font_handle.clone(),
font_size: 33.0,
..default()
},
// Alpha channel of the color controls transparency.
TextColor(Color::srgba(1.0, 1.0, 1.0, 0.2)),
));
});
});
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/font_weights.rs | examples/ui/font_weights.rs | //! This example demonstrates how to use font weights with text.
use bevy::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let font: FontSource = asset_server.load("fonts/MonaSans-VariableFont.ttf").into();
commands.spawn(Camera2d);
commands.spawn((
Node {
flex_direction: FlexDirection::Column,
align_self: AlignSelf::Center,
justify_self: JustifySelf::Center,
align_items: AlignItems::Center,
..default()
},
children![
(
Text::new("Font Weights"),
TextFont {
font: font.clone(),
font_size: 32.0,
..default()
},
Underline,
),
(
Node {
flex_direction: FlexDirection::Column,
padding: px(8.).all(),
row_gap: px(8.),
..default()
},
children![
(
Text::new("Weight 100 (Thin)"),
TextFont {
font: font.clone(),
font_size: 32.0,
weight: FontWeight::THIN, // 100
..default()
},
),
(
Text::new("Weight 200 (Extra Light)"),
TextFont {
font: font.clone(),
font_size: 32.0,
weight: FontWeight::EXTRA_LIGHT, // 200
..default()
},
),
(
Text::new("Weight 300 (Light)"),
TextFont {
font: font.clone(),
font_size: 32.0,
weight: FontWeight::LIGHT, // 300
..default()
},
),
(
Text::new("Weight 400 (Normal)"),
TextFont {
font: font.clone(),
font_size: 32.0,
weight: FontWeight::NORMAL, // 400
..default()
},
),
(
Text::new("Weight 500 (Medium)"),
TextFont {
font: font.clone(),
font_size: 32.0,
weight: FontWeight::MEDIUM, // 500
..default()
},
),
(
Text::new("Weight 600 (Semibold)"),
TextFont {
font: font.clone(),
font_size: 32.0,
weight: FontWeight::SEMIBOLD, // 600
..default()
},
),
(
Text::new("Weight 700 (Bold)"),
TextFont {
font: font.clone(),
font_size: 32.0,
weight: FontWeight::BOLD, // 700
..default()
},
),
(
Text::new("Weight 800 (Extra Bold)"),
TextFont {
font: font.clone(),
font_size: 32.0,
weight: FontWeight::EXTRA_BOLD, // 800
..default()
},
),
(
Text::new("Weight 900 (Black)"),
TextFont {
font: font.clone(),
font_size: 32.0,
weight: FontWeight::BLACK, // 900
..default()
},
),
]
),
],
));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/overflow_debug.rs | examples/ui/overflow_debug.rs | //! Tests how different transforms behave when clipped with `Overflow::Hidden`
use bevy::{input::common_conditions::input_just_pressed, prelude::*, ui::widget::TextUiWriter};
use std::f32::consts::{FRAC_PI_2, PI, TAU};
const CONTAINER_SIZE: f32 = 150.0;
const LOOP_LENGTH: f32 = 4.0;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_resource::<AnimationState>()
.add_systems(Startup, setup)
.add_systems(
Update,
(
toggle_overflow.run_if(input_just_pressed(KeyCode::KeyO)),
next_container_size.run_if(input_just_pressed(KeyCode::KeyS)),
update_transform::<Move>,
update_transform::<Scale>,
update_transform::<Rotate>,
update_animation,
),
)
.run();
}
#[derive(Component)]
struct Instructions;
#[derive(Resource, Default)]
struct AnimationState {
playing: bool,
paused_at: f32,
paused_total: f32,
t: f32,
}
#[derive(Component)]
struct Container(u8);
trait UpdateTransform {
fn update(&self, t: f32, transform: &mut UiTransform);
}
#[derive(Component)]
struct Move;
impl UpdateTransform for Move {
fn update(&self, t: f32, transform: &mut UiTransform) {
transform.translation.x = percent(ops::sin(t * TAU - FRAC_PI_2) * 50.);
transform.translation.y = percent(-ops::cos(t * TAU - FRAC_PI_2) * 50.);
}
}
#[derive(Component)]
struct Scale;
impl UpdateTransform for Scale {
fn update(&self, t: f32, transform: &mut UiTransform) {
transform.scale.x = 1.0 + 0.5 * ops::cos(t * TAU).max(0.0);
transform.scale.y = 1.0 + 0.5 * ops::cos(t * TAU + PI).max(0.0);
}
}
#[derive(Component)]
struct Rotate;
impl UpdateTransform for Rotate {
fn update(&self, t: f32, transform: &mut UiTransform) {
transform.rotation = Rot2::radians(ops::cos(t * TAU) * 45.0);
}
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Camera
commands.spawn(Camera2d);
// Instructions
let text_font = TextFont::default();
commands
.spawn((
Text::new(
"Next Overflow Setting (O)\nNext Container Size (S)\nToggle Animation (space)\n\n",
),
text_font.clone(),
Node {
position_type: PositionType::Absolute,
top: px(12),
left: px(12),
..default()
},
Instructions,
))
.with_child((
TextSpan::new(format!("{:?}", Overflow::clip())),
text_font.clone(),
));
// Overflow Debug
commands
.spawn(Node {
width: percent(100),
height: percent(100),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
})
.with_children(|parent| {
parent
.spawn(Node {
display: Display::Grid,
grid_template_columns: RepeatedGridTrack::px(3, CONTAINER_SIZE),
grid_template_rows: RepeatedGridTrack::px(2, CONTAINER_SIZE),
row_gap: px(80),
column_gap: px(80),
..default()
})
.with_children(|parent| {
spawn_image(parent, &asset_server, Move);
spawn_image(parent, &asset_server, Scale);
spawn_image(parent, &asset_server, Rotate);
spawn_text(parent, &asset_server, Move);
spawn_text(parent, &asset_server, Scale);
spawn_text(parent, &asset_server, Rotate);
});
});
}
fn spawn_image(
parent: &mut ChildSpawnerCommands,
asset_server: &Res<AssetServer>,
update_transform: impl UpdateTransform + Component,
) {
spawn_container(parent, update_transform, |parent| {
parent.spawn((
ImageNode::new(asset_server.load("branding/bevy_logo_dark_big.png")),
Node {
height: px(100),
position_type: PositionType::Absolute,
top: px(-50),
left: px(-200),
..default()
},
));
});
}
fn spawn_text(
parent: &mut ChildSpawnerCommands,
asset_server: &Res<AssetServer>,
update_transform: impl UpdateTransform + Component,
) {
spawn_container(parent, update_transform, |parent| {
parent.spawn((
Text::new("Bevy"),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 100.0,
..default()
},
));
});
}
fn spawn_container(
parent: &mut ChildSpawnerCommands,
update_transform: impl UpdateTransform + Component,
spawn_children: impl FnOnce(&mut ChildSpawnerCommands),
) {
parent
.spawn((
Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
overflow: Overflow::clip(),
..default()
},
BackgroundColor(Color::srgb(0.25, 0.25, 0.25)),
Container(0),
))
.with_children(|parent| {
parent
.spawn((
Node {
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
update_transform,
))
.with_children(spawn_children);
});
}
fn update_animation(
mut animation: ResMut<AnimationState>,
time: Res<Time>,
keys: Res<ButtonInput<KeyCode>>,
) {
let delta = time.elapsed_secs();
if keys.just_pressed(KeyCode::Space) {
animation.playing = !animation.playing;
if !animation.playing {
animation.paused_at = delta;
} else {
animation.paused_total += delta - animation.paused_at;
}
}
if animation.playing {
animation.t = (delta - animation.paused_total) % LOOP_LENGTH / LOOP_LENGTH;
}
}
fn update_transform<T: UpdateTransform + Component>(
animation: Res<AnimationState>,
mut containers: Query<(&mut UiTransform, &T)>,
) {
for (mut transform, update_transform) in &mut containers {
update_transform.update(animation.t, &mut transform);
}
}
fn toggle_overflow(
mut containers: Query<&mut Node, With<Container>>,
instructions: Single<Entity, With<Instructions>>,
mut writer: TextUiWriter,
) {
for mut node in &mut containers {
node.overflow = match node.overflow {
Overflow {
x: OverflowAxis::Visible,
y: OverflowAxis::Visible,
} => Overflow::clip_y(),
Overflow {
x: OverflowAxis::Visible,
y: OverflowAxis::Clip,
} => Overflow::clip_x(),
Overflow {
x: OverflowAxis::Clip,
y: OverflowAxis::Visible,
} => Overflow::clip(),
_ => Overflow::visible(),
};
let entity = *instructions;
*writer.text(entity, 1) = format!("{:?}", node.overflow);
}
}
fn next_container_size(mut containers: Query<(&mut Node, &mut Container)>) {
for (mut node, mut container) in &mut containers {
container.0 = (container.0 + 1) % 3;
node.width = match container.0 {
2 => percent(30),
_ => percent(100),
};
node.height = match container.0 {
1 => percent(30),
_ => percent(100),
};
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/ui_drag_and_drop.rs | examples/ui/ui_drag_and_drop.rs | //! Demonstrates dragging and dropping UI nodes
use bevy::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
const COLUMNS: i16 = 10;
const ROWS: i16 = 10;
const TILE_SIZE: f32 = 40.;
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
commands
.spawn((Node {
display: Display::Grid,
align_self: AlignSelf::Center,
justify_self: JustifySelf::Center,
..Default::default()
}, Pickable::IGNORE, BackgroundColor(Color::srgb(0.4, 0.4, 0.4))))
.with_children(|parent| {
let tile_colors = [
Color::srgb(0.2, 0.2, 0.8),
Color::srgb(0.8, 0.2, 0.2)
];
for column in 0..COLUMNS {
for row in 0..ROWS {
let i = column + row * COLUMNS;
let tile_color = tile_colors[((row % 2) + column) as usize % tile_colors.len()];
let tile_border_color = tile_color.darker(0.025);
parent
.spawn((
Node {
width: Val::Px(TILE_SIZE),
height: Val::Px(TILE_SIZE),
border: UiRect::all(Val::Px(4.)),
grid_row: GridPlacement::start(row + 1),
grid_column: GridPlacement::start(column + 1),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..Default::default()
},
BorderColor::all(tile_border_color),
BackgroundColor(tile_color),
Outline {
width: Val::Px(2.),
offset: Val::ZERO,
color: Color::NONE,
},
Pickable {
should_block_lower: false,
is_hoverable: true,
},
GlobalZIndex::default()
))
.observe(move |on_over: On<Pointer<Over>>, mut query: Query<(&mut BackgroundColor, &mut BorderColor)>| {
if let Ok((mut background_color, mut border_color)) = query.get_mut(on_over.event_target()) {
background_color.0 = tile_color.lighter(0.1);
border_color.set_all(tile_border_color.lighter(0.1));
}
})
.observe(move |on_out: On<Pointer<Out>>, mut query: Query<(&mut BackgroundColor, &mut BorderColor)>| {
if let Ok((mut background_color, mut border_color)) = query.get_mut(on_out.event_target()) {
background_color.0 = tile_color;
border_color.set_all(tile_border_color);
}
})
.observe(|on_drag_start: On<Pointer<DragStart>>, mut query: Query<(&mut Outline, &mut GlobalZIndex)>| {
if let Ok((mut outline, mut global_zindex, )) = query.get_mut(on_drag_start.event_target()) {
outline.color = Color::WHITE;
global_zindex.0 = 1;
}
})
.observe(|on_drag: On<Pointer<Drag>>, mut query: Query<&mut UiTransform>| {
if let Ok(mut transform) = query.get_mut(on_drag.event_target()) {
transform.translation = Val2::px(on_drag.distance.x, on_drag.distance.y);
}
})
.observe(move |on_drag_end: On<Pointer<DragEnd>>, mut query: Query<(&mut UiTransform, &mut Outline, &mut GlobalZIndex)>| {
if let Ok((mut transform, mut outline, mut global_zindex)) = query.get_mut(on_drag_end.event_target()) {
transform.translation = Val2::ZERO;
outline.color = Color::NONE;
global_zindex.0 = 0;
}
})
.observe(|on_drag_drop: On<Pointer<DragDrop>>, mut query: Query<&mut Node>| {
if let Ok([mut a, mut b]) = query.get_many_mut([on_drag_drop.event_target(), on_drag_drop.dropped]) {
core::mem::swap(&mut a.grid_row, &mut b.grid_row);
core::mem::swap(&mut a.grid_column, &mut b.grid_column);
}
})
.with_child((Text::new(format!("{i}")), Pickable::IGNORE));
}
}
});
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/gradients.rs | examples/ui/gradients.rs | //! Simple example demonstrating linear gradients.
use bevy::color::palettes::css::BLUE;
use bevy::color::palettes::css::GREEN;
use bevy::color::palettes::css::INDIGO;
use bevy::color::palettes::css::LIME;
use bevy::color::palettes::css::ORANGE;
use bevy::color::palettes::css::RED;
use bevy::color::palettes::css::VIOLET;
use bevy::color::palettes::css::YELLOW;
use bevy::prelude::*;
use bevy::ui::ColorStop;
use std::f32::consts::TAU;
#[derive(Component)]
struct CurrentColorSpaceLabel;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, update)
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
commands
.spawn(Node {
flex_direction: FlexDirection::Column,
row_gap: px(20),
margin: UiRect::all(px(20)),
..Default::default()
})
.with_children(|commands| {
for (b, stops) in [
(
4.,
vec![
ColorStop::new(Color::WHITE, percent(15)),
ColorStop::new(Color::BLACK, percent(85)),
],
),
(4., vec![RED.into(), BLUE.into(), LIME.into()]),
(
0.,
vec![
RED.into(),
ColorStop::new(RED, percent(100. / 7.)),
ColorStop::new(ORANGE, percent(100. / 7.)),
ColorStop::new(ORANGE, percent(200. / 7.)),
ColorStop::new(YELLOW, percent(200. / 7.)),
ColorStop::new(YELLOW, percent(300. / 7.)),
ColorStop::new(GREEN, percent(300. / 7.)),
ColorStop::new(GREEN, percent(400. / 7.)),
ColorStop::new(BLUE, percent(400. / 7.)),
ColorStop::new(BLUE, percent(500. / 7.)),
ColorStop::new(INDIGO, percent(500. / 7.)),
ColorStop::new(INDIGO, percent(600. / 7.)),
ColorStop::new(VIOLET, percent(600. / 7.)),
VIOLET.into(),
],
),
] {
commands.spawn(Node::default()).with_children(|commands| {
commands
.spawn(Node {
flex_direction: FlexDirection::Column,
row_gap: px(5),
..Default::default()
})
.with_children(|commands| {
for (w, h) in [(70., 70.), (35., 70.), (70., 35.)] {
commands
.spawn(Node {
column_gap: px(10),
..Default::default()
})
.with_children(|commands| {
for angle in (0..8).map(|i| i as f32 * TAU / 8.) {
commands.spawn((
Node {
width: px(w),
height: px(h),
border: UiRect::all(px(b)),
border_radius: BorderRadius::all(px(20)),
..default()
},
BackgroundGradient::from(LinearGradient {
angle,
stops: stops.clone(),
..default()
}),
BorderGradient::from(LinearGradient {
angle: 3. * TAU / 8.,
stops: vec![
YELLOW.into(),
Color::WHITE.into(),
ORANGE.into(),
],
..default()
}),
));
}
});
}
});
commands.spawn(Node::default()).with_children(|commands| {
commands.spawn((
Node {
aspect_ratio: Some(1.),
height: percent(100),
border: UiRect::all(px(b)),
margin: UiRect::left(px(20)),
border_radius: BorderRadius::all(px(20)),
..default()
},
BackgroundGradient::from(LinearGradient {
angle: 0.,
stops: stops.clone(),
..default()
}),
BorderGradient::from(LinearGradient {
angle: 3. * TAU / 8.,
stops: vec![YELLOW.into(), Color::WHITE.into(), ORANGE.into()],
..default()
}),
AnimateMarker,
));
commands.spawn((
Node {
aspect_ratio: Some(1.),
height: percent(100),
border: UiRect::all(px(b)),
margin: UiRect::left(px(20)),
border_radius: BorderRadius::all(px(20)),
..default()
},
BackgroundGradient::from(RadialGradient {
stops: stops.clone(),
shape: RadialGradientShape::ClosestSide,
position: UiPosition::CENTER,
..default()
}),
BorderGradient::from(LinearGradient {
angle: 3. * TAU / 8.,
stops: vec![YELLOW.into(), Color::WHITE.into(), ORANGE.into()],
..default()
}),
AnimateMarker,
));
commands.spawn((
Node {
aspect_ratio: Some(1.),
height: percent(100),
border: UiRect::all(px(b)),
margin: UiRect::left(px(20)),
border_radius: BorderRadius::all(px(20)),
..default()
},
BackgroundGradient::from(ConicGradient {
start: 0.,
stops: stops
.iter()
.map(|stop| AngularColorStop::auto(stop.color))
.collect(),
position: UiPosition::CENTER,
..default()
}),
BorderGradient::from(LinearGradient {
angle: 3. * TAU / 8.,
stops: vec![YELLOW.into(), Color::WHITE.into(), ORANGE.into()],
..default()
}),
AnimateMarker,
));
});
});
}
let button = commands.spawn((
Button,
Node {
border: UiRect::all(px(2)),
padding: UiRect::axes(px(8), px(4)),
// horizontally center child text
justify_content: JustifyContent::Center,
// vertically center child text
align_items: AlignItems::Center,
border_radius: BorderRadius::MAX,
..default()
},
BorderColor::all(Color::WHITE),
BackgroundColor(Color::BLACK),
children![(
Text::new("next color space"),
TextColor(Color::srgb(0.9, 0.9, 0.9)),
TextShadow::default(),
)]
)).observe(
|_event: On<Pointer<Over>>, mut border_query: Query<&mut BorderColor, With<Button>>| {
*border_query.single_mut().unwrap() = BorderColor::all(RED);
})
.observe(
|_event: On<Pointer<Out>>, mut border_query: Query<&mut BorderColor, With<Button>>| {
*border_query.single_mut().unwrap() = BorderColor::all(Color::WHITE);
})
.observe(
|_event: On<Pointer<Click>>,
mut gradients_query: Query<&mut BackgroundGradient>,
mut label_query: Query<
&mut Text,
With<CurrentColorSpaceLabel>,
>| {
let mut current_space = InterpolationColorSpace::default();
for mut gradients in gradients_query.iter_mut() {
for gradient in gradients.0.iter_mut() {
let space = match gradient {
Gradient::Linear(linear_gradient) => {
&mut linear_gradient.color_space
}
Gradient::Radial(radial_gradient) => {
&mut radial_gradient.color_space
}
Gradient::Conic(conic_gradient) => {
&mut conic_gradient.color_space
}
};
*space = match *space {
InterpolationColorSpace::Oklaba => {
InterpolationColorSpace::Oklcha
}
InterpolationColorSpace::Oklcha => {
InterpolationColorSpace::OklchaLong
}
InterpolationColorSpace::OklchaLong => {
InterpolationColorSpace::Srgba
}
InterpolationColorSpace::Srgba => {
InterpolationColorSpace::LinearRgba
}
InterpolationColorSpace::LinearRgba => {
InterpolationColorSpace::Hsla
}
InterpolationColorSpace::Hsla => {
InterpolationColorSpace::HslaLong
}
InterpolationColorSpace::HslaLong => {
InterpolationColorSpace::Hsva
}
InterpolationColorSpace::Hsva => {
InterpolationColorSpace::HsvaLong
}
InterpolationColorSpace::HsvaLong => {
InterpolationColorSpace::Oklaba
}
};
current_space = *space;
}
}
for mut label in label_query.iter_mut() {
label.0 = format!("{current_space:?}");
}
}
).id();
commands.spawn(
Node {
flex_direction: FlexDirection::Column,
row_gap: px(10),
align_items: AlignItems::Center,
..Default::default()
}
).with_children(|commands| {
commands.spawn((Text::new(format!("{:?}", InterpolationColorSpace::default())), TextFont { font_size: 25., ..default() }, CurrentColorSpaceLabel));
})
.add_child(button);
});
}
#[derive(Component)]
struct AnimateMarker;
fn update(time: Res<Time>, mut query: Query<&mut BackgroundGradient, With<AnimateMarker>>) {
for mut gradients in query.iter_mut() {
for gradient in gradients.0.iter_mut() {
if let Gradient::Linear(LinearGradient { angle, .. }) = gradient {
*angle += 0.5 * time.delta_secs();
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ui/ui_texture_slice_flip_and_tile.rs | examples/ui/ui_texture_slice_flip_and_tile.rs | //! This example illustrates how to how to flip and tile images with 9-slicing in the UI.
use bevy::{
image::{ImageLoaderSettings, ImageSampler},
prelude::*,
ui::widget::NodeImageMode,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(UiScale(2.))
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let image = asset_server.load_with_settings(
"textures/fantasy_ui_borders/numbered_slices.png",
|settings: &mut ImageLoaderSettings| {
// Need to use nearest filtering to avoid bleeding between the slices with tiling
settings.sampler = ImageSampler::nearest();
},
);
let slicer = TextureSlicer {
// `numbered_slices.png` is 48 pixels square. `BorderRect::square(16.)` insets the slicing line from each edge by 16 pixels, resulting in nine slices that are each 16 pixels square.
border: BorderRect::all(16.),
// With `SliceScaleMode::Tile` the side and center slices are tiled to fill the side and center sections of the target.
// And with a `stretch_value` of `1.` the tiles will have the same size as the corresponding slices in the source image.
center_scale_mode: SliceScaleMode::Tile { stretch_value: 1. },
sides_scale_mode: SliceScaleMode::Tile { stretch_value: 1. },
..default()
};
// ui camera
commands.spawn(Camera2d);
commands
.spawn(Node {
width: percent(100),
height: percent(100),
justify_content: JustifyContent::Center,
align_content: AlignContent::Center,
flex_wrap: FlexWrap::Wrap,
column_gap: px(10),
row_gap: px(10),
..default()
})
.with_children(|parent| {
for [columns, rows] in [[3, 3], [4, 4], [5, 4], [4, 5], [5, 5]] {
for (flip_x, flip_y) in [(false, false), (false, true), (true, false), (true, true)]
{
parent.spawn((
ImageNode {
image: image.clone(),
flip_x,
flip_y,
image_mode: NodeImageMode::Sliced(slicer.clone()),
..default()
},
Node {
width: px(16 * columns),
height: px(16 * rows),
..default()
},
));
}
}
});
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/extra_source.rs | examples/asset/extra_source.rs | //! An example of registering an extra asset source, and loading assets from it.
//! This asset source exists in addition to the default asset source.
use bevy::{
asset::{
io::{AssetSourceBuilder, AssetSourceId},
AssetPath,
},
prelude::*,
};
use std::path::Path;
fn main() {
App::new()
// Add an extra asset source with the name "example_files" to
// AssetSourceBuilders.
//
// This must be done before AssetPlugin finalizes building assets.
.register_asset_source(
"example_files",
AssetSourceBuilder::platform_default("examples/asset/files", None),
)
// DefaultPlugins contains AssetPlugin so it must be added to our App
// after inserting our new asset source.
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
// Now we can load the asset using our new asset source.
//
// The actual file path relative to workspace root is
// "examples/asset/files/bevy_pixel_light.png".
let path = Path::new("bevy_pixel_light.png");
let source = AssetSourceId::from("example_files");
let asset_path = AssetPath::from_path(path).with_source(source);
// You could also parse this URL-like string representation for the asset
// path.
assert_eq!(asset_path, "example_files://bevy_pixel_light.png".into());
commands.spawn(Sprite::from_image(asset_server.load(asset_path)));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/web_asset.rs | examples/asset/web_asset.rs | //! Example usage of the `https` asset source to load assets from the web.
//!
//! Run with the feature `https`, and optionally `web_asset_cache`
//! for a simple caching mechanism that never invalidates.
//!
use bevy::{asset::io::web::WebAssetPlugin, prelude::*};
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(WebAssetPlugin {
silence_startup_warning: true,
}))
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let url = "https://raw.githubusercontent.com/bevyengine/bevy/refs/heads/main/assets/branding/bevy_bird_dark.png";
// Simply use a url where you would normally use an asset folder relative path
commands.spawn(Sprite::from_image(asset_server.load(url)));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/multi_asset_sync.rs | examples/asset/multi_asset_sync.rs | //! This example illustrates how to wait for multiple assets to be loaded.
use std::{
f32::consts::PI,
ops::Drop,
sync::{
atomic::{AtomicBool, AtomicU32, Ordering},
Arc,
},
};
use bevy::{gltf::Gltf, prelude::*, tasks::AsyncComputeTaskPool};
use event_listener::Event;
use futures_lite::Future;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_state::<LoadingState>()
.insert_resource(GlobalAmbientLight {
color: Color::WHITE,
brightness: 2000.,
..default()
})
.add_systems(Startup, setup_assets)
.add_systems(Startup, setup_scene)
.add_systems(Startup, setup_ui)
// This showcases how to wait for assets using sync code.
// This approach polls a value in a system.
.add_systems(Update, wait_on_load.run_if(assets_loaded))
// This showcases how to wait for assets using async
// by spawning a `Future` in `AsyncComputeTaskPool`.
.add_systems(
Update,
get_async_loading_state.run_if(in_state(LoadingState::Loading)),
)
// This showcases how to react to asynchronous world mutation synchronously.
.add_systems(
OnExit(LoadingState::Loading),
despawn_loading_state_entities,
)
.run();
}
/// [`States`] of asset loading.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, States, Default)]
pub enum LoadingState {
/// Is loading.
#[default]
Loading,
/// Loading completed.
Loaded,
}
/// Holds a bunch of [`Gltf`]s that takes time to load.
#[derive(Debug, Resource)]
pub struct OneHundredThings([Handle<Gltf>; 100]);
/// This is required to support both sync and async.
///
/// For sync only the easiest implementation is
/// [`Arc<()>`] and use [`Arc::strong_count`] for completion.
/// [`Arc<Atomic>`] is a more robust alternative.
#[derive(Debug, Resource, Deref)]
pub struct AssetBarrier(Arc<AssetBarrierInner>);
/// This guard is to be acquired by [`AssetServer::load_acquire`]
/// and dropped once finished.
#[derive(Debug, Deref)]
pub struct AssetBarrierGuard(Arc<AssetBarrierInner>);
/// Tracks how many guards are remaining.
#[derive(Debug, Resource)]
pub struct AssetBarrierInner {
count: AtomicU32,
/// This can be omitted if async is not needed.
notify: Event,
}
/// State of loading asynchronously.
#[derive(Debug, Resource)]
pub struct AsyncLoadingState(Arc<AtomicBool>);
/// Entities that are to be removed once loading finished
#[derive(Debug, Component)]
pub struct Loading;
/// Marker for the "Loading..." Text component.
#[derive(Debug, Component)]
pub struct LoadingText;
impl AssetBarrier {
/// Create an [`AssetBarrier`] with a [`AssetBarrierGuard`].
pub fn new() -> (AssetBarrier, AssetBarrierGuard) {
let inner = Arc::new(AssetBarrierInner {
count: AtomicU32::new(1),
notify: Event::new(),
});
(AssetBarrier(inner.clone()), AssetBarrierGuard(inner))
}
/// Returns true if all [`AssetBarrierGuard`] is dropped.
pub fn is_ready(&self) -> bool {
self.count.load(Ordering::Acquire) == 0
}
/// Wait for all [`AssetBarrierGuard`]s to be dropped asynchronously.
pub fn wait_async(&self) -> impl Future<Output = ()> + 'static {
let shared = self.0.clone();
async move {
loop {
// Acquire an event listener.
let listener = shared.notify.listen();
// If all barrier guards are dropped, return
if shared.count.load(Ordering::Acquire) == 0 {
return;
}
// Wait for the last barrier guard to notify us
listener.await;
}
}
}
}
// Increment count on clone.
impl Clone for AssetBarrierGuard {
fn clone(&self) -> Self {
self.count.fetch_add(1, Ordering::AcqRel);
AssetBarrierGuard(self.0.clone())
}
}
// Decrement count on drop.
impl Drop for AssetBarrierGuard {
fn drop(&mut self) {
let prev = self.count.fetch_sub(1, Ordering::AcqRel);
if prev == 1 {
// Notify all listeners if count reaches 0.
self.notify.notify(usize::MAX);
}
}
}
fn setup_assets(mut commands: Commands, asset_server: Res<AssetServer>) {
let (barrier, guard) = AssetBarrier::new();
commands.insert_resource(OneHundredThings(std::array::from_fn(|i| match i % 5 {
0 => asset_server.load_acquire("models/GolfBall/GolfBall.glb", guard.clone()),
1 => asset_server.load_acquire("models/AlienCake/alien.glb", guard.clone()),
2 => asset_server.load_acquire("models/AlienCake/cakeBirthday.glb", guard.clone()),
3 => asset_server.load_acquire("models/FlightHelmet/FlightHelmet.gltf", guard.clone()),
4 => asset_server.load_acquire("models/torus/torus.gltf", guard.clone()),
_ => unreachable!(),
})));
let future = barrier.wait_async();
commands.insert_resource(barrier);
let loading_state = Arc::new(AtomicBool::new(false));
commands.insert_resource(AsyncLoadingState(loading_state.clone()));
// await the `AssetBarrierFuture`.
AsyncComputeTaskPool::get()
.spawn(async move {
future.await;
// Notify via `AsyncLoadingState`
loading_state.store(true, Ordering::Release);
})
.detach();
}
fn setup_ui(mut commands: Commands) {
// Display the result of async loading.
commands.spawn((
LoadingText,
Text::new("Loading...".to_owned()),
Node {
position_type: PositionType::Absolute,
left: px(12),
top: px(12),
..default()
},
));
}
fn setup_scene(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(10.0, 10.0, 15.0).looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
));
// Light
commands.spawn((
DirectionalLight {
shadows_enabled: true,
..default()
},
Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
));
// Plane
commands.spawn((
Mesh3d(meshes.add(Plane3d::default().mesh().size(50000.0, 50000.0))),
MeshMaterial3d(materials.add(Color::srgb(0.7, 0.2, 0.2))),
Loading,
));
}
// A run condition for all assets being loaded.
fn assets_loaded(barrier: Option<Res<AssetBarrier>>) -> bool {
// If our barrier isn't ready, return early and wait another cycle
barrier.map(|b| b.is_ready()) == Some(true)
}
// This showcases how to wait for assets using sync code and systems.
//
// This function only runs if `assets_loaded` returns true.
fn wait_on_load(
mut commands: Commands,
foxes: Res<OneHundredThings>,
gltfs: Res<Assets<Gltf>>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Change color of plane to green
commands.spawn((
Mesh3d(meshes.add(Plane3d::default().mesh().size(50000.0, 50000.0))),
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
Transform::from_translation(Vec3::Z * -0.01),
));
// Spawn our scenes.
for i in 0..10 {
for j in 0..10 {
let index = i * 10 + j;
let position = Vec3::new(i as f32 - 5.0, 0.0, j as f32 - 5.0);
// All gltfs must exist because this is guarded by the `AssetBarrier`.
let gltf = gltfs.get(&foxes.0[index]).unwrap();
let scene = gltf.scenes.first().unwrap().clone();
commands.spawn((SceneRoot(scene), Transform::from_translation(position)));
}
}
}
// This showcases how to wait for assets using async.
fn get_async_loading_state(
state: Res<AsyncLoadingState>,
mut next_loading_state: ResMut<NextState<LoadingState>>,
mut text: Query<&mut Text, With<LoadingText>>,
) {
// Load the value written by the `Future`.
let is_loaded = state.0.load(Ordering::Acquire);
// If loaded, change the state.
if is_loaded {
next_loading_state.set(LoadingState::Loaded);
if let Ok(mut text) = text.single_mut() {
"Loaded!".clone_into(&mut **text);
}
}
}
// This showcases how to react to asynchronous world mutations synchronously.
fn despawn_loading_state_entities(mut commands: Commands, loading: Query<Entity, With<Loading>>) {
// Despawn entities in the loading phase.
for entity in loading.iter() {
commands.entity(entity).despawn();
}
// Despawn resources used in the loading phase.
commands.remove_resource::<AssetBarrier>();
commands.remove_resource::<AsyncLoadingState>();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/repeated_texture.rs | examples/asset/repeated_texture.rs | //! By default Bevy loads images to textures that clamps the image to the edges
//! This example shows how to configure it to repeat the image instead.
use bevy::{
image::{ImageAddressMode, ImageLoaderSettings, ImageSampler, ImageSamplerDescriptor},
math::Affine2,
prelude::*,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let image_with_default_sampler =
asset_server.load("textures/fantasy_ui_borders/panel-border-010.png");
// central cube with not repeated texture
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(StandardMaterial {
base_color_texture: Some(image_with_default_sampler.clone()),
..default()
})),
Transform::from_translation(Vec3::ZERO),
));
// left cube with repeated texture
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(StandardMaterial {
base_color_texture: Some(asset_server.load_with_settings(
"textures/fantasy_ui_borders/panel-border-010-repeated.png",
|s: &mut _| {
*s = ImageLoaderSettings {
sampler: ImageSampler::Descriptor(ImageSamplerDescriptor {
// rewriting mode to repeat image,
address_mode_u: ImageAddressMode::Repeat,
address_mode_v: ImageAddressMode::Repeat,
..default()
}),
..default()
}
},
)),
// uv_transform used here for proportions only, but it is full Affine2
// that's why you can use rotation and shift also
uv_transform: Affine2::from_scale(Vec2::new(2., 3.)),
..default()
})),
Transform::from_xyz(-1.5, 0.0, 0.0),
));
// right cube with scaled texture, because with default sampler
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(StandardMaterial {
// there is no sampler set, that's why
// by default you see only one small image in a row/column
// and other space is filled by image edge
base_color_texture: Some(image_with_default_sampler),
// uv_transform used here for proportions only, but it is full Affine2
// that's why you can use rotation and shift also
uv_transform: Affine2::from_scale(Vec2::new(2., 3.)),
..default()
})),
Transform::from_xyz(1.5, 0.0, 0.0),
));
// light
commands.spawn((
PointLight {
shadows_enabled: true,
..default()
},
Transform::from_xyz(4.0, 8.0, 4.0),
));
// camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(0.0, 1.5, 4.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/custom_asset.rs | examples/asset/custom_asset.rs | //! Implements loader for a custom asset type.
use bevy::{
asset::{io::Reader, AssetLoader, LoadContext},
prelude::*,
reflect::TypePath,
};
use serde::Deserialize;
use thiserror::Error;
#[derive(Asset, TypePath, Debug, Deserialize)]
struct CustomAsset {
#[expect(
dead_code,
reason = "Used to show how the data inside an asset file will be loaded into the struct"
)]
value: i32,
}
#[derive(Default, TypePath)]
struct CustomAssetLoader;
/// Possible errors that can be produced by [`CustomAssetLoader`]
#[non_exhaustive]
#[derive(Debug, Error)]
enum CustomAssetLoaderError {
/// An [IO](std::io) Error
#[error("Could not load asset: {0}")]
Io(#[from] std::io::Error),
/// A [RON](ron) Error
#[error("Could not parse RON: {0}")]
RonSpannedError(#[from] ron::error::SpannedError),
}
impl AssetLoader for CustomAssetLoader {
type Asset = CustomAsset;
type Settings = ();
type Error = CustomAssetLoaderError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &(),
_load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let custom_asset = ron::de::from_bytes::<CustomAsset>(&bytes)?;
Ok(custom_asset)
}
fn extensions(&self) -> &[&str] {
&["custom"]
}
}
#[derive(Asset, TypePath, Debug)]
struct Blob {
bytes: Vec<u8>,
}
#[derive(Default, TypePath)]
struct BlobAssetLoader;
/// Possible errors that can be produced by [`BlobAssetLoader`]
#[non_exhaustive]
#[derive(Debug, Error)]
enum BlobAssetLoaderError {
/// An [IO](std::io) Error
#[error("Could not load file: {0}")]
Io(#[from] std::io::Error),
}
impl AssetLoader for BlobAssetLoader {
type Asset = Blob;
type Settings = ();
type Error = BlobAssetLoaderError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &(),
_load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
info!("Loading Blob...");
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
Ok(Blob { bytes })
}
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_resource::<State>()
.init_asset::<CustomAsset>()
.init_asset::<Blob>()
.init_asset_loader::<CustomAssetLoader>()
.init_asset_loader::<BlobAssetLoader>()
.add_systems(Startup, setup)
.add_systems(Update, print_on_load)
.run();
}
#[derive(Resource, Default)]
struct State {
handle: Handle<CustomAsset>,
other_handle: Handle<CustomAsset>,
blob: Handle<Blob>,
printed: bool,
}
fn setup(mut state: ResMut<State>, asset_server: Res<AssetServer>) {
// Recommended way to load an asset
state.handle = asset_server.load("data/asset.custom");
// File extensions are optional, but are recommended for project management and last-resort inference
state.other_handle = asset_server.load("data/asset_no_extension");
// Will use BlobAssetLoader instead of CustomAssetLoader thanks to type inference
state.blob = asset_server.load("data/asset.custom");
}
fn print_on_load(
mut state: ResMut<State>,
custom_assets: Res<Assets<CustomAsset>>,
blob_assets: Res<Assets<Blob>>,
) {
let custom_asset = custom_assets.get(&state.handle);
let other_custom_asset = custom_assets.get(&state.other_handle);
let blob = blob_assets.get(&state.blob);
// Can't print results if the assets aren't ready
if state.printed {
return;
}
if custom_asset.is_none() {
info!("Custom Asset Not Ready");
return;
}
if other_custom_asset.is_none() {
info!("Other Custom Asset Not Ready");
return;
}
if blob.is_none() {
info!("Blob Not Ready");
return;
}
info!("Custom asset loaded: {:?}", custom_asset.unwrap());
info!("Custom asset loaded: {:?}", other_custom_asset.unwrap());
info!("Blob Size: {} Bytes", blob.unwrap().bytes.len());
// Once printed, we won't print again
state.printed = true;
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/embedded_asset.rs | examples/asset/embedded_asset.rs | //! Example of loading an embedded asset.
//! An embedded asset is an asset included in the program's memory, in contrast to other assets that are normally loaded from disk to memory when needed.
//! The below example embeds the asset at program startup, unlike the common use case of embedding an asset at build time. Embedded an asset at program startup can be useful
//! for things like loading screens, since it might be nice to display some art while other, non-embedded, assets are loading.
//! One common use case for embedded assets is including them directly within the executable during its creation. By embedding an asset at build time rather than runtime
//! the program never needs to go to disk for the asset at all, since it is already located in the program's binary executable.
use bevy::{
asset::{embedded_asset, io::AssetSourceId, AssetPath},
prelude::*,
};
use std::path::Path;
fn main() {
App::new()
.add_plugins((DefaultPlugins, EmbeddedAssetPlugin))
.add_systems(Startup, setup)
.run();
}
struct EmbeddedAssetPlugin;
impl Plugin for EmbeddedAssetPlugin {
fn build(&self, app: &mut App) {
// We get to choose some prefix relative to the workspace root which
// will be ignored in "embedded://" asset paths.
let omit_prefix = "examples/asset";
// Path to asset must be relative to this file, because that's how
// include_bytes! works.
embedded_asset!(app, omit_prefix, "files/bevy_pixel_light.png");
}
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
// Each example is its own crate (with name from [[example]] in Cargo.toml).
let crate_name = "embedded_asset";
// The actual file path relative to workspace root is
// "examples/asset/files/bevy_pixel_light.png".
//
// We omit the "examples/asset" from the embedded_asset! call and replace it
// with the crate name.
let path = Path::new(crate_name).join("files/bevy_pixel_light.png");
let source = AssetSourceId::from("embedded");
let asset_path = AssetPath::from_path(&path).with_source(source);
// You could also parse this URL-like string representation for the asset
// path.
assert_eq!(
asset_path,
"embedded://embedded_asset/files/bevy_pixel_light.png".into()
);
commands.spawn(Sprite::from_image(asset_server.load(asset_path)));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/asset_settings.rs | examples/asset/asset_settings.rs | //! This example demonstrates the usage of '.meta' files and [`AssetServer::load_with_settings`] to override the default settings for loading an asset
use bevy::{
image::{ImageLoaderSettings, ImageSampler},
prelude::*,
};
fn main() {
App::new()
.add_plugins(
// This just tells the asset server to look in the right examples folder
DefaultPlugins.set(AssetPlugin {
file_path: "examples/asset/files".to_string(),
..Default::default()
}),
)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Without any .meta file specifying settings, the default sampler [ImagePlugin::default()] is used for loading images.
// If you are using a very small image and rendering it larger like seen here, the default linear filtering will result in a blurry image.
// Useful note: The default sampler specified by the ImagePlugin is *not* the same as the default implementation of sampler. This is why
// everything uses linear by default but if you look at the default of sampler, it uses nearest.
commands.spawn((
Sprite {
image: asset_server.load("bevy_pixel_dark.png"),
custom_size: Some(Vec2 { x: 160.0, y: 120.0 }),
..Default::default()
},
Transform::from_xyz(-100.0, 0.0, 0.0),
));
// When a .meta file is added with the same name as the asset and a '.meta' extension
// you can (and must) specify all fields of the asset loader's settings for that
// particular asset, in this case [ImageLoaderSettings]. Take a look at
// examples/asset/files/bevy_pixel_dark_with_meta.png.meta
// for the format and you'll notice, the only non-default option is setting Nearest
// filtering. This tends to work much better for pixel art assets.
// A good reference when filling this out is to check out [ImageLoaderSettings::default()]
// and follow to the default implementation of each fields type.
// https://docs.rs/bevy/latest/bevy/image/struct.ImageLoaderSettings.html
commands.spawn((
Sprite {
image: asset_server.load("bevy_pixel_dark_with_meta.png"),
custom_size: Some(Vec2 { x: 160.0, y: 120.0 }),
..Default::default()
},
Transform::from_xyz(100.0, 0.0, 0.0),
));
// Another option is to use the AssetServers load_with_settings function.
// With this you can specify the same settings upon loading your asset with a
// couple of differences. A big one is that you aren't required to set *every*
// setting, just modify the ones that you need. It works by passing in a function
// (in this case an anonymous closure) that takes a reference to the settings type
// that is then modified in the function.
// Do note that if you want to load the same asset with different settings, the
// settings changes from any loads after the first of the same asset will be ignored.
// This is why this one loads a differently named copy of the asset instead of using
// same one as without a .meta file.
commands.spawn((
Sprite {
image: asset_server.load_with_settings(
"bevy_pixel_dark_with_settings.png",
|settings: &mut ImageLoaderSettings| {
settings.sampler = ImageSampler::nearest();
},
),
custom_size: Some(Vec2 { x: 160.0, y: 120.0 }),
..Default::default()
},
Transform::from_xyz(0.0, 150.0, 0.0),
));
commands.spawn(Camera2d);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/asset_loading.rs | examples/asset/asset_loading.rs | //! This example illustrates various ways to load assets.
use bevy::{asset::LoadedFolder, prelude::*};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
meshes: Res<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// By default AssetServer will load assets from inside the "assets" folder.
// For example, the next line will load GltfAssetLabel::Primitive{mesh:0,primitive:0}.from_asset("ROOT/assets/models/cube/cube.gltf"),
// where "ROOT" is the directory of the Application.
//
// This can be overridden by setting [`AssetPlugin.file_path`].
let cube_handle = asset_server.load(
GltfAssetLabel::Primitive {
mesh: 0,
primitive: 0,
}
.from_asset("models/cube/cube.gltf"),
);
let sphere_handle = asset_server.load(
GltfAssetLabel::Primitive {
mesh: 0,
primitive: 0,
}
.from_asset("models/sphere/sphere.gltf"),
);
// All assets end up in their Assets<T> collection once they are done loading:
if let Some(sphere) = meshes.get(&sphere_handle) {
// You might notice that this doesn't run! This is because assets load in parallel without
// blocking. When an asset has loaded, it will appear in relevant Assets<T>
// collection.
info!("{:?}", sphere.primitive_topology());
} else {
info!("sphere hasn't loaded yet");
}
// You can load all assets in a folder like this. They will be loaded in parallel without
// blocking. The LoadedFolder asset holds handles to each asset in the folder. These are all
// dependencies of the LoadedFolder asset, meaning you can wait for the LoadedFolder asset to
// fire AssetEvent::LoadedWithDependencies if you want to wait for all assets in the folder
// to load.
// If you want to keep the assets in the folder alive, make sure you store the returned handle
// somewhere.
let _loaded_folder: Handle<LoadedFolder> = asset_server.load_folder("models/torus");
// If you want a handle to a specific asset in a loaded folder, the easiest way to get one is to call load.
// It will _not_ be loaded a second time.
// The LoadedFolder asset will ultimately also hold handles to the assets, but waiting for it to load
// and finding the right handle is more work!
let torus_handle = asset_server.load(
GltfAssetLabel::Primitive {
mesh: 0,
primitive: 0,
}
.from_asset("models/torus/torus.gltf"),
);
// You can also add assets directly to their Assets<T> storage:
let material_handle = materials.add(StandardMaterial {
base_color: Color::srgb(0.8, 0.7, 0.6),
..default()
});
// torus
commands.spawn((
Mesh3d(torus_handle),
MeshMaterial3d(material_handle.clone()),
Transform::from_xyz(-3.0, 0.0, 0.0),
));
// cube
commands.spawn((
Mesh3d(cube_handle),
MeshMaterial3d(material_handle.clone()),
Transform::from_xyz(0.0, 0.0, 0.0),
));
// sphere
commands.spawn((
Mesh3d(sphere_handle),
MeshMaterial3d(material_handle),
Transform::from_xyz(3.0, 0.0, 0.0),
));
// light
commands.spawn((PointLight::default(), Transform::from_xyz(4.0, 5.0, 4.0)));
// camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(0.0, 3.0, 10.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/custom_asset_reader.rs | examples/asset/custom_asset_reader.rs | //! Implements a custom asset io loader.
//! An [`AssetReader`] is what the asset server uses to read the raw bytes of assets.
//! It does not know anything about the asset formats, only how to talk to the underlying storage.
use bevy::{
asset::io::{
AssetReader, AssetReaderError, AssetSource, AssetSourceBuilder, AssetSourceId,
ErasedAssetReader, PathStream, Reader, ReaderRequiredFeatures,
},
prelude::*,
};
use std::path::Path;
/// A custom asset reader implementation that wraps a given asset reader implementation
struct CustomAssetReader(Box<dyn ErasedAssetReader>);
impl AssetReader for CustomAssetReader {
async fn read<'a>(
&'a self,
path: &'a Path,
required_features: ReaderRequiredFeatures,
) -> Result<impl Reader + 'a, AssetReaderError> {
info!("Reading {}", path.display());
self.0.read(path, required_features).await
}
async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
self.0.read_meta(path).await
}
async fn read_directory<'a>(
&'a self,
path: &'a Path,
) -> Result<Box<PathStream>, AssetReaderError> {
self.0.read_directory(path).await
}
async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> {
self.0.is_directory(path).await
}
}
/// A plugins that registers our new asset reader
struct CustomAssetReaderPlugin;
impl Plugin for CustomAssetReaderPlugin {
fn build(&self, app: &mut App) {
app.register_asset_source(
AssetSourceId::Default,
AssetSourceBuilder::new(|| {
Box::new(CustomAssetReader(
// This is the default reader for the current platform
AssetSource::get_default_reader("assets".to_string())(),
))
}),
);
}
}
fn main() {
App::new()
.add_plugins((CustomAssetReaderPlugin, DefaultPlugins))
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands.spawn(Sprite::from_image(asset_server.load("branding/icon.png")));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/hot_asset_reloading.rs | examples/asset/hot_asset_reloading.rs | //! Hot reloading allows you to modify assets files to be immediately reloaded while your game is
//! running. This lets you immediately see the results of your changes without restarting the game.
//! This example illustrates hot reloading mesh changes.
//!
//! Note that hot asset reloading requires the [`AssetWatcher`](bevy::asset::io::AssetWatcher) to be enabled
//! for your current platform. For desktop platforms, enable the `file_watcher` cargo feature.
use bevy::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Load our mesh:
let scene_handle =
asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/torus/torus.gltf"));
// Any changes to the mesh will be reloaded automatically! Try making a change to torus.gltf.
// You should see the changes immediately show up in your app.
// mesh
commands.spawn(SceneRoot(scene_handle));
// light
commands.spawn((
DirectionalLight::default(),
Transform::from_xyz(4.0, 5.0, 4.0).looking_at(Vec3::ZERO, Vec3::Y),
));
// camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(2.0, 2.0, 6.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/alter_mesh.rs | examples/asset/alter_mesh.rs | //! Shows how to modify mesh assets after spawning.
use bevy::{
asset::RenderAssetUsages, gltf::GltfLoaderSettings,
input::common_conditions::input_just_pressed, mesh::VertexAttributeValues, prelude::*,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, (setup, spawn_text))
.add_systems(
Update,
alter_handle.run_if(input_just_pressed(KeyCode::Space)),
)
.add_systems(
Update,
alter_mesh.run_if(input_just_pressed(KeyCode::Enter)),
)
.run();
}
#[derive(Component, Debug)]
enum Shape {
Cube,
Sphere,
}
impl Shape {
fn get_model_path(&self) -> String {
match self {
Shape::Cube => "models/cube/cube.gltf".into(),
Shape::Sphere => "models/sphere/sphere.gltf".into(),
}
}
fn set_next_variant(&mut self) {
*self = match self {
Shape::Cube => Shape::Sphere,
Shape::Sphere => Shape::Cube,
}
}
}
#[derive(Component, Debug)]
struct Left;
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let left_shape = Shape::Cube;
let right_shape = Shape::Cube;
// In normal use, you can call `asset_server.load`, however see below for an explanation of
// `RenderAssetUsages`.
let left_shape_model = asset_server.load_with_settings(
GltfAssetLabel::Primitive {
mesh: 0,
// This field stores an index to this primitive in its parent mesh. In this case, we
// want the first one. You might also have seen the syntax:
//
// models/cube/cube.gltf#Scene0
//
// which accomplishes the same thing.
primitive: 0,
}
.from_asset(left_shape.get_model_path()),
// `RenderAssetUsages::all()` is already the default, so the line below could be omitted.
// It's helpful to know it exists, however.
//
// `RenderAssetUsages` tell Bevy whether to keep the data around:
// - for the GPU (`RenderAssetUsages::RENDER_WORLD`),
// - for the CPU (`RenderAssetUsages::MAIN_WORLD`),
// - or both.
// `RENDER_WORLD` is necessary to render the mesh, `MAIN_WORLD` is necessary to inspect
// and modify the mesh (via `ResMut<Assets<Mesh>>`).
//
// Since most games will not need to modify meshes at runtime, many developers opt to pass
// only `RENDER_WORLD`. This is more memory efficient, as we don't need to keep the mesh in
// RAM. For this example however, this would not work, as we need to inspect and modify the
// mesh at runtime.
|settings: &mut GltfLoaderSettings| settings.load_meshes = RenderAssetUsages::all(),
);
// Here, we rely on the default loader settings to achieve a similar result to the above.
let right_shape_model = asset_server.load(
GltfAssetLabel::Primitive {
mesh: 0,
primitive: 0,
}
.from_asset(right_shape.get_model_path()),
);
// Add a material asset directly to the materials storage
let material_handle = materials.add(StandardMaterial {
base_color: Color::srgb(0.6, 0.8, 0.6),
..default()
});
commands.spawn((
Left,
Name::new("Left Shape"),
Mesh3d(left_shape_model),
MeshMaterial3d(material_handle.clone()),
Transform::from_xyz(-3.0, 0.0, 0.0),
left_shape,
));
commands.spawn((
Name::new("Right Shape"),
Mesh3d(right_shape_model),
MeshMaterial3d(material_handle),
Transform::from_xyz(3.0, 0.0, 0.0),
right_shape,
));
commands.spawn((
Name::new("Point Light"),
PointLight::default(),
Transform::from_xyz(4.0, 5.0, 4.0),
));
commands.spawn((
Name::new("Camera"),
Camera3d::default(),
Transform::from_xyz(0.0, 3.0, 20.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
fn spawn_text(mut commands: Commands) {
commands.spawn((
Name::new("Instructions"),
Text::new(
"Space: swap meshes by mutating a Handle<Mesh>\n\
Return: mutate the mesh itself, changing all copies of it",
),
Node {
position_type: PositionType::Absolute,
top: px(12),
left: px(12),
..default()
},
));
}
fn alter_handle(
asset_server: Res<AssetServer>,
right_shape: Single<(&mut Mesh3d, &mut Shape), Without<Left>>,
) {
// Mesh handles, like other parts of the ECS, can be queried as mutable and modified at
// runtime. We only spawned one shape without the `Left` marker component.
let (mut mesh, mut shape) = right_shape.into_inner();
// Switch to a new Shape variant
shape.set_next_variant();
// Modify the handle associated with the Shape on the right side. Note that we will only
// have to load the same path from storage media once: repeated attempts will re-use the
// asset.
mesh.0 = asset_server.load(
GltfAssetLabel::Primitive {
mesh: 0,
primitive: 0,
}
.from_asset(shape.get_model_path()),
);
}
fn alter_mesh(
mut is_mesh_scaled: Local<bool>,
left_shape: Single<&Mesh3d, With<Left>>,
mut meshes: ResMut<Assets<Mesh>>,
) {
// Obtain a mutable reference to the Mesh asset.
let Some(mesh) = meshes.get_mut(*left_shape) else {
return;
};
// Now we can directly manipulate vertices on the mesh. Here, we're just scaling in and out
// for demonstration purposes. This will affect all entities currently using the asset.
//
// To do this, we need to grab the stored attributes of each vertex. `Float32x3` just describes
// the format in which the attributes will be read: each position consists of an array of three
// f32 corresponding to x, y, and z.
//
// `ATTRIBUTE_POSITION` is a constant indicating that we want to know where the vertex is
// located in space (as opposed to which way its normal is facing, vertex color, or other
// details).
if let Some(VertexAttributeValues::Float32x3(positions)) =
mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION)
{
// Check a Local value (which only this system can make use of) to determine if we're
// currently scaled up or not.
let scale_factor = if *is_mesh_scaled { 0.5 } else { 2.0 };
for position in positions.iter_mut() {
// Apply the scale factor to each of x, y, and z.
position[0] *= scale_factor;
position[1] *= scale_factor;
position[2] *= scale_factor;
}
// Flip the local value to reverse the behavior next time the key is pressed.
*is_mesh_scaled = !*is_mesh_scaled;
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/alter_sprite.rs | examples/asset/alter_sprite.rs | //! Shows how to modify texture assets after spawning.
use bevy::{
asset::RenderAssetUsages, image::ImageLoaderSettings,
input::common_conditions::input_just_pressed, prelude::*,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, (setup, spawn_text))
.add_systems(
Update,
alter_handle.run_if(input_just_pressed(KeyCode::Space)),
)
.add_systems(
Update,
alter_asset.run_if(input_just_pressed(KeyCode::Enter)),
)
.run();
}
#[derive(Component, Debug)]
enum Bird {
Normal,
Logo,
}
impl Bird {
fn get_texture_path(&self) -> String {
match self {
Bird::Normal => "branding/bevy_bird_dark.png".into(),
Bird::Logo => "branding/bevy_logo_dark.png".into(),
}
}
fn set_next_variant(&mut self) {
*self = match self {
Bird::Normal => Bird::Logo,
Bird::Logo => Bird::Normal,
}
}
}
#[derive(Component, Debug)]
struct Left;
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let bird_left = Bird::Normal;
let bird_right = Bird::Normal;
commands.spawn(Camera2d);
let texture_left = asset_server.load_with_settings(
bird_left.get_texture_path(),
// `RenderAssetUsages::all()` is already the default, so the line below could be omitted.
// It's helpful to know it exists, however.
//
// `RenderAssetUsages` tell Bevy whether to keep the data around:
// - for the GPU (`RenderAssetUsages::RENDER_WORLD`),
// - for the CPU (`RenderAssetUsages::MAIN_WORLD`),
// - or both.
// `RENDER_WORLD` is necessary to render the image, `MAIN_WORLD` is necessary to inspect
// and modify the image (via `ResMut<Assets<Image>>`).
//
// Since most games will not need to modify textures at runtime, many developers opt to pass
// only `RENDER_WORLD`. This is more memory efficient, as we don't need to keep the image in
// RAM. For this example however, this would not work, as we need to inspect and modify the
// image at runtime.
|settings: &mut ImageLoaderSettings| settings.asset_usage = RenderAssetUsages::all(),
);
commands.spawn((
Name::new("Bird Left"),
// This marker component ensures we can easily find either of the Birds by using With and
// Without query filters.
Left,
Sprite::from_image(texture_left),
Transform::from_xyz(-200.0, 0.0, 0.0),
bird_left,
));
commands.spawn((
Name::new("Bird Right"),
// In contrast to the above, here we rely on the default `RenderAssetUsages` loader setting
Sprite::from_image(asset_server.load(bird_right.get_texture_path())),
Transform::from_xyz(200.0, 0.0, 0.0),
bird_right,
));
}
fn spawn_text(mut commands: Commands) {
commands.spawn((
Name::new("Instructions"),
Text::new(
"Space: swap the right sprite's image handle\n\
Return: modify the image Asset of the left sprite, affecting all uses of it",
),
Node {
position_type: PositionType::Absolute,
top: px(12),
left: px(12),
..default()
},
));
}
fn alter_handle(
asset_server: Res<AssetServer>,
right_bird: Single<(&mut Bird, &mut Sprite), Without<Left>>,
) {
// Image handles, like other parts of the ECS, can be queried as mutable and modified at
// runtime. We only spawned one bird without the `Left` marker component.
let (mut bird, mut sprite) = right_bird.into_inner();
// Switch to a new Bird variant
bird.set_next_variant();
// Modify the handle associated with the Bird on the right side. Note that we will only
// have to load the same path from storage media once: repeated attempts will re-use the
// asset.
sprite.image = asset_server.load(bird.get_texture_path());
}
fn alter_asset(mut images: ResMut<Assets<Image>>, left_bird: Single<&Sprite, With<Left>>) {
// Obtain a mutable reference to the Image asset.
let Some(image) = images.get_mut(&left_bird.image) else {
return;
};
for pixel in image.data.as_mut().unwrap() {
// Directly modify the asset data, which will affect all users of this asset. By
// contrast, mutating the handle (as we did above) affects only one copy. In this case,
// we'll just invert the colors, by way of demonstration. Notice that both uses of the
// asset show the change, not just the one on the left.
*pixel = 255 - *pixel;
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/asset_decompression.rs | examples/asset/asset_decompression.rs | //! Implements loader for a Gzip compressed asset.
use bevy::{
asset::{
io::{Reader, VecReader},
AssetLoader, ErasedLoadedAsset, LoadContext, LoadDirectError,
},
prelude::*,
reflect::TypePath,
};
use flate2::read::GzDecoder;
use std::{io::prelude::*, marker::PhantomData};
use thiserror::Error;
#[derive(Asset, TypePath)]
struct GzAsset {
uncompressed: ErasedLoadedAsset,
}
#[derive(Default, TypePath)]
struct GzAssetLoader;
/// Possible errors that can be produced by [`GzAssetLoader`]
#[non_exhaustive]
#[derive(Debug, Error)]
enum GzAssetLoaderError {
/// An [IO](std::io) Error
#[error("Could not load asset: {0}")]
Io(#[from] std::io::Error),
/// An error caused when the asset path cannot be used to determine the uncompressed asset type.
#[error("Could not determine file path of uncompressed asset")]
IndeterminateFilePath,
/// An error caused by the internal asset loader.
#[error("Could not load contained asset: {0}")]
LoadDirectError(#[from] LoadDirectError),
}
impl AssetLoader for GzAssetLoader {
type Asset = GzAsset;
type Settings = ();
type Error = GzAssetLoaderError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &(),
load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let compressed_path = load_context.path();
let file_name = compressed_path
.path()
.file_name()
.ok_or(GzAssetLoaderError::IndeterminateFilePath)?
.to_string_lossy();
let uncompressed_file_name = file_name
.strip_suffix(".gz")
.ok_or(GzAssetLoaderError::IndeterminateFilePath)?;
let contained_path = compressed_path
.resolve_embed(uncompressed_file_name)
.map_err(|_| GzAssetLoaderError::IndeterminateFilePath)?;
let mut bytes_compressed = Vec::new();
reader.read_to_end(&mut bytes_compressed).await?;
let mut decoder = GzDecoder::new(bytes_compressed.as_slice());
let mut bytes_uncompressed = Vec::new();
decoder.read_to_end(&mut bytes_uncompressed)?;
// Now that we have decompressed the asset, let's pass it back to the
// context to continue loading
let mut reader = VecReader::new(bytes_uncompressed);
let uncompressed = load_context
.loader()
.with_unknown_type()
.immediate()
.with_reader(&mut reader)
.load(contained_path)
.await?;
Ok(GzAsset { uncompressed })
}
fn extensions(&self) -> &[&str] {
&["gz"]
}
}
#[derive(Component, Default)]
struct Compressed<T> {
compressed: Handle<GzAsset>,
_phantom: PhantomData<T>,
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_asset::<GzAsset>()
.init_asset_loader::<GzAssetLoader>()
.add_systems(Startup, setup)
.add_systems(Update, decompress::<Sprite, Image>)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands.spawn(Compressed::<Image> {
compressed: asset_server.load("data/compressed_image.png.gz"),
..default()
});
}
fn decompress<T: Component + From<Handle<A>>, A: Asset>(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut compressed_assets: ResMut<Assets<GzAsset>>,
query: Query<(Entity, &Compressed<A>)>,
) {
for (entity, Compressed { compressed, .. }) in query.iter() {
let Some(GzAsset { uncompressed }) = compressed_assets.remove(compressed) else {
continue;
};
let uncompressed = uncompressed.take::<A>().unwrap();
commands
.entity(entity)
.remove::<Compressed<A>>()
.insert(T::from(asset_server.add(uncompressed)));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/asset/processing/asset_processing.rs | examples/asset/processing/asset_processing.rs | //! This example illustrates how to define custom `AssetLoader`s, `AssetTransformer`s, and `AssetSaver`s, how to configure them, and how to register asset processors.
use bevy::{
asset::{
embedded_asset,
io::{Reader, Writer},
processor::LoadTransformAndSave,
saver::{AssetSaver, SavedAsset},
transformer::{AssetTransformer, TransformedAsset},
AssetLoader, AsyncWriteExt, LoadContext,
},
prelude::*,
reflect::TypePath,
};
use serde::{Deserialize, Serialize};
use std::convert::Infallible;
use thiserror::Error;
fn main() {
App::new()
// Using the "processed" mode will configure the AssetPlugin to use asset processing.
// If you also enable the `asset_processor` cargo feature, this will run the AssetProcessor
// in the background, run them through configured asset processors, and write the results to
// the `imported_assets` folder. If you also enable the `file_watcher` cargo feature, changes to the
// source assets will be detected and they will be reprocessed.
//
// The AssetProcessor will create `.meta` files automatically for assets in the `assets` folder,
// which can then be used to configure how the asset will be processed.
.add_plugins((
DefaultPlugins.set(AssetPlugin {
mode: AssetMode::Processed,
// This is just overriding the default paths to scope this to the correct example folder
// You can generally skip this in your own projects
file_path: "examples/asset/processing/assets".to_string(),
processed_file_path: "examples/asset/processing/imported_assets/Default"
.to_string(),
..default()
}),
TextPlugin,
))
.add_systems(Startup, setup)
.add_systems(Update, print_text)
.run();
}
/// This [`TextPlugin`] defines two assets types:
/// * [`CoolText`]: a custom RON text format that supports dependencies and embedded dependencies
/// * [`Text`]: a "normal" plain text file
///
/// It also defines an asset processor that will load [`CoolText`], resolve embedded dependencies, and write the resulting
/// output to a "normal" plain text file. When the processed asset is loaded, it is loaded as a Text (plaintext) asset.
/// This illustrates that when you process an asset, you can change its type! However you don't _need_ to change the type.
struct TextPlugin;
impl Plugin for TextPlugin {
fn build(&self, app: &mut App) {
embedded_asset!(app, "examples/asset/processing/", "e.txt");
app.init_asset::<CoolText>()
.init_asset::<Text>()
.register_asset_loader(CoolTextLoader)
.register_asset_loader(TextLoader)
.register_asset_processor::<LoadTransformAndSave<CoolTextLoader, CoolTextTransformer, CoolTextSaver>>(
LoadTransformAndSave::new(CoolTextTransformer, CoolTextSaver),
)
.set_default_asset_processor::<LoadTransformAndSave<CoolTextLoader, CoolTextTransformer, CoolTextSaver>>("cool.ron");
}
}
#[derive(Asset, TypePath, Debug)]
struct Text(String);
#[derive(Default, TypePath)]
struct TextLoader;
#[derive(Clone, Default, Serialize, Deserialize)]
struct TextSettings {
text_override: Option<String>,
}
impl AssetLoader for TextLoader {
type Asset = Text;
type Settings = TextSettings;
type Error = std::io::Error;
async fn load(
&self,
reader: &mut dyn Reader,
settings: &TextSettings,
_load_context: &mut LoadContext<'_>,
) -> Result<Text, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let value = if let Some(ref text) = settings.text_override {
text.clone()
} else {
String::from_utf8(bytes).unwrap()
};
Ok(Text(value))
}
fn extensions(&self) -> &[&str] {
&["txt"]
}
}
#[derive(Serialize, Deserialize)]
struct CoolTextRon {
text: String,
dependencies: Vec<String>,
embedded_dependencies: Vec<String>,
dependencies_with_settings: Vec<(String, TextSettings)>,
}
#[derive(Asset, TypePath, Debug)]
struct CoolText {
text: String,
#[expect(
dead_code,
reason = "Used to show that our assets can hold handles to other assets"
)]
dependencies: Vec<Handle<Text>>,
}
#[derive(Default, TypePath)]
struct CoolTextLoader;
#[derive(Debug, Error)]
enum CoolTextLoaderError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
RonSpannedError(#[from] ron::error::SpannedError),
#[error(transparent)]
LoadDirectError(#[from] bevy::asset::LoadDirectError),
}
impl AssetLoader for CoolTextLoader {
type Asset = CoolText;
type Settings = ();
type Error = CoolTextLoaderError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &Self::Settings,
load_context: &mut LoadContext<'_>,
) -> Result<CoolText, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let ron: CoolTextRon = ron::de::from_bytes(&bytes)?;
let mut base_text = ron.text;
for embedded in ron.embedded_dependencies {
let loaded = load_context
.loader()
.immediate()
.load::<Text>(&embedded)
.await?;
base_text.push_str(&loaded.get().0);
}
for (path, settings_override) in ron.dependencies_with_settings {
let loaded = load_context
.loader()
.with_settings(move |settings| {
*settings = settings_override.clone();
})
.immediate()
.load::<Text>(&path)
.await?;
base_text.push_str(&loaded.get().0);
}
Ok(CoolText {
text: base_text,
dependencies: ron
.dependencies
.iter()
.map(|p| load_context.load(p))
.collect(),
})
}
fn extensions(&self) -> &[&str] {
&["cool.ron"]
}
}
#[derive(Default, TypePath)]
struct CoolTextTransformer;
#[derive(Default, Serialize, Deserialize)]
struct CoolTextTransformerSettings {
appended: String,
}
impl AssetTransformer for CoolTextTransformer {
type AssetInput = CoolText;
type AssetOutput = CoolText;
type Settings = CoolTextTransformerSettings;
type Error = Infallible;
async fn transform<'a>(
&'a self,
mut asset: TransformedAsset<Self::AssetInput>,
settings: &'a Self::Settings,
) -> Result<TransformedAsset<Self::AssetOutput>, Self::Error> {
asset.text = format!("{}{}", asset.text, settings.appended);
Ok(asset)
}
}
#[derive(TypePath)]
struct CoolTextSaver;
impl AssetSaver for CoolTextSaver {
type Asset = CoolText;
type Settings = ();
type OutputLoader = TextLoader;
type Error = std::io::Error;
async fn save(
&self,
writer: &mut Writer,
asset: SavedAsset<'_, Self::Asset>,
_settings: &Self::Settings,
) -> Result<TextSettings, Self::Error> {
writer.write_all(asset.text.as_bytes()).await?;
Ok(TextSettings::default())
}
}
#[derive(Resource)]
struct TextAssets {
a: Handle<Text>,
b: Handle<Text>,
c: Handle<Text>,
d: Handle<Text>,
e: Handle<Text>,
}
fn setup(mut commands: Commands, assets: Res<AssetServer>) {
// This the final processed versions of `assets/a.cool.ron` and `assets/foo.c.cool.ron`
// Check out their counterparts in `imported_assets` to see what the outputs look like.
commands.insert_resource(TextAssets {
a: assets.load("a.cool.ron"),
b: assets.load("foo/b.cool.ron"),
c: assets.load("foo/c.cool.ron"),
d: assets.load("d.cool.ron"),
e: assets.load("embedded://asset_processing/e.txt"),
});
}
fn print_text(
handles: Res<TextAssets>,
texts: Res<Assets<Text>>,
mut asset_events: MessageReader<AssetEvent<Text>>,
) {
if !asset_events.is_empty() {
// This prints the current values of the assets
// Hot-reloading is supported, so try modifying the source assets (and their meta files)!
println!("Current Values:");
println!(" a: {:?}", texts.get(&handles.a));
println!(" b: {:?}", texts.get(&handles.b));
println!(" c: {:?}", texts.get(&handles.c));
println!(" d: {:?}", texts.get(&handles.d));
println!(" e: {:?}", texts.get(&handles.e));
println!("(You can modify source assets and their .meta files to hot-reload changes!)");
println!();
asset_events.clear();
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/animation/custom_skinned_mesh.rs | examples/animation/custom_skinned_mesh.rs | //! Skinned mesh example with mesh and joints data defined in code.
//! Example taken from <https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_019_SimpleSkin.md>
use std::f32::consts::*;
use bevy::{
asset::RenderAssetUsages,
math::ops,
mesh::{
skinning::{SkinnedMesh, SkinnedMeshInverseBindposes},
Indices, PrimitiveTopology, VertexAttributeValues,
},
prelude::*,
};
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(GlobalAmbientLight {
brightness: 3000.0,
..default()
})
.add_systems(Startup, setup)
.add_systems(Update, joint_animation)
.run();
}
/// Used to mark a joint to be animated in the [`joint_animation`] system.
#[derive(Component)]
struct AnimatedJoint(isize);
/// Construct a mesh and a skeleton with 2 joints for that mesh,
/// and mark the second joint to be animated.
/// It is similar to the scene defined in `models/SimpleSkin/SimpleSkin.gltf`
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut skinned_mesh_inverse_bindposes_assets: ResMut<Assets<SkinnedMeshInverseBindposes>>,
) {
// Create a camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(2.5, 2.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
));
// Create inverse bindpose matrices for a skeleton consists of 2 joints
let inverse_bindposes = skinned_mesh_inverse_bindposes_assets.add(vec![
Mat4::from_translation(Vec3::new(-0.5, -1.0, 0.0)),
Mat4::from_translation(Vec3::new(-0.5, -1.0, 0.0)),
]);
// Create a mesh
let mesh = Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::RENDER_WORLD,
)
// Set mesh vertex positions
.with_inserted_attribute(
Mesh::ATTRIBUTE_POSITION,
vec![
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 0.5, 0.0],
[1.0, 0.5, 0.0],
[0.0, 1.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 1.5, 0.0],
[1.0, 1.5, 0.0],
[0.0, 2.0, 0.0],
[1.0, 2.0, 0.0],
],
)
// Add UV coordinates that map the left half of the texture since its a 1 x
// 2 rectangle.
.with_inserted_attribute(
Mesh::ATTRIBUTE_UV_0,
vec![
[0.0, 0.00],
[0.5, 0.00],
[0.0, 0.25],
[0.5, 0.25],
[0.0, 0.50],
[0.5, 0.50],
[0.0, 0.75],
[0.5, 0.75],
[0.0, 1.00],
[0.5, 1.00],
],
)
// Set mesh vertex normals
.with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, vec![[0.0, 0.0, 1.0]; 10])
// Set mesh vertex joint indices for mesh skinning.
// Each vertex gets 4 indices used to address the `JointTransforms` array in the vertex shader
// as well as `SkinnedMeshJoint` array in the `SkinnedMesh` component.
// This means that a maximum of 4 joints can affect a single vertex.
.with_inserted_attribute(
Mesh::ATTRIBUTE_JOINT_INDEX,
// Need to be explicit here as [u16; 4] could be either Uint16x4 or Unorm16x4.
VertexAttributeValues::Uint16x4(vec![
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
]),
)
// Set mesh vertex joint weights for mesh skinning.
// Each vertex gets 4 joint weights corresponding to the 4 joint indices assigned to it.
// The sum of these weights should equal to 1.
.with_inserted_attribute(
Mesh::ATTRIBUTE_JOINT_WEIGHT,
vec![
[1.00, 0.00, 0.0, 0.0],
[1.00, 0.00, 0.0, 0.0],
[0.75, 0.25, 0.0, 0.0],
[0.75, 0.25, 0.0, 0.0],
[0.50, 0.50, 0.0, 0.0],
[0.50, 0.50, 0.0, 0.0],
[0.25, 0.75, 0.0, 0.0],
[0.25, 0.75, 0.0, 0.0],
[0.00, 1.00, 0.0, 0.0],
[0.00, 1.00, 0.0, 0.0],
],
)
// Tell bevy to construct triangles from a list of vertex indices,
// where each 3 vertex indices form a triangle.
.with_inserted_indices(Indices::U16(vec![
0, 1, 3, 0, 3, 2, 2, 3, 5, 2, 5, 4, 4, 5, 7, 4, 7, 6, 6, 7, 9, 6, 9, 8,
]));
let mesh = meshes.add(mesh);
// We're seeding the PRNG here to make this example deterministic for testing purposes.
// This isn't strictly required in practical use unless you need your app to be deterministic.
let mut rng = ChaCha8Rng::seed_from_u64(42);
for i in -5..5 {
// Create joint entities
let joint_0 = commands
.spawn(Transform::from_xyz(
i as f32 * 1.5,
0.0,
// Move quads back a small amount to avoid Z-fighting and not
// obscure the transform gizmos.
-(i as f32 * 0.01).abs(),
))
.id();
let joint_1 = commands.spawn((AnimatedJoint(i), Transform::IDENTITY)).id();
// Set joint_1 as a child of joint_0.
commands.entity(joint_0).add_children(&[joint_1]);
// Each joint in this vector corresponds to each inverse bindpose matrix in `SkinnedMeshInverseBindposes`.
let joint_entities = vec![joint_0, joint_1];
// Create skinned mesh renderer. Note that its transform doesn't affect the position of the mesh.
commands.spawn((
Mesh3d(mesh.clone()),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: Color::srgb(
rng.random_range(0.0..1.0),
rng.random_range(0.0..1.0),
rng.random_range(0.0..1.0),
),
base_color_texture: Some(asset_server.load("textures/uv_checker_bw.png")),
..default()
})),
SkinnedMesh {
inverse_bindposes: inverse_bindposes.clone(),
joints: joint_entities,
},
));
}
}
/// Animate the joint marked with [`AnimatedJoint`] component.
fn joint_animation(
time: Res<Time>,
mut query: Query<(&mut Transform, &AnimatedJoint)>,
mut gizmos: Gizmos,
) {
for (mut transform, animated_joint) in &mut query {
match animated_joint.0 {
-5 => {
transform.rotation =
Quat::from_rotation_x(FRAC_PI_2 * ops::sin(time.elapsed_secs()));
}
-4 => {
transform.rotation =
Quat::from_rotation_y(FRAC_PI_2 * ops::sin(time.elapsed_secs()));
}
-3 => {
transform.rotation =
Quat::from_rotation_z(FRAC_PI_2 * ops::sin(time.elapsed_secs()));
}
-2 => {
transform.scale.x = ops::sin(time.elapsed_secs()) + 1.0;
}
-1 => {
transform.scale.y = ops::sin(time.elapsed_secs()) + 1.0;
}
0 => {
transform.translation.x = 0.5 * ops::sin(time.elapsed_secs());
transform.translation.y = ops::cos(time.elapsed_secs());
}
1 => {
transform.translation.y = ops::sin(time.elapsed_secs());
transform.translation.z = ops::cos(time.elapsed_secs());
}
2 => {
transform.translation.x = ops::sin(time.elapsed_secs());
}
3 => {
transform.translation.y = ops::sin(time.elapsed_secs());
transform.scale.x = ops::sin(time.elapsed_secs()) + 1.0;
}
_ => (),
}
// Show transform
let mut axis = *transform;
axis.translation.x += animated_joint.0 as f32 * 1.5;
gizmos.axes(axis, 1.0);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/animation/easing_functions.rs | examples/animation/easing_functions.rs | //! Demonstrates the behavior of the built-in easing functions.
use bevy::prelude::*;
#[derive(Component)]
#[require(Visibility, Transform)]
struct EaseFunctionPlot(EaseFunction, Color);
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, display_curves)
.run();
}
const COLS: usize = 12;
const EXTENT: Vec2 = Vec2::new(1172.0, 520.0);
const PLOT_SIZE: Vec2 = Vec2::splat(80.0);
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
let text_font = TextFont {
font_size: 10.0,
..default()
};
let chunks = [
// "In" row
EaseFunction::SineIn,
EaseFunction::QuadraticIn,
EaseFunction::CubicIn,
EaseFunction::QuarticIn,
EaseFunction::QuinticIn,
EaseFunction::SmoothStepIn,
EaseFunction::SmootherStepIn,
EaseFunction::CircularIn,
EaseFunction::ExponentialIn,
EaseFunction::ElasticIn,
EaseFunction::BackIn,
EaseFunction::BounceIn,
// "Out" row
EaseFunction::SineOut,
EaseFunction::QuadraticOut,
EaseFunction::CubicOut,
EaseFunction::QuarticOut,
EaseFunction::QuinticOut,
EaseFunction::SmoothStepOut,
EaseFunction::SmootherStepOut,
EaseFunction::CircularOut,
EaseFunction::ExponentialOut,
EaseFunction::ElasticOut,
EaseFunction::BackOut,
EaseFunction::BounceOut,
// "InOut" row
EaseFunction::SineInOut,
EaseFunction::QuadraticInOut,
EaseFunction::CubicInOut,
EaseFunction::QuarticInOut,
EaseFunction::QuinticInOut,
EaseFunction::SmoothStep,
EaseFunction::SmootherStep,
EaseFunction::CircularInOut,
EaseFunction::ExponentialInOut,
EaseFunction::ElasticInOut,
EaseFunction::BackInOut,
EaseFunction::BounceInOut,
// "Other" row
EaseFunction::Linear,
EaseFunction::Steps(4, JumpAt::End),
EaseFunction::Steps(4, JumpAt::Start),
EaseFunction::Steps(4, JumpAt::Both),
EaseFunction::Steps(4, JumpAt::None),
EaseFunction::Elastic(50.0),
]
.chunks(COLS);
let max_rows = chunks.clone().count();
let half_extent = EXTENT / 2.;
let half_size = PLOT_SIZE / 2.;
for (row, functions) in chunks.enumerate() {
for (col, function) in functions.iter().enumerate() {
let color = Hsla::hsl(col as f32 / COLS as f32 * 360.0, 0.8, 0.75).into();
commands.spawn((
EaseFunctionPlot(*function, color),
Transform::from_xyz(
-half_extent.x + EXTENT.x / (COLS - 1) as f32 * col as f32,
half_extent.y - EXTENT.y / (max_rows - 1) as f32 * row as f32,
0.0,
),
children![
(
Sprite::from_color(color, Vec2::splat(5.0)),
Transform::from_xyz(half_size.x + 5.0, -half_size.y, 0.0),
),
(
Sprite::from_color(color, Vec2::splat(4.0)),
Transform::from_xyz(-half_size.x, -half_size.y, 0.0),
),
(
Text2d(format!("{function:?}")),
text_font.clone(),
TextColor(color),
Transform::from_xyz(0.0, -half_size.y - 15.0, 0.0),
)
],
));
}
}
commands.spawn((
Text::default(),
Node {
position_type: PositionType::Absolute,
top: px(12),
left: px(12),
..default()
},
));
}
fn display_curves(
mut gizmos: Gizmos,
ease_functions: Query<(&EaseFunctionPlot, &Transform, &Children)>,
mut transforms: Query<&mut Transform, Without<EaseFunctionPlot>>,
mut ui_text: Single<&mut Text>,
time: Res<Time>,
) {
let samples = 100;
let duration = 2.5;
let time_margin = 0.5;
let now = ((time.elapsed_secs() % (duration + time_margin * 2.0) - time_margin) / duration)
.clamp(0.0, 1.0);
ui_text.0 = format!("Progress: {now:.2}");
for (EaseFunctionPlot(function, color), transform, children) in &ease_functions {
let center = transform.translation.xy();
let half_size = PLOT_SIZE / 2.0;
// Draw a box around the curve
gizmos.linestrip_2d(
[
center + half_size,
center + half_size * Vec2::new(-1., 1.),
center + half_size * Vec2::new(-1., -1.),
center + half_size * Vec2::new(1., -1.),
center + half_size,
],
color.darker(0.4),
);
// Draw the curve
let f = EasingCurve::new(0.0, 1.0, *function);
let drawn_curve = f
.by_ref()
.graph()
.map(|(x, y)| center - half_size + Vec2::new(x, y) * PLOT_SIZE);
gizmos.curve_2d(
&drawn_curve,
drawn_curve.domain().spaced_points(samples).unwrap(),
*color,
);
// Show progress along the curve for the current time
let y = f.sample(now).unwrap() * PLOT_SIZE.y;
transforms.get_mut(children[0]).unwrap().translation.y = -half_size.y + y;
transforms.get_mut(children[1]).unwrap().translation =
-half_size.extend(0.0) + Vec3::new(now * PLOT_SIZE.x, y, 0.0);
// Show horizontal bar at y value
gizmos.linestrip_2d(
[
center - half_size + Vec2::Y * y,
center - half_size + Vec2::new(PLOT_SIZE.x, y),
],
color.darker(0.2),
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/animation/animation_masks.rs | examples/animation/animation_masks.rs | //! Demonstrates how to use masks to limit the scope of animations.
use bevy::{
animation::{AnimatedBy, AnimationTargetId},
color::palettes::css::{LIGHT_GRAY, WHITE},
prelude::*,
};
use std::collections::HashSet;
// IDs of the mask groups we define for the running fox model.
//
// Each mask group defines a set of bones for which animations can be toggled on
// and off.
const MASK_GROUP_HEAD: u32 = 0;
const MASK_GROUP_LEFT_FRONT_LEG: u32 = 1;
const MASK_GROUP_RIGHT_FRONT_LEG: u32 = 2;
const MASK_GROUP_LEFT_HIND_LEG: u32 = 3;
const MASK_GROUP_RIGHT_HIND_LEG: u32 = 4;
const MASK_GROUP_TAIL: u32 = 5;
// The width in pixels of the small buttons that allow the user to toggle a mask
// group on or off.
const MASK_GROUP_BUTTON_WIDTH: f32 = 250.0;
// The names of the bones that each mask group consists of. Each mask group is
// defined as a (prefix, suffix) tuple. The mask group consists of a single
// bone chain rooted at the prefix. For example, if the chain's prefix is
// "A/B/C" and the suffix is "D/E", then the bones that will be included in the
// mask group are "A/B/C", "A/B/C/D", and "A/B/C/D/E".
//
// The fact that our mask groups are single chains of bones isn't an engine
// requirement; it just so happens to be the case for the model we're using. A
// mask group can consist of any set of animation targets, regardless of whether
// they form a single chain.
const MASK_GROUP_PATHS: [(&str, &str); 6] = [
// Head
(
"root/_rootJoint/b_Root_00/b_Hip_01/b_Spine01_02/b_Spine02_03",
"b_Neck_04/b_Head_05",
),
// Left front leg
(
"root/_rootJoint/b_Root_00/b_Hip_01/b_Spine01_02/b_Spine02_03/b_LeftUpperArm_09",
"b_LeftForeArm_010/b_LeftHand_011",
),
// Right front leg
(
"root/_rootJoint/b_Root_00/b_Hip_01/b_Spine01_02/b_Spine02_03/b_RightUpperArm_06",
"b_RightForeArm_07/b_RightHand_08",
),
// Left hind leg
(
"root/_rootJoint/b_Root_00/b_Hip_01/b_LeftLeg01_015",
"b_LeftLeg02_016/b_LeftFoot01_017/b_LeftFoot02_018",
),
// Right hind leg
(
"root/_rootJoint/b_Root_00/b_Hip_01/b_RightLeg01_019",
"b_RightLeg02_020/b_RightFoot01_021/b_RightFoot02_022",
),
// Tail
(
"root/_rootJoint/b_Root_00/b_Hip_01/b_Tail01_012",
"b_Tail02_013/b_Tail03_014",
),
];
#[derive(Clone, Copy, Component)]
struct AnimationControl {
// The ID of the mask group that this button controls.
group_id: u32,
label: AnimationLabel,
}
#[derive(Clone, Copy, Component, PartialEq, Debug)]
enum AnimationLabel {
Idle = 0,
Walk = 1,
Run = 2,
Off = 3,
}
#[derive(Clone, Debug, Resource)]
struct AnimationNodes([AnimationNodeIndex; 3]);
#[derive(Clone, Copy, Debug, Resource)]
struct AppState([MaskGroupState; 6]);
#[derive(Clone, Copy, Debug)]
struct MaskGroupState {
clip: u8,
}
// The application entry point.
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
title: "Bevy Animation Masks Example".into(),
..default()
}),
..default()
}))
.add_systems(Startup, (setup_scene, setup_ui))
.add_systems(Update, setup_animation_graph_once_loaded)
.add_systems(Update, handle_button_toggles)
.add_systems(Update, update_ui)
.insert_resource(GlobalAmbientLight {
color: WHITE.into(),
brightness: 100.0,
..default()
})
.init_resource::<AppState>()
.run();
}
// Spawns the 3D objects in the scene, and loads the fox animation from the glTF
// file.
fn setup_scene(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Spawn the camera.
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-15.0, 10.0, 20.0).looking_at(Vec3::new(0., 1., 0.), Vec3::Y),
));
// Spawn the light.
commands.spawn((
PointLight {
intensity: 10_000_000.0,
shadows_enabled: true,
..default()
},
Transform::from_xyz(-4.0, 8.0, 13.0),
));
// Spawn the fox.
commands.spawn((
SceneRoot(
asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/animated/Fox.glb")),
),
Transform::from_scale(Vec3::splat(0.07)),
));
// Spawn the ground.
commands.spawn((
Mesh3d(meshes.add(Circle::new(7.0))),
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
));
}
// Creates the UI.
fn setup_ui(mut commands: Commands) {
// Add help text.
commands.spawn((
Text::new("Click on a button to toggle animations for its associated bones"),
Node {
position_type: PositionType::Absolute,
left: px(12),
top: px(12),
..default()
},
));
// Add the buttons that allow the user to toggle mask groups on and off.
commands.spawn((
Node {
flex_direction: FlexDirection::Column,
position_type: PositionType::Absolute,
row_gap: px(6),
left: px(12),
bottom: px(12),
..default()
},
children![
new_mask_group_control("Head", auto(), MASK_GROUP_HEAD),
(
Node {
flex_direction: FlexDirection::Row,
column_gap: px(6),
..default()
},
children![
new_mask_group_control(
"Left Front Leg",
px(MASK_GROUP_BUTTON_WIDTH),
MASK_GROUP_LEFT_FRONT_LEG,
),
new_mask_group_control(
"Right Front Leg",
px(MASK_GROUP_BUTTON_WIDTH),
MASK_GROUP_RIGHT_FRONT_LEG,
)
],
),
(
Node {
flex_direction: FlexDirection::Row,
column_gap: px(6),
..default()
},
children![
new_mask_group_control(
"Left Hind Leg",
px(MASK_GROUP_BUTTON_WIDTH),
MASK_GROUP_LEFT_HIND_LEG,
),
new_mask_group_control(
"Right Hind Leg",
px(MASK_GROUP_BUTTON_WIDTH),
MASK_GROUP_RIGHT_HIND_LEG,
)
]
),
new_mask_group_control("Tail", auto(), MASK_GROUP_TAIL),
],
));
}
// Adds a button that allows the user to toggle a mask group on and off.
//
// The button will automatically become a child of the parent that owns the
// given `ChildSpawnerCommands`.
fn new_mask_group_control(label: &str, width: Val, mask_group_id: u32) -> impl Bundle {
let button_text_style = (
TextFont {
font_size: 14.0,
..default()
},
TextColor::WHITE,
);
let selected_button_text_style = (button_text_style.0.clone(), TextColor::BLACK);
let label_text_style = (
button_text_style.0.clone(),
TextColor(Color::Srgba(LIGHT_GRAY)),
);
let make_animation_label = {
let button_text_style = button_text_style.clone();
let selected_button_text_style = selected_button_text_style.clone();
move |first: bool, label: AnimationLabel| {
(
Button,
BackgroundColor(if !first { Color::BLACK } else { Color::WHITE }),
Node {
flex_grow: 1.0,
border: if !first {
UiRect::left(px(1))
} else {
UiRect::ZERO
},
..default()
},
BorderColor::all(Color::WHITE),
AnimationControl {
group_id: mask_group_id,
label,
},
children![(
Text(format!("{label:?}")),
if !first {
button_text_style.clone()
} else {
selected_button_text_style.clone()
},
TextLayout::new_with_justify(Justify::Center),
Node {
flex_grow: 1.0,
margin: UiRect::vertical(px(3)),
..default()
},
)],
)
}
};
(
Node {
border: UiRect::all(px(1)),
width,
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
padding: UiRect::ZERO,
margin: UiRect::ZERO,
border_radius: BorderRadius::all(px(3)),
..default()
},
BorderColor::all(Color::WHITE),
BackgroundColor(Color::BLACK),
children![
(
Node {
border: UiRect::ZERO,
width: percent(100),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
padding: UiRect::ZERO,
margin: UiRect::ZERO,
..default()
},
BackgroundColor(Color::BLACK),
children![(
Text::new(label),
label_text_style.clone(),
Node {
margin: UiRect::vertical(px(3)),
..default()
},
)]
),
(
Node {
width: percent(100),
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
border: UiRect::top(px(1)),
..default()
},
BorderColor::all(Color::WHITE),
children![
make_animation_label(true, AnimationLabel::Run),
make_animation_label(false, AnimationLabel::Walk),
make_animation_label(false, AnimationLabel::Idle),
make_animation_label(false, AnimationLabel::Off),
]
)
],
)
}
// Builds up the animation graph, including the mask groups, and adds it to the
// entity with the `AnimationPlayer` that the glTF loader created.
fn setup_animation_graph_once_loaded(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut animation_graphs: ResMut<Assets<AnimationGraph>>,
mut players: Query<(Entity, &mut AnimationPlayer), Added<AnimationPlayer>>,
targets: Query<(Entity, &AnimationTargetId)>,
) {
for (entity, mut player) in &mut players {
// Load the animation clip from the glTF file.
let mut animation_graph = AnimationGraph::new();
let blend_node = animation_graph.add_additive_blend(1.0, animation_graph.root);
let animation_graph_nodes: [AnimationNodeIndex; 3] =
std::array::from_fn(|animation_index| {
let handle = asset_server.load(
GltfAssetLabel::Animation(animation_index)
.from_asset("models/animated/Fox.glb"),
);
let mask = if animation_index == 0 { 0 } else { 0x3f };
animation_graph.add_clip_with_mask(handle, mask, 1.0, blend_node)
});
// Create each mask group.
let mut all_animation_target_ids = HashSet::new();
for (mask_group_index, (mask_group_prefix, mask_group_suffix)) in
MASK_GROUP_PATHS.iter().enumerate()
{
// Split up the prefix and suffix, and convert them into `Name`s.
let prefix: Vec<_> = mask_group_prefix.split('/').map(Name::new).collect();
let suffix: Vec<_> = mask_group_suffix.split('/').map(Name::new).collect();
// Add each bone in the chain to the appropriate mask group.
for chain_length in 0..=suffix.len() {
let animation_target_id = AnimationTargetId::from_names(
prefix.iter().chain(suffix[0..chain_length].iter()),
);
animation_graph
.add_target_to_mask_group(animation_target_id, mask_group_index as u32);
all_animation_target_ids.insert(animation_target_id);
}
}
// We're doing constructing the animation graph. Add it as an asset.
let animation_graph = animation_graphs.add(animation_graph);
commands
.entity(entity)
.insert(AnimationGraphHandle(animation_graph));
// Remove animation targets that aren't in any of the mask groups. If we
// don't do that, those bones will play all animations at once, which is
// ugly.
for (target_entity, target) in &targets {
if !all_animation_target_ids.contains(target) {
commands
.entity(target_entity)
.remove::<AnimationTargetId>()
.remove::<AnimatedBy>();
}
}
// Play the animation.
for animation_graph_node in animation_graph_nodes {
player.play(animation_graph_node).repeat();
}
// Record the graph nodes.
commands.insert_resource(AnimationNodes(animation_graph_nodes));
}
}
// A system that handles requests from the user to toggle mask groups on and
// off.
fn handle_button_toggles(
mut interactions: Query<(&Interaction, &mut AnimationControl), Changed<Interaction>>,
mut animation_players: Query<&AnimationGraphHandle, With<AnimationPlayer>>,
mut animation_graphs: ResMut<Assets<AnimationGraph>>,
mut animation_nodes: Option<ResMut<AnimationNodes>>,
mut app_state: ResMut<AppState>,
) {
let Some(ref mut animation_nodes) = animation_nodes else {
return;
};
for (interaction, animation_control) in interactions.iter_mut() {
// We only care about press events.
if *interaction != Interaction::Pressed {
continue;
}
// Toggle the state of the clip.
app_state.0[animation_control.group_id as usize].clip = animation_control.label as u8;
// Now grab the animation player. (There's only one in our case, but we
// iterate just for clarity's sake.)
for animation_graph_handle in animation_players.iter_mut() {
// The animation graph needs to have loaded.
let Some(animation_graph) = animation_graphs.get_mut(animation_graph_handle) else {
continue;
};
for (clip_index, &animation_node_index) in animation_nodes.0.iter().enumerate() {
let Some(animation_node) = animation_graph.get_mut(animation_node_index) else {
continue;
};
if animation_control.label as usize == clip_index {
animation_node.mask &= !(1 << animation_control.group_id);
} else {
animation_node.mask |= 1 << animation_control.group_id;
}
}
}
}
}
// A system that updates the UI based on the current app state.
fn update_ui(
mut animation_controls: Query<(&AnimationControl, &mut BackgroundColor, &Children)>,
texts: Query<Entity, With<Text>>,
mut writer: TextUiWriter,
app_state: Res<AppState>,
) {
for (animation_control, mut background_color, kids) in animation_controls.iter_mut() {
let enabled =
app_state.0[animation_control.group_id as usize].clip == animation_control.label as u8;
*background_color = if enabled {
BackgroundColor(Color::WHITE)
} else {
BackgroundColor(Color::BLACK)
};
for &kid in kids {
let Ok(text) = texts.get(kid) else {
continue;
};
writer.for_each_color(text, |mut color| {
color.0 = if enabled { Color::BLACK } else { Color::WHITE };
});
}
}
}
impl Default for AppState {
fn default() -> Self {
AppState([MaskGroupState { clip: 0 }; 6])
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/animation/morph_targets.rs | examples/animation/morph_targets.rs | //! Play an animation with morph targets.
//!
//! Also illustrates how to read morph target names in `name_morphs`.
use bevy::{prelude::*, scene::SceneInstanceReady};
use std::f32::consts::PI;
const GLTF_PATH: &str = "models/animated/MorphStressTest.gltf";
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(GlobalAmbientLight {
brightness: 150.0,
..default()
})
.add_systems(Startup, setup)
.add_systems(Update, name_morphs)
.run();
}
#[derive(Component)]
struct AnimationToPlay {
graph_handle: Handle<AnimationGraph>,
index: AnimationNodeIndex,
}
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut graphs: ResMut<Assets<AnimationGraph>>,
) {
let (graph, index) = AnimationGraph::from_clip(
asset_server.load(GltfAssetLabel::Animation(2).from_asset(GLTF_PATH)),
);
commands
.spawn((
AnimationToPlay {
graph_handle: graphs.add(graph),
index,
},
SceneRoot(asset_server.load(GltfAssetLabel::Scene(0).from_asset(GLTF_PATH))),
))
.observe(play_animation_when_ready);
commands.spawn((
DirectionalLight::default(),
Transform::from_rotation(Quat::from_rotation_z(PI / 2.0)),
));
commands.spawn((
Camera3d::default(),
Transform::from_xyz(3.0, 2.1, 10.2).looking_at(Vec3::ZERO, Vec3::Y),
));
}
fn play_animation_when_ready(
scene_ready: On<SceneInstanceReady>,
mut commands: Commands,
children: Query<&Children>,
animations_to_play: Query<&AnimationToPlay>,
mut players: Query<&mut AnimationPlayer>,
) {
if let Ok(animation_to_play) = animations_to_play.get(scene_ready.entity) {
for child in children.iter_descendants(scene_ready.entity) {
if let Ok(mut player) = players.get_mut(child) {
player.play(animation_to_play.index).repeat();
commands
.entity(child)
.insert(AnimationGraphHandle(animation_to_play.graph_handle.clone()));
}
}
}
}
/// Whenever a mesh asset is loaded, print the name of the asset and the names
/// of its morph targets.
fn name_morphs(
asset_server: Res<AssetServer>,
mut events: MessageReader<AssetEvent<Mesh>>,
meshes: Res<Assets<Mesh>>,
) {
for event in events.read() {
if let AssetEvent::<Mesh>::Added { id } = event
&& let Some(path) = asset_server.get_path(*id)
&& let Some(mesh) = meshes.get(*id)
&& let Some(names) = mesh.morph_target_names()
{
info!("Morph target names for {path:?}:");
for name in names {
info!(" {name}");
}
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/animation/animated_mesh_control.rs | examples/animation/animated_mesh_control.rs | //! Plays animations from a skinned glTF.
use std::{f32::consts::PI, time::Duration};
use bevy::{animation::RepeatAnimation, light::CascadeShadowConfigBuilder, prelude::*};
const FOX_PATH: &str = "models/animated/Fox.glb";
fn main() {
App::new()
.insert_resource(GlobalAmbientLight {
color: Color::WHITE,
brightness: 2000.,
..default()
})
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, setup_scene_once_loaded)
.add_systems(Update, keyboard_control)
.run();
}
#[derive(Resource)]
struct Animations {
animations: Vec<AnimationNodeIndex>,
graph_handle: Handle<AnimationGraph>,
}
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut graphs: ResMut<Assets<AnimationGraph>>,
) {
// Build the animation graph
let (graph, node_indices) = AnimationGraph::from_clips([
asset_server.load(GltfAssetLabel::Animation(2).from_asset(FOX_PATH)),
asset_server.load(GltfAssetLabel::Animation(1).from_asset(FOX_PATH)),
asset_server.load(GltfAssetLabel::Animation(0).from_asset(FOX_PATH)),
]);
// Keep our animation graph in a Resource so that it can be inserted onto
// the correct entity once the scene actually loads.
let graph_handle = graphs.add(graph);
commands.insert_resource(Animations {
animations: node_indices,
graph_handle,
});
// Camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(100.0, 100.0, 150.0).looking_at(Vec3::new(0.0, 20.0, 0.0), Vec3::Y),
));
// Plane
commands.spawn((
Mesh3d(meshes.add(Plane3d::default().mesh().size(500000.0, 500000.0))),
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
));
// Light
commands.spawn((
Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
DirectionalLight {
shadows_enabled: true,
..default()
},
CascadeShadowConfigBuilder {
first_cascade_far_bound: 200.0,
maximum_distance: 400.0,
..default()
}
.build(),
));
// Fox
commands.spawn(SceneRoot(
asset_server.load(GltfAssetLabel::Scene(0).from_asset(FOX_PATH)),
));
// Instructions
commands.spawn((
Text::new(concat!(
"space: play / pause\n",
"up / down: playback speed\n",
"left / right: seek\n",
"1-3: play N times\n",
"L: loop forever\n",
"return: change animation\n",
)),
Node {
position_type: PositionType::Absolute,
top: px(12),
left: px(12),
..default()
},
));
}
// An `AnimationPlayer` is automatically added to the scene when it's ready.
// When the player is added, start the animation.
fn setup_scene_once_loaded(
mut commands: Commands,
animations: Res<Animations>,
mut players: Query<(Entity, &mut AnimationPlayer), Added<AnimationPlayer>>,
) {
for (entity, mut player) in &mut players {
let mut transitions = AnimationTransitions::new();
// Make sure to start the animation via the `AnimationTransitions`
// component. The `AnimationTransitions` component wants to manage all
// the animations and will get confused if the animations are started
// directly via the `AnimationPlayer`.
transitions
.play(&mut player, animations.animations[0], Duration::ZERO)
.repeat();
commands
.entity(entity)
.insert(AnimationGraphHandle(animations.graph_handle.clone()))
.insert(transitions);
}
}
fn keyboard_control(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut animation_players: Query<(&mut AnimationPlayer, &mut AnimationTransitions)>,
animations: Res<Animations>,
mut current_animation: Local<usize>,
) {
for (mut player, mut transitions) in &mut animation_players {
let Some((&playing_animation_index, _)) = player.playing_animations().next() else {
continue;
};
if keyboard_input.just_pressed(KeyCode::Space) {
let playing_animation = player.animation_mut(playing_animation_index).unwrap();
if playing_animation.is_paused() {
playing_animation.resume();
} else {
playing_animation.pause();
}
}
if keyboard_input.just_pressed(KeyCode::ArrowUp) {
let playing_animation = player.animation_mut(playing_animation_index).unwrap();
let speed = playing_animation.speed();
playing_animation.set_speed(speed * 1.2);
}
if keyboard_input.just_pressed(KeyCode::ArrowDown) {
let playing_animation = player.animation_mut(playing_animation_index).unwrap();
let speed = playing_animation.speed();
playing_animation.set_speed(speed * 0.8);
}
if keyboard_input.just_pressed(KeyCode::ArrowLeft) {
let playing_animation = player.animation_mut(playing_animation_index).unwrap();
let elapsed = playing_animation.seek_time();
playing_animation.seek_to(elapsed - 0.1);
}
if keyboard_input.just_pressed(KeyCode::ArrowRight) {
let playing_animation = player.animation_mut(playing_animation_index).unwrap();
let elapsed = playing_animation.seek_time();
playing_animation.seek_to(elapsed + 0.1);
}
if keyboard_input.just_pressed(KeyCode::Enter) {
*current_animation = (*current_animation + 1) % animations.animations.len();
transitions
.play(
&mut player,
animations.animations[*current_animation],
Duration::from_millis(250),
)
.repeat();
}
if keyboard_input.just_pressed(KeyCode::Digit1) {
let playing_animation = player.animation_mut(playing_animation_index).unwrap();
playing_animation
.set_repeat(RepeatAnimation::Count(1))
.replay();
}
if keyboard_input.just_pressed(KeyCode::Digit2) {
let playing_animation = player.animation_mut(playing_animation_index).unwrap();
playing_animation
.set_repeat(RepeatAnimation::Count(2))
.replay();
}
if keyboard_input.just_pressed(KeyCode::Digit3) {
let playing_animation = player.animation_mut(playing_animation_index).unwrap();
playing_animation
.set_repeat(RepeatAnimation::Count(3))
.replay();
}
if keyboard_input.just_pressed(KeyCode::KeyL) {
let playing_animation = player.animation_mut(playing_animation_index).unwrap();
playing_animation.set_repeat(RepeatAnimation::Forever);
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/animation/animated_mesh_events.rs | examples/animation/animated_mesh_events.rs | //! Plays animations from a skinned glTF.
use std::{f32::consts::PI, time::Duration};
use bevy::{
animation::{AnimationEvent, AnimationTargetId},
color::palettes::css::WHITE,
light::CascadeShadowConfigBuilder,
prelude::*,
};
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
const FOX_PATH: &str = "models/animated/Fox.glb";
fn main() {
App::new()
.insert_resource(GlobalAmbientLight {
color: Color::WHITE,
brightness: 2000.,
..default()
})
.add_plugins(DefaultPlugins)
.init_resource::<ParticleAssets>()
.init_resource::<FoxFeetTargets>()
.add_systems(Startup, setup)
.add_systems(Update, setup_scene_once_loaded)
.add_systems(Update, simulate_particles)
.add_observer(observe_on_step)
.run();
}
#[derive(Resource)]
struct SeededRng(ChaCha8Rng);
#[derive(Resource)]
struct Animations {
index: AnimationNodeIndex,
graph_handle: Handle<AnimationGraph>,
}
#[derive(AnimationEvent, Reflect, Clone)]
struct Step;
fn observe_on_step(
step: On<Step>,
particle: Res<ParticleAssets>,
mut commands: Commands,
transforms: Query<&GlobalTransform>,
mut seeded_rng: ResMut<SeededRng>,
) -> Result {
let translation = transforms.get(step.trigger().target)?.translation();
// Spawn a bunch of particles.
for _ in 0..14 {
let horizontal = seeded_rng.0.random::<Dir2>() * seeded_rng.0.random_range(8.0..12.0);
let vertical = seeded_rng.0.random_range(0.0..4.0);
let size = seeded_rng.0.random_range(0.2..1.0);
commands.spawn((
Particle {
lifetime_timer: Timer::from_seconds(
seeded_rng.0.random_range(0.2..0.6),
TimerMode::Once,
),
size,
velocity: Vec3::new(horizontal.x, vertical, horizontal.y) * 10.0,
},
Mesh3d(particle.mesh.clone()),
MeshMaterial3d(particle.material.clone()),
Transform {
translation,
scale: Vec3::splat(size),
..Default::default()
},
));
}
Ok(())
}
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut graphs: ResMut<Assets<AnimationGraph>>,
) {
// Build the animation graph
let (graph, index) = AnimationGraph::from_clip(
// We specifically want the "run" animation, which is the third one.
asset_server.load(GltfAssetLabel::Animation(2).from_asset(FOX_PATH)),
);
// Insert a resource with the current scene information
let graph_handle = graphs.add(graph);
commands.insert_resource(Animations {
index,
graph_handle,
});
// Camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(100.0, 100.0, 150.0).looking_at(Vec3::new(0.0, 20.0, 0.0), Vec3::Y),
));
// Plane
commands.spawn((
Mesh3d(meshes.add(Plane3d::default().mesh().size(500000.0, 500000.0))),
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
));
// Light
commands.spawn((
Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
DirectionalLight {
shadows_enabled: true,
..default()
},
CascadeShadowConfigBuilder {
first_cascade_far_bound: 200.0,
maximum_distance: 400.0,
..default()
}
.build(),
));
// Fox
commands.spawn(SceneRoot(
asset_server.load(GltfAssetLabel::Scene(0).from_asset(FOX_PATH)),
));
// We're seeding the PRNG here to make this example deterministic for testing purposes.
// This isn't strictly required in practical use unless you need your app to be deterministic.
let seeded_rng = ChaCha8Rng::seed_from_u64(19878367467712);
commands.insert_resource(SeededRng(seeded_rng));
}
// An `AnimationPlayer` is automatically added to the scene when it's ready.
// When the player is added, start the animation.
fn setup_scene_once_loaded(
mut commands: Commands,
animations: Res<Animations>,
feet: Res<FoxFeetTargets>,
graphs: Res<Assets<AnimationGraph>>,
mut clips: ResMut<Assets<AnimationClip>>,
mut players: Query<(Entity, &mut AnimationPlayer), Added<AnimationPlayer>>,
) {
fn get_clip<'a>(
node: AnimationNodeIndex,
graph: &AnimationGraph,
clips: &'a mut Assets<AnimationClip>,
) -> &'a mut AnimationClip {
let node = graph.get(node).unwrap();
let clip = match &node.node_type {
AnimationNodeType::Clip(handle) => clips.get_mut(handle),
_ => unreachable!(),
};
clip.unwrap()
}
for (entity, mut player) in &mut players {
// Send `OnStep` events once the fox feet hits the ground in the running animation.
let graph = graphs.get(&animations.graph_handle).unwrap();
let running_animation = get_clip(animations.index, graph, &mut clips);
// You can determine the time an event should trigger if you know witch frame it occurs and
// the frame rate of the animation. Let's say we want to trigger an event at frame 15,
// and the animation has a frame rate of 24 fps, then time = 15 / 24 = 0.625.
running_animation.add_event_to_target(feet.front_left, 0.625, Step);
running_animation.add_event_to_target(feet.front_right, 0.5, Step);
running_animation.add_event_to_target(feet.back_left, 0.0, Step);
running_animation.add_event_to_target(feet.back_right, 0.125, Step);
// Start the animation
let mut transitions = AnimationTransitions::new();
// Make sure to start the animation via the `AnimationTransitions`
// component. The `AnimationTransitions` component wants to manage all
// the animations and will get confused if the animations are started
// directly via the `AnimationPlayer`.
transitions
.play(&mut player, animations.index, Duration::ZERO)
.repeat();
commands
.entity(entity)
.insert(AnimationGraphHandle(animations.graph_handle.clone()))
.insert(transitions);
}
}
fn simulate_particles(
mut commands: Commands,
mut query: Query<(Entity, &mut Transform, &mut Particle)>,
time: Res<Time>,
) {
for (entity, mut transform, mut particle) in &mut query {
if particle.lifetime_timer.tick(time.delta()).just_finished() {
commands.entity(entity).despawn();
return;
}
transform.translation += particle.velocity * time.delta_secs();
transform.scale = Vec3::splat(particle.size.lerp(0.0, particle.lifetime_timer.fraction()));
particle
.velocity
.smooth_nudge(&Vec3::ZERO, 4.0, time.delta_secs());
}
}
#[derive(Component)]
struct Particle {
lifetime_timer: Timer,
size: f32,
velocity: Vec3,
}
#[derive(Resource)]
struct ParticleAssets {
mesh: Handle<Mesh>,
material: Handle<StandardMaterial>,
}
impl FromWorld for ParticleAssets {
fn from_world(world: &mut World) -> Self {
Self {
mesh: world.add_asset::<Mesh>(Sphere::new(10.0)),
material: world.add_asset::<StandardMaterial>(StandardMaterial {
base_color: WHITE.into(),
..Default::default()
}),
}
}
}
/// Stores the `AnimationTargetId`s of the fox's feet
#[derive(Resource)]
struct FoxFeetTargets {
front_right: AnimationTargetId,
front_left: AnimationTargetId,
back_left: AnimationTargetId,
back_right: AnimationTargetId,
}
impl Default for FoxFeetTargets {
fn default() -> Self {
let hip_node = ["root", "_rootJoint", "b_Root_00", "b_Hip_01"];
let front_left_foot = hip_node.iter().chain(
[
"b_Spine01_02",
"b_Spine02_03",
"b_LeftUpperArm_09",
"b_LeftForeArm_010",
"b_LeftHand_011",
]
.iter(),
);
let front_right_foot = hip_node.iter().chain(
[
"b_Spine01_02",
"b_Spine02_03",
"b_RightUpperArm_06",
"b_RightForeArm_07",
"b_RightHand_08",
]
.iter(),
);
let back_left_foot = hip_node.iter().chain(
[
"b_LeftLeg01_015",
"b_LeftLeg02_016",
"b_LeftFoot01_017",
"b_LeftFoot02_018",
]
.iter(),
);
let back_right_foot = hip_node.iter().chain(
[
"b_RightLeg01_019",
"b_RightLeg02_020",
"b_RightFoot01_021",
"b_RightFoot02_022",
]
.iter(),
);
Self {
front_left: AnimationTargetId::from_iter(front_left_foot),
front_right: AnimationTargetId::from_iter(front_right_foot),
back_left: AnimationTargetId::from_iter(back_left_foot),
back_right: AnimationTargetId::from_iter(back_right_foot),
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/animation/animated_transform.rs | examples/animation/animated_transform.rs | //! Create and play an animation defined by code that operates on the [`Transform`] component.
use std::f32::consts::PI;
use bevy::{
animation::{animated_field, AnimatedBy, AnimationTargetId},
prelude::*,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(GlobalAmbientLight {
color: Color::WHITE,
brightness: 150.0,
..default()
})
.add_systems(Startup, setup)
.run();
}
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut animations: ResMut<Assets<AnimationClip>>,
mut graphs: ResMut<Assets<AnimationGraph>>,
) {
// Camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
));
// Light
commands.spawn((
PointLight {
intensity: 500_000.0,
..default()
},
Transform::from_xyz(0.0, 2.5, 0.0),
));
// Let's use the `Name` component to target entities. We can use anything we
// like, but names are convenient.
let planet = Name::new("planet");
let orbit_controller = Name::new("orbit_controller");
let satellite = Name::new("satellite");
// Creating the animation
let mut animation = AnimationClip::default();
// A curve can modify a single part of a transform: here, the translation.
let planet_animation_target_id = AnimationTargetId::from_name(&planet);
animation.add_curve_to_target(
planet_animation_target_id,
AnimatableCurve::new(
animated_field!(Transform::translation),
UnevenSampleAutoCurve::new([0.0, 1.0, 2.0, 3.0, 4.0].into_iter().zip([
Vec3::new(1.0, 0.0, 1.0),
Vec3::new(-1.0, 0.0, 1.0),
Vec3::new(-1.0, 0.0, -1.0),
Vec3::new(1.0, 0.0, -1.0),
// in case seamless looping is wanted, the last keyframe should
// be the same as the first one
Vec3::new(1.0, 0.0, 1.0),
]))
.expect("should be able to build translation curve because we pass in valid samples"),
),
);
// Or it can modify the rotation of the transform.
// To find the entity to modify, the hierarchy will be traversed looking for
// an entity with the right name at each level.
let orbit_controller_animation_target_id =
AnimationTargetId::from_names([planet.clone(), orbit_controller.clone()].iter());
animation.add_curve_to_target(
orbit_controller_animation_target_id,
AnimatableCurve::new(
animated_field!(Transform::rotation),
UnevenSampleAutoCurve::new([0.0, 1.0, 2.0, 3.0, 4.0].into_iter().zip([
Quat::IDENTITY,
Quat::from_axis_angle(Vec3::Y, PI / 2.),
Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
Quat::IDENTITY,
]))
.expect("Failed to build rotation curve"),
),
);
// If a curve in an animation is shorter than the other, it will not repeat
// until all other curves are finished. In that case, another animation should
// be created for each part that would have a different duration / period.
let satellite_animation_target_id = AnimationTargetId::from_names(
[planet.clone(), orbit_controller.clone(), satellite.clone()].iter(),
);
animation.add_curve_to_target(
satellite_animation_target_id,
AnimatableCurve::new(
animated_field!(Transform::scale),
UnevenSampleAutoCurve::new(
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]
.into_iter()
.zip([
Vec3::splat(0.8),
Vec3::splat(1.2),
Vec3::splat(0.8),
Vec3::splat(1.2),
Vec3::splat(0.8),
Vec3::splat(1.2),
Vec3::splat(0.8),
Vec3::splat(1.2),
Vec3::splat(0.8),
]),
)
.expect("Failed to build scale curve"),
),
);
// There can be more than one curve targeting the same entity path.
animation.add_curve_to_target(
AnimationTargetId::from_names(
[planet.clone(), orbit_controller.clone(), satellite.clone()].iter(),
),
AnimatableCurve::new(
animated_field!(Transform::rotation),
UnevenSampleAutoCurve::new([0.0, 1.0, 2.0, 3.0, 4.0].into_iter().zip([
Quat::IDENTITY,
Quat::from_axis_angle(Vec3::Y, PI / 2.),
Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
Quat::IDENTITY,
]))
.expect("should be able to build translation curve because we pass in valid samples"),
),
);
// Create the animation graph
let (graph, animation_index) = AnimationGraph::from_clip(animations.add(animation));
// Create the animation player, and set it to repeat
let mut player = AnimationPlayer::default();
player.play(animation_index).repeat();
// Create the scene that will be animated
// First entity is the planet
let planet_entity = commands
.spawn((
Mesh3d(meshes.add(Sphere::default())),
MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))),
// Add the animation graph and player
planet,
AnimationGraphHandle(graphs.add(graph)),
player,
))
.id();
commands.entity(planet_entity).insert((
planet_animation_target_id,
AnimatedBy(planet_entity),
children![(
Transform::default(),
Visibility::default(),
orbit_controller,
orbit_controller_animation_target_id,
AnimatedBy(planet_entity),
children![(
Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.9, 0.3))),
Transform::from_xyz(1.5, 0.0, 0.0),
satellite_animation_target_id,
AnimatedBy(planet_entity),
satellite,
)],
)],
));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/animation/animation_graph.rs | examples/animation/animation_graph.rs | //! Demonstrates animation blending with animation graphs.
//!
//! The animation graph is shown on screen. You can change the weights of the
//! playing animations by clicking and dragging left or right within the nodes.
use bevy::{
color::palettes::{
basic::WHITE,
css::{ANTIQUE_WHITE, DARK_GREEN},
},
prelude::*,
ui::RelativeCursorPosition,
};
use argh::FromArgs;
#[cfg(not(target_arch = "wasm32"))]
use {
bevy::{asset::io::file::FileAssetReader, tasks::IoTaskPool},
ron::ser::PrettyConfig,
std::{fs::File, path::Path},
};
/// Where to find the serialized animation graph.
static ANIMATION_GRAPH_PATH: &str = "animation_graphs/Fox.animgraph.ron";
/// The indices of the nodes containing animation clips in the graph.
static CLIP_NODE_INDICES: [u32; 3] = [2, 3, 4];
/// The help text in the upper left corner.
static HELP_TEXT: &str = "Click and drag an animation clip node to change its weight";
/// The node widgets in the UI.
static NODE_TYPES: [NodeType; 5] = [
NodeType::Clip(ClipNode::new("Idle", 0)),
NodeType::Clip(ClipNode::new("Walk", 1)),
NodeType::Blend("Root"),
NodeType::Blend("Blend\n0.5"),
NodeType::Clip(ClipNode::new("Run", 2)),
];
/// The positions of the node widgets in the UI.
///
/// These are in the same order as [`NODE_TYPES`] above.
static NODE_RECTS: [NodeRect; 5] = [
NodeRect::new(10.00, 10.00, 97.64, 48.41),
NodeRect::new(10.00, 78.41, 97.64, 48.41),
NodeRect::new(286.08, 78.41, 97.64, 48.41),
NodeRect::new(148.04, 112.61, 97.64, 48.41), // was 44.20
NodeRect::new(10.00, 146.82, 97.64, 48.41),
];
/// The positions of the horizontal lines in the UI.
static HORIZONTAL_LINES: [Line; 6] = [
Line::new(107.64, 34.21, 158.24),
Line::new(107.64, 102.61, 20.20),
Line::new(107.64, 171.02, 20.20),
Line::new(127.84, 136.82, 20.20),
Line::new(245.68, 136.82, 20.20),
Line::new(265.88, 102.61, 20.20),
];
/// The positions of the vertical lines in the UI.
static VERTICAL_LINES: [Line; 2] = [
Line::new(127.83, 102.61, 68.40),
Line::new(265.88, 34.21, 102.61),
];
/// Initializes the app.
fn main() {
#[cfg(not(target_arch = "wasm32"))]
let args: Args = argh::from_env();
#[cfg(target_arch = "wasm32")]
let args = Args::from_args(&[], &[]).unwrap();
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
title: "Bevy Animation Graph Example".into(),
..default()
}),
..default()
}))
.add_systems(Startup, (setup_assets, setup_scene, setup_ui))
.add_systems(Update, init_animations)
.add_systems(
Update,
(handle_weight_drag, update_ui, sync_weights).chain(),
)
.insert_resource(args)
.insert_resource(GlobalAmbientLight {
color: WHITE.into(),
brightness: 100.0,
..default()
})
.run();
}
/// Demonstrates animation blending with animation graphs
#[derive(FromArgs, Resource)]
struct Args {
/// disables loading of the animation graph asset from disk
#[argh(switch)]
no_load: bool,
/// regenerates the asset file; implies `--no-load`
#[argh(switch)]
save: bool,
}
/// The [`AnimationGraph`] asset, which specifies how the animations are to
/// be blended together.
#[derive(Clone, Resource)]
struct ExampleAnimationGraph(Handle<AnimationGraph>);
/// The current weights of the three playing animations.
#[derive(Component)]
struct ExampleAnimationWeights {
/// The weights of the three playing animations.
weights: [f32; 3],
}
/// Initializes the scene.
fn setup_assets(
mut commands: Commands,
mut asset_server: ResMut<AssetServer>,
mut animation_graphs: ResMut<Assets<AnimationGraph>>,
args: Res<Args>,
) {
// Create or load the assets.
if args.no_load || args.save {
setup_assets_programmatically(
&mut commands,
&mut asset_server,
&mut animation_graphs,
args.save,
);
} else {
setup_assets_via_serialized_animation_graph(&mut commands, &mut asset_server);
}
}
fn setup_ui(mut commands: Commands) {
setup_help_text(&mut commands);
setup_node_rects(&mut commands);
setup_node_lines(&mut commands);
}
/// Creates the assets programmatically, including the animation graph.
/// Optionally saves them to disk if `save` is present (corresponding to the
/// `--save` option).
fn setup_assets_programmatically(
commands: &mut Commands,
asset_server: &mut AssetServer,
animation_graphs: &mut Assets<AnimationGraph>,
_save: bool,
) {
// Create the nodes.
let mut animation_graph = AnimationGraph::new();
let blend_node = animation_graph.add_blend(0.5, animation_graph.root);
animation_graph.add_clip(
asset_server.load(GltfAssetLabel::Animation(0).from_asset("models/animated/Fox.glb")),
1.0,
animation_graph.root,
);
animation_graph.add_clip(
asset_server.load(GltfAssetLabel::Animation(1).from_asset("models/animated/Fox.glb")),
1.0,
blend_node,
);
animation_graph.add_clip(
asset_server.load(GltfAssetLabel::Animation(2).from_asset("models/animated/Fox.glb")),
1.0,
blend_node,
);
// If asked to save, do so.
#[cfg(not(target_arch = "wasm32"))]
if _save {
let animation_graph = animation_graph.clone();
IoTaskPool::get()
.spawn(async move {
use std::io::Write;
let animation_graph: SerializedAnimationGraph = animation_graph
.try_into()
.expect("The animation graph failed to convert to its serialized form");
let serialized_graph =
ron::ser::to_string_pretty(&animation_graph, PrettyConfig::default())
.expect("Failed to serialize the animation graph");
let mut animation_graph_writer = File::create(Path::join(
&FileAssetReader::get_base_path(),
Path::join(Path::new("assets"), Path::new(ANIMATION_GRAPH_PATH)),
))
.expect("Failed to open the animation graph asset");
animation_graph_writer
.write_all(serialized_graph.as_bytes())
.expect("Failed to write the animation graph");
})
.detach();
}
// Add the graph.
let handle = animation_graphs.add(animation_graph);
// Save the assets in a resource.
commands.insert_resource(ExampleAnimationGraph(handle));
}
fn setup_assets_via_serialized_animation_graph(
commands: &mut Commands,
asset_server: &mut AssetServer,
) {
commands.insert_resource(ExampleAnimationGraph(
asset_server.load(ANIMATION_GRAPH_PATH),
));
}
/// Spawns the animated fox.
fn setup_scene(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-10.0, 5.0, 13.0).looking_at(Vec3::new(0., 1., 0.), Vec3::Y),
));
commands.spawn((
PointLight {
intensity: 10_000_000.0,
shadows_enabled: true,
..default()
},
Transform::from_xyz(-4.0, 8.0, 13.0),
));
commands.spawn((
SceneRoot(
asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/animated/Fox.glb")),
),
Transform::from_scale(Vec3::splat(0.07)),
));
// Ground
commands.spawn((
Mesh3d(meshes.add(Circle::new(7.0))),
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
));
}
/// Places the help text at the top left of the window.
fn setup_help_text(commands: &mut Commands) {
commands.spawn((
Text::new(HELP_TEXT),
Node {
position_type: PositionType::Absolute,
top: px(12),
left: px(12),
..default()
},
));
}
/// Initializes the node UI widgets.
fn setup_node_rects(commands: &mut Commands) {
for (node_rect, node_type) in NODE_RECTS.iter().zip(NODE_TYPES.iter()) {
let node_string = match *node_type {
NodeType::Clip(ref clip) => clip.text,
NodeType::Blend(text) => text,
};
let text = commands
.spawn((
Text::new(node_string),
TextFont {
font_size: 16.0,
..default()
},
TextColor(ANTIQUE_WHITE.into()),
TextLayout::new_with_justify(Justify::Center),
))
.id();
let container = {
let mut container = commands.spawn((
Node {
position_type: PositionType::Absolute,
bottom: px(node_rect.bottom),
left: px(node_rect.left),
height: px(node_rect.height),
width: px(node_rect.width),
align_items: AlignItems::Center,
justify_items: JustifyItems::Center,
align_content: AlignContent::Center,
justify_content: JustifyContent::Center,
..default()
},
BorderColor::all(WHITE),
Outline::new(px(1), Val::ZERO, Color::WHITE),
));
if let NodeType::Clip(clip) = node_type {
container.insert((
Interaction::None,
RelativeCursorPosition::default(),
(*clip).clone(),
));
}
container.id()
};
// Create the background color.
if let NodeType::Clip(_) = node_type {
let background = commands
.spawn((
Node {
position_type: PositionType::Absolute,
top: px(0),
left: px(0),
height: px(node_rect.height),
width: px(node_rect.width),
..default()
},
BackgroundColor(DARK_GREEN.into()),
))
.id();
commands.entity(container).add_child(background);
}
commands.entity(container).add_child(text);
}
}
/// Creates boxes for the horizontal and vertical lines.
///
/// This is a bit hacky: it uses 1-pixel-wide and 1-pixel-high boxes to draw
/// vertical and horizontal lines, respectively.
fn setup_node_lines(commands: &mut Commands) {
for line in &HORIZONTAL_LINES {
commands.spawn((
Node {
position_type: PositionType::Absolute,
bottom: px(line.bottom),
left: px(line.left),
height: px(0),
width: px(line.length),
border: UiRect::bottom(px(1)),
..default()
},
BorderColor::all(WHITE),
));
}
for line in &VERTICAL_LINES {
commands.spawn((
Node {
position_type: PositionType::Absolute,
bottom: px(line.bottom),
left: px(line.left),
height: px(line.length),
width: px(0),
border: UiRect::left(px(1)),
..default()
},
BorderColor::all(WHITE),
));
}
}
/// Attaches the animation graph to the scene, and plays all three animations.
fn init_animations(
mut commands: Commands,
mut query: Query<(Entity, &mut AnimationPlayer)>,
animation_graph: Res<ExampleAnimationGraph>,
mut done: Local<bool>,
) {
if *done {
return;
}
for (entity, mut player) in query.iter_mut() {
commands.entity(entity).insert((
AnimationGraphHandle(animation_graph.0.clone()),
ExampleAnimationWeights::default(),
));
for &node_index in &CLIP_NODE_INDICES {
player.play(node_index.into()).repeat();
}
*done = true;
}
}
/// Read cursor position relative to clip nodes, allowing the user to change weights
/// when dragging the node UI widgets.
fn handle_weight_drag(
mut interaction_query: Query<(&Interaction, &RelativeCursorPosition, &ClipNode)>,
mut animation_weights_query: Query<&mut ExampleAnimationWeights>,
) {
for (interaction, relative_cursor, clip_node) in &mut interaction_query {
if !matches!(*interaction, Interaction::Pressed) {
continue;
}
let Some(pos) = relative_cursor.normalized else {
continue;
};
for mut animation_weights in animation_weights_query.iter_mut() {
animation_weights.weights[clip_node.index] = pos.x.clamp(0., 1.);
}
}
}
// Updates the UI based on the weights that the user has chosen.
fn update_ui(
mut text_query: Query<&mut Text>,
mut background_query: Query<&mut Node, Without<Text>>,
container_query: Query<(&Children, &ClipNode)>,
animation_weights_query: Query<&ExampleAnimationWeights, Changed<ExampleAnimationWeights>>,
) {
for animation_weights in animation_weights_query.iter() {
for (children, clip_node) in &container_query {
// Draw the green background color to visually indicate the weight.
let mut bg_iter = background_query.iter_many_mut(children);
if let Some(mut node) = bg_iter.fetch_next() {
// All nodes are the same width, so `NODE_RECTS[0]` is as good as any other.
node.width = px(NODE_RECTS[0].width * animation_weights.weights[clip_node.index]);
}
// Update the node labels with the current weights.
let mut text_iter = text_query.iter_many_mut(children);
if let Some(mut text) = text_iter.fetch_next() {
**text = format!(
"{}\n{:.2}",
clip_node.text, animation_weights.weights[clip_node.index]
);
}
}
}
}
/// Takes the weights that were set in the UI and assigns them to the actual
/// playing animation.
fn sync_weights(mut query: Query<(&mut AnimationPlayer, &ExampleAnimationWeights)>) {
for (mut animation_player, animation_weights) in query.iter_mut() {
for (&animation_node_index, &animation_weight) in CLIP_NODE_INDICES
.iter()
.zip(animation_weights.weights.iter())
{
// If the animation happens to be no longer active, restart it.
if !animation_player.is_playing_animation(animation_node_index.into()) {
animation_player.play(animation_node_index.into());
}
// Set the weight.
if let Some(active_animation) =
animation_player.animation_mut(animation_node_index.into())
{
active_animation.set_weight(animation_weight);
}
}
}
}
/// An on-screen representation of a node.
#[derive(Debug)]
struct NodeRect {
/// The number of pixels that this rectangle is from the left edge of the
/// window.
left: f32,
/// The number of pixels that this rectangle is from the bottom edge of the
/// window.
bottom: f32,
/// The width of this rectangle in pixels.
width: f32,
/// The height of this rectangle in pixels.
height: f32,
}
/// Either a straight horizontal or a straight vertical line on screen.
///
/// The line starts at (`left`, `bottom`) and goes either right (if the line is
/// horizontal) or down (if the line is vertical).
struct Line {
/// The number of pixels that the start of this line is from the left edge
/// of the screen.
left: f32,
/// The number of pixels that the start of this line is from the bottom edge
/// of the screen.
bottom: f32,
/// The length of the line.
length: f32,
}
/// The type of each node in the UI: either a clip node or a blend node.
enum NodeType {
/// A clip node, which specifies an animation.
Clip(ClipNode),
/// A blend node with no animation and a string label.
Blend(&'static str),
}
/// The label for the UI representation of a clip node.
#[derive(Clone, Component)]
struct ClipNode {
/// The string label of the node.
text: &'static str,
/// Which of the three animations this UI widget represents.
index: usize,
}
impl Default for ExampleAnimationWeights {
fn default() -> Self {
Self { weights: [1.0; 3] }
}
}
impl ClipNode {
/// Creates a new [`ClipNodeText`] from a label and the animation index.
const fn new(text: &'static str, index: usize) -> Self {
Self { text, index }
}
}
impl NodeRect {
/// Creates a new [`NodeRect`] from the lower-left corner and size.
///
/// Note that node rectangles are anchored in the *lower*-left corner. The
/// `bottom` parameter specifies vertical distance from the *bottom* of the
/// window.
const fn new(left: f32, bottom: f32, width: f32, height: f32) -> NodeRect {
NodeRect {
left,
bottom,
width,
height,
}
}
}
impl Line {
/// Creates a new [`Line`], either horizontal or vertical.
///
/// Note that the line's start point is anchored in the lower-*left* corner,
/// and that the `length` extends either to the right or downward.
const fn new(left: f32, bottom: f32, length: f32) -> Self {
Self {
left,
bottom,
length,
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/animation/animated_ui.rs | examples/animation/animated_ui.rs | //! Shows how to use animation clips to animate UI properties.
use bevy::{
animation::{
animated_field, AnimatedBy, AnimationEntityMut, AnimationEvaluationError, AnimationTargetId,
},
prelude::*,
};
use std::any::TypeId;
// Holds information about the animation we programmatically create.
struct AnimationInfo {
// The name of the animation target (in this case, the text).
target_name: Name,
// The ID of the animation target, derived from the name.
target_id: AnimationTargetId,
// The animation graph asset.
graph: Handle<AnimationGraph>,
// The index of the node within that graph.
node_index: AnimationNodeIndex,
}
// The entry point.
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// Note that we don't need any systems other than the setup system,
// because Bevy automatically updates animations every frame.
.add_systems(Startup, setup)
.run();
}
impl AnimationInfo {
// Programmatically creates the UI animation.
fn create(
animation_graphs: &mut Assets<AnimationGraph>,
animation_clips: &mut Assets<AnimationClip>,
) -> AnimationInfo {
// Create an ID that identifies the text node we're going to animate.
let animation_target_name = Name::new("Text");
let animation_target_id = AnimationTargetId::from_name(&animation_target_name);
// Allocate an animation clip.
let mut animation_clip = AnimationClip::default();
// Create a curve that animates font size.
animation_clip.add_curve_to_target(
animation_target_id,
AnimatableCurve::new(
animated_field!(TextFont::font_size),
AnimatableKeyframeCurve::new(
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
.into_iter()
.zip([24.0, 80.0, 24.0, 80.0, 24.0, 80.0, 24.0]),
)
.expect(
"should be able to build translation curve because we pass in valid samples",
),
),
);
// Create a curve that animates font color. Note that this should have
// the same time duration as the previous curve.
//
// This time we use a "custom property", which in this case animates TextColor under the assumption
// that it is in the "srgba" format.
animation_clip.add_curve_to_target(
animation_target_id,
AnimatableCurve::new(
TextColorProperty,
AnimatableKeyframeCurve::new([0.0, 1.0, 2.0, 3.0].into_iter().zip([
Srgba::RED,
Srgba::GREEN,
Srgba::BLUE,
Srgba::RED,
]))
.expect(
"should be able to build translation curve because we pass in valid samples",
),
),
);
// Save our animation clip as an asset.
let animation_clip_handle = animation_clips.add(animation_clip);
// Create an animation graph with that clip.
let (animation_graph, animation_node_index) =
AnimationGraph::from_clip(animation_clip_handle);
let animation_graph_handle = animation_graphs.add(animation_graph);
AnimationInfo {
target_name: animation_target_name,
target_id: animation_target_id,
graph: animation_graph_handle,
node_index: animation_node_index,
}
}
}
// Creates all the entities in the scene.
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut animation_graphs: ResMut<Assets<AnimationGraph>>,
mut animation_clips: ResMut<Assets<AnimationClip>>,
) {
// Create the animation.
let AnimationInfo {
target_name: animation_target_name,
target_id: animation_target_id,
graph: animation_graph,
node_index: animation_node_index,
} = AnimationInfo::create(&mut animation_graphs, &mut animation_clips);
// Build an animation player that automatically plays the UI animation.
let mut animation_player = AnimationPlayer::default();
animation_player.play(animation_node_index).repeat();
// Add a camera.
commands.spawn(Camera2d);
// Build the UI. We have a parent node that covers the whole screen and
// contains the `AnimationPlayer`, as well as a child node that contains the
// text to be animated.
let mut entity = commands.spawn((
// Cover the whole screen, and center contents.
Node {
position_type: PositionType::Absolute,
top: px(0),
left: px(0),
right: px(0),
bottom: px(0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
animation_player,
AnimationGraphHandle(animation_graph),
));
let player = entity.id();
entity.insert(children![(
Text::new("Bevy"),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
font_size: 24.0,
..default()
},
TextColor(Color::Srgba(Srgba::RED)),
TextLayout::new_with_justify(Justify::Center),
animation_target_id,
AnimatedBy(player),
animation_target_name,
)]);
}
// A type that represents the color of the first text section.
//
// We implement `AnimatableProperty` on this to define custom property accessor logic
#[derive(Clone)]
struct TextColorProperty;
impl AnimatableProperty for TextColorProperty {
type Property = Srgba;
fn evaluator_id(&self) -> EvaluatorId<'_> {
EvaluatorId::Type(TypeId::of::<Self>())
}
fn get_mut<'a>(
&self,
entity: &'a mut AnimationEntityMut,
) -> Result<&'a mut Self::Property, AnimationEvaluationError> {
let text_color = entity
.get_mut::<TextColor>()
.ok_or(AnimationEvaluationError::ComponentNotPresent(TypeId::of::<
TextColor,
>(
)))?
.into_inner();
match text_color.0 {
Color::Srgba(ref mut color) => Ok(color),
_ => Err(AnimationEvaluationError::PropertyNotPresent(TypeId::of::<
Srgba,
>(
))),
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/animation/animated_mesh.rs | examples/animation/animated_mesh.rs | //! Plays an animation on a skinned glTF model of a fox.
use std::f32::consts::PI;
use bevy::{light::CascadeShadowConfigBuilder, prelude::*, scene::SceneInstanceReady};
// An example asset that contains a mesh and animation.
const GLTF_PATH: &str = "models/animated/Fox.glb";
fn main() {
App::new()
.insert_resource(GlobalAmbientLight {
color: Color::WHITE,
brightness: 2000.,
..default()
})
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup_mesh_and_animation)
.add_systems(Startup, setup_camera_and_environment)
.run();
}
// A component that stores a reference to an animation we want to play. This is
// created when we start loading the mesh (see `setup_mesh_and_animation`) and
// read when the mesh has spawned (see `play_animation_once_loaded`).
#[derive(Component)]
struct AnimationToPlay {
graph_handle: Handle<AnimationGraph>,
index: AnimationNodeIndex,
}
fn setup_mesh_and_animation(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut graphs: ResMut<Assets<AnimationGraph>>,
) {
// Create an animation graph containing a single animation. We want the "run"
// animation from our example asset, which has an index of two.
let (graph, index) = AnimationGraph::from_clip(
asset_server.load(GltfAssetLabel::Animation(2).from_asset(GLTF_PATH)),
);
// Store the animation graph as an asset.
let graph_handle = graphs.add(graph);
// Create a component that stores a reference to our animation.
let animation_to_play = AnimationToPlay {
graph_handle,
index,
};
// Start loading the asset as a scene and store a reference to it in a
// SceneRoot component. This component will automatically spawn a scene
// containing our mesh once it has loaded.
let mesh_scene = SceneRoot(asset_server.load(GltfAssetLabel::Scene(0).from_asset(GLTF_PATH)));
// Spawn an entity with our components, and connect it to an observer that
// will trigger when the scene is loaded and spawned.
commands
.spawn((animation_to_play, mesh_scene))
.observe(play_animation_when_ready);
}
fn play_animation_when_ready(
scene_ready: On<SceneInstanceReady>,
mut commands: Commands,
children: Query<&Children>,
animations_to_play: Query<&AnimationToPlay>,
mut players: Query<&mut AnimationPlayer>,
) {
// The entity we spawned in `setup_mesh_and_animation` is the trigger's target.
// Start by finding the AnimationToPlay component we added to that entity.
if let Ok(animation_to_play) = animations_to_play.get(scene_ready.entity) {
// The SceneRoot component will have spawned the scene as a hierarchy
// of entities parented to our entity. Since the asset contained a skinned
// mesh and animations, it will also have spawned an animation player
// component. Search our entity's descendants to find the animation player.
for child in children.iter_descendants(scene_ready.entity) {
if let Ok(mut player) = players.get_mut(child) {
// Tell the animation player to start the animation and keep
// repeating it.
//
// If you want to try stopping and switching animations, see the
// `animated_mesh_control.rs` example.
player.play(animation_to_play.index).repeat();
// Add the animation graph. This only needs to be done once to
// connect the animation player to the mesh.
commands
.entity(child)
.insert(AnimationGraphHandle(animation_to_play.graph_handle.clone()));
}
}
}
}
// Spawn a camera and a simple environment with a ground plane and light.
fn setup_camera_and_environment(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(100.0, 100.0, 150.0).looking_at(Vec3::new(0.0, 20.0, 0.0), Vec3::Y),
));
// Plane
commands.spawn((
Mesh3d(meshes.add(Plane3d::default().mesh().size(500000.0, 500000.0))),
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
));
// Light
commands.spawn((
Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
DirectionalLight {
shadows_enabled: true,
..default()
},
CascadeShadowConfigBuilder {
first_cascade_far_bound: 200.0,
maximum_distance: 400.0,
..default()
}
.build(),
));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/animation/color_animation.rs | examples/animation/color_animation.rs | //! Demonstrates how to animate colors in different color spaces using mixing and splines.
use bevy::{math::VectorSpace, prelude::*};
// We define this trait so we can reuse the same code for multiple color types that may be implemented using curves.
trait CurveColor: VectorSpace<Scalar = f32> + Into<Color> + Send + Sync + 'static {}
impl<T: VectorSpace<Scalar = f32> + Into<Color> + Send + Sync + 'static> CurveColor for T {}
// We define this trait so we can reuse the same code for multiple color types that may be implemented using mixing.
trait MixedColor: Mix + Into<Color> + Send + Sync + 'static {}
impl<T: Mix + Into<Color> + Send + Sync + 'static> MixedColor for T {}
#[derive(Debug, Component)]
struct Curve<T: CurveColor>(CubicCurve<T>);
#[derive(Debug, Component)]
struct Mixed<T: MixedColor>([T; 4]);
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(
Update,
(
animate_curve::<LinearRgba>,
animate_curve::<Oklaba>,
animate_curve::<Xyza>,
animate_mixed::<Hsla>,
animate_mixed::<Srgba>,
animate_mixed::<Oklcha>,
),
)
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
// The color spaces `Oklaba`, `Laba`, `LinearRgba`, `Srgba` and `Xyza` all are either perceptually or physically linear.
// This property allows us to define curves, e.g. bezier curves through these spaces.
// Define the control points for the curve.
// For more information, please see the cubic curve example.
let colors = [
LinearRgba::WHITE,
LinearRgba::rgb(1., 1., 0.), // Yellow
LinearRgba::RED,
LinearRgba::BLACK,
];
// Spawn a sprite using the provided colors as control points.
spawn_curve_sprite(&mut commands, 275., colors);
// Spawn another sprite using the provided colors as control points after converting them to the `Xyza` color space.
spawn_curve_sprite(&mut commands, 175., colors.map(Xyza::from));
spawn_curve_sprite(&mut commands, 75., colors.map(Oklaba::from));
// Other color spaces like `Srgba` or `Hsva` are neither perceptually nor physically linear.
// As such, we cannot use curves in these spaces.
// However, we can still mix these colors and animate that way. In fact, mixing colors works in any color space.
// Spawn a sprite using the provided colors for mixing.
spawn_mixed_sprite(&mut commands, -75., colors.map(Hsla::from));
spawn_mixed_sprite(&mut commands, -175., colors.map(Srgba::from));
spawn_mixed_sprite(&mut commands, -275., colors.map(Oklcha::from));
}
fn spawn_curve_sprite<T: CurveColor>(commands: &mut Commands, y: f32, points: [T; 4]) {
commands.spawn((
Sprite::sized(Vec2::new(75., 75.)),
Transform::from_xyz(0., y, 0.),
Curve(CubicBezier::new([points]).to_curve().unwrap()),
));
}
fn spawn_mixed_sprite<T: MixedColor>(commands: &mut Commands, y: f32, colors: [T; 4]) {
commands.spawn((
Transform::from_xyz(0., y, 0.),
Sprite::sized(Vec2::new(75., 75.)),
Mixed(colors),
));
}
fn animate_curve<T: CurveColor>(
time: Res<Time>,
mut query: Query<(&mut Transform, &mut Sprite, &Curve<T>)>,
) {
let t = (ops::sin(time.elapsed_secs()) + 1.) / 2.;
for (mut transform, mut sprite, cubic_curve) in &mut query {
// position takes a point from the curve where 0 is the initial point
// and 1 is the last point
sprite.color = cubic_curve.0.position(t).into();
transform.translation.x = 600. * (t - 0.5);
}
}
fn animate_mixed<T: MixedColor>(
time: Res<Time>,
mut query: Query<(&mut Transform, &mut Sprite, &Mixed<T>)>,
) {
let t = (ops::sin(time.elapsed_secs()) + 1.) / 2.;
for (mut transform, mut sprite, mixed) in &mut query {
sprite.color = {
// First, we determine the amount of intervals between colors.
// For four colors, there are three intervals between those colors;
let intervals = (mixed.0.len() - 1) as f32;
// Next we determine the index of the first of the two colors to mix.
let start_i = (t * intervals).floor().min(intervals - 1.);
// Lastly we determine the 'local' value of t in this interval.
let local_t = (t * intervals) - start_i;
let color = mixed.0[start_i as usize].mix(&mixed.0[start_i as usize + 1], local_t);
color.into()
};
transform.translation.x = 600. * (t - 0.5);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/animation/animation_events.rs | examples/animation/animation_events.rs | //! Demonstrate how to use animation events.
use bevy::{
animation::AnimationEvent,
color::palettes::css::{ALICE_BLUE, BLACK, CRIMSON},
post_process::bloom::Bloom,
prelude::*,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, animate_text_opacity)
.add_observer(on_set_message)
.run();
}
#[derive(Component)]
struct MessageText;
#[derive(AnimationEvent, Clone)]
struct SetMessage {
value: String,
color: Color,
}
fn on_set_message(
set_message: On<SetMessage>,
text: Single<(&mut Text2d, &mut TextColor), With<MessageText>>,
) {
let (mut text, mut color) = text.into_inner();
text.0 = set_message.value.clone();
color.0 = set_message.color;
}
fn setup(
mut commands: Commands,
mut animations: ResMut<Assets<AnimationClip>>,
mut graphs: ResMut<Assets<AnimationGraph>>,
) {
// Camera
commands.spawn((
Camera2d,
Camera {
clear_color: ClearColorConfig::Custom(BLACK.into()),
..Default::default()
},
Bloom {
intensity: 0.4,
..Bloom::NATURAL
},
));
// The text that will be changed by animation events.
commands.spawn((
MessageText,
Text2d::default(),
TextFont {
font_size: 119.0,
..default()
},
TextColor(Color::NONE),
));
// Create a new animation clip.
let mut animation = AnimationClip::default();
// This is only necessary if you want the duration of the
// animation to be longer than the last event in the clip.
animation.set_duration(2.0);
// Add events at the specified time.
animation.add_event(
0.0,
SetMessage {
value: "HELLO".into(),
color: ALICE_BLUE.into(),
},
);
animation.add_event(
1.0,
SetMessage {
value: "BYE".into(),
color: CRIMSON.into(),
},
);
// Create the animation graph.
let (graph, animation_index) = AnimationGraph::from_clip(animations.add(animation));
let mut player = AnimationPlayer::default();
player.play(animation_index).repeat();
commands.spawn((AnimationGraphHandle(graphs.add(graph)), player));
}
// Slowly fade out the text opacity.
fn animate_text_opacity(mut colors: Query<&mut TextColor>, time: Res<Time>) {
for mut color in &mut colors {
let a = color.0.alpha();
color.0.set_alpha(a - time.delta_secs());
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/animation/eased_motion.rs | examples/animation/eased_motion.rs | //! Demonstrates the application of easing curves to animate a transition.
use std::f32::consts::FRAC_PI_2;
use bevy::{
animation::{animated_field, AnimatedBy, AnimationTargetId},
color::palettes::css::{ORANGE, SILVER},
math::vec3,
prelude::*,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut animation_graphs: ResMut<Assets<AnimationGraph>>,
mut animation_clips: ResMut<Assets<AnimationClip>>,
) {
// Create the animation:
let AnimationInfo {
target_name: animation_target_name,
target_id: animation_target_id,
graph: animation_graph,
node_index: animation_node_index,
} = AnimationInfo::create(&mut animation_graphs, &mut animation_clips);
// Build an animation player that automatically plays the animation.
let mut animation_player = AnimationPlayer::default();
animation_player.play(animation_node_index).repeat();
// A cube together with the components needed to animate it
let cube_entity = commands
.spawn((
Mesh3d(meshes.add(Cuboid::from_length(2.0))),
MeshMaterial3d(materials.add(Color::from(ORANGE))),
Transform::from_translation(vec3(-6., 2., 0.)),
animation_target_name,
animation_player,
AnimationGraphHandle(animation_graph),
))
.id();
commands
.entity(cube_entity)
.insert((animation_target_id, AnimatedBy(cube_entity)));
// Some light to see something
commands.spawn((
PointLight {
shadows_enabled: true,
intensity: 10_000_000.,
range: 100.0,
..default()
},
Transform::from_xyz(8., 16., 8.),
));
// Ground plane
commands.spawn((
Mesh3d(meshes.add(Plane3d::default().mesh().size(50., 50.))),
MeshMaterial3d(materials.add(Color::from(SILVER))),
));
// The camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(0., 6., 12.).looking_at(Vec3::new(0., 1.5, 0.), Vec3::Y),
));
}
// Holds information about the animation we programmatically create.
struct AnimationInfo {
// The name of the animation target (in this case, the text).
target_name: Name,
// The ID of the animation target, derived from the name.
target_id: AnimationTargetId,
// The animation graph asset.
graph: Handle<AnimationGraph>,
// The index of the node within that graph.
node_index: AnimationNodeIndex,
}
impl AnimationInfo {
// Programmatically creates the UI animation.
fn create(
animation_graphs: &mut Assets<AnimationGraph>,
animation_clips: &mut Assets<AnimationClip>,
) -> AnimationInfo {
// Create an ID that identifies the text node we're going to animate.
let animation_target_name = Name::new("Cube");
let animation_target_id = AnimationTargetId::from_name(&animation_target_name);
// Allocate an animation clip.
let mut animation_clip = AnimationClip::default();
// Each leg of the translation motion should take 3 seconds.
let animation_domain = interval(0.0, 3.0).unwrap();
// The easing curve is parametrized over [0, 1], so we reparametrize it and
// then ping-pong, which makes it spend another 3 seconds on the return journey.
let translation_curve = EasingCurve::new(
vec3(-6., 2., 0.),
vec3(6., 2., 0.),
EaseFunction::CubicInOut,
)
.reparametrize_linear(animation_domain)
.expect("this curve has bounded domain, so this should never fail")
.ping_pong()
.expect("this curve has bounded domain, so this should never fail");
// Something similar for rotation. The repetition here is an illusion caused
// by the symmetry of the cube; it rotates on the forward journey and never
// rotates back.
let rotation_curve = EasingCurve::new(
Quat::IDENTITY,
Quat::from_rotation_y(FRAC_PI_2),
EaseFunction::ElasticInOut,
)
.reparametrize_linear(interval(0.0, 4.0).unwrap())
.expect("this curve has bounded domain, so this should never fail");
animation_clip.add_curve_to_target(
animation_target_id,
AnimatableCurve::new(animated_field!(Transform::translation), translation_curve),
);
animation_clip.add_curve_to_target(
animation_target_id,
AnimatableCurve::new(animated_field!(Transform::rotation), rotation_curve),
);
// Save our animation clip as an asset.
let animation_clip_handle = animation_clips.add(animation_clip);
// Create an animation graph with that clip.
let (animation_graph, animation_node_index) =
AnimationGraph::from_clip(animation_clip_handle);
let animation_graph_handle = animation_graphs.add(animation_graph);
AnimationInfo {
target_name: animation_target_name,
target_id: animation_target_id,
graph: animation_graph_handle,
node_index: animation_node_index,
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/dynamic.rs | examples/ecs/dynamic.rs | #![expect(
unsafe_code,
reason = "Unsafe code is needed to work with dynamic components"
)]
//! This example show how you can create components dynamically, spawn entities with those components
//! as well as query for entities with those components.
use std::{alloc::Layout, collections::HashMap, io::Write, ptr::NonNull};
use bevy::{
ecs::{
component::{
ComponentCloneBehavior, ComponentDescriptor, ComponentId, ComponentInfo, StorageType,
},
query::{ComponentAccessKind, QueryData},
world::FilteredEntityMut,
},
prelude::*,
ptr::{Aligned, OwningPtr},
};
const PROMPT: &str = "
Commands:
comp, c Create new components
spawn, s Spawn entities
query, q Query for entities
Enter a command with no parameters for usage.";
const COMPONENT_PROMPT: &str = "
comp, c Create new components
Enter a comma separated list of type names optionally followed by a size in u64s.
e.g. CompA 3, CompB, CompC 2";
const ENTITY_PROMPT: &str = "
spawn, s Spawn entities
Enter a comma separated list of components optionally followed by values.
e.g. CompA 0 1 0, CompB, CompC 1";
const QUERY_PROMPT: &str = "
query, q Query for entities
Enter a query to fetch and update entities
Components with read or write access will be displayed with their values
Components with write access will have their fields incremented by one
Accesses: 'A' with, '&A' read, '&mut A' write
Operators: '||' or, ',' and, '?' optional
e.g. &A || &B, &mut C, D, ?E";
fn main() {
let mut world = World::new();
let mut lines = std::io::stdin().lines();
let mut component_names = HashMap::<String, ComponentId>::new();
let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
println!("{PROMPT}");
loop {
print!("\n> ");
let _ = std::io::stdout().flush();
let Some(Ok(line)) = lines.next() else {
return;
};
if line.is_empty() {
return;
};
let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
match &line.chars().next() {
Some('c') => println!("{COMPONENT_PROMPT}"),
Some('s') => println!("{ENTITY_PROMPT}"),
Some('q') => println!("{QUERY_PROMPT}"),
_ => println!("{PROMPT}"),
}
continue;
};
match &first[0..1] {
"c" => {
rest.split(',').for_each(|component| {
let mut component = component.split_whitespace();
let Some(name) = component.next() else {
return;
};
let size = match component.next().map(str::parse) {
Some(Ok(size)) => size,
_ => 0,
};
// Register our new component to the world with a layout specified by it's size
// SAFETY: [u64] is Send + Sync
let id = world.register_component_with_descriptor(unsafe {
ComponentDescriptor::new_with_layout(
name.to_string(),
StorageType::Table,
Layout::array::<u64>(size).unwrap(),
None,
true,
ComponentCloneBehavior::Default,
None,
)
});
let Some(info) = world.components().get_info(id) else {
return;
};
component_names.insert(name.to_string(), id);
component_info.insert(id, info.clone());
println!("Component {} created with id: {}", name, id.index());
});
}
"s" => {
let mut to_insert_ids = Vec::new();
let mut to_insert_data = Vec::new();
rest.split(',').for_each(|component| {
let mut component = component.split_whitespace();
let Some(name) = component.next() else {
return;
};
// Get the id for the component with the given name
let Some(&id) = component_names.get(name) else {
println!("Component {name} does not exist");
return;
};
// Calculate the length for the array based on the layout created for this component id
let info = world.components().get_info(id).unwrap();
let len = info.layout().size() / size_of::<u64>();
let mut values: Vec<u64> = component
.take(len)
.filter_map(|value| value.parse::<u64>().ok())
.collect();
values.resize(len, 0);
// Collect the id and array to be inserted onto our entity
to_insert_ids.push(id);
to_insert_data.push(values);
});
let mut entity = world.spawn_empty();
// Construct an `OwningPtr` for each component in `to_insert_data`
let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
// SAFETY:
// - Component ids have been taken from the same world
// - Each array is created to the layout specified in the world
unsafe {
entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
}
println!("Entity spawned with id: {}", entity.id());
}
"q" => {
let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
parse_query(rest, &mut builder, &component_names);
let mut query = builder.build();
query.iter_mut(&mut world).for_each(|filtered_entity| {
let terms = filtered_entity
.access()
.try_iter_component_access()
.unwrap()
.map(|component_access| {
let id = *component_access.index();
let ptr = filtered_entity.get_by_id(id).unwrap();
let info = component_info.get(&id).unwrap();
let len = info.layout().size() / size_of::<u64>();
// SAFETY:
// - All components are created with layout [u64]
// - len is calculated from the component descriptor
let data = unsafe {
std::slice::from_raw_parts_mut(
ptr.assert_unique().as_ptr().cast::<u64>(),
len,
)
};
// If we have write access, increment each value once
if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
data.iter_mut().for_each(|data| {
*data += 1;
});
}
format!("{}: {:?}", info.name(), data[0..len].to_vec())
})
.collect::<Vec<_>>()
.join(", ");
println!("{}: {}", filtered_entity.id(), terms);
});
}
_ => continue,
}
}
}
// Constructs `OwningPtr` for each item in `components`
// By sharing the lifetime of `components` with the resulting ptrs we ensure we don't drop the data before use
fn to_owning_ptrs(components: &mut [Vec<u64>]) -> Vec<OwningPtr<'_, Aligned>> {
components
.iter_mut()
.map(|data| {
let ptr = data.as_mut_ptr();
// SAFETY:
// - Pointers are guaranteed to be non-null
// - Memory pointed to won't be dropped until `components` is dropped
unsafe {
let non_null = NonNull::new_unchecked(ptr.cast());
OwningPtr::new(non_null)
}
})
.collect()
}
fn parse_term<Q: QueryData>(
str: &str,
builder: &mut QueryBuilder<Q>,
components: &HashMap<String, ComponentId>,
) {
let mut matched = false;
let str = str.trim();
match str.chars().next() {
// Optional term
Some('?') => {
builder.optional(|b| parse_term(&str[1..], b, components));
matched = true;
}
// Reference term
Some('&') => {
let mut parts = str.split_whitespace();
let first = parts.next().unwrap();
if first == "&mut" {
if let Some(str) = parts.next()
&& let Some(&id) = components.get(str)
{
builder.mut_id(id);
matched = true;
};
} else if let Some(&id) = components.get(&first[1..]) {
builder.ref_id(id);
matched = true;
}
}
// With term
Some(_) => {
if let Some(&id) = components.get(str) {
builder.with_id(id);
matched = true;
}
}
None => {}
};
if !matched {
println!("Unable to find component: {str}");
}
}
fn parse_query<Q: QueryData>(
str: &str,
builder: &mut QueryBuilder<Q>,
components: &HashMap<String, ComponentId>,
) {
let str = str.split(',');
str.for_each(|term| {
let sub_terms: Vec<_> = term.split("||").collect();
if sub_terms.len() == 1 {
parse_term(sub_terms[0], builder, components);
} else {
builder.or(|b| {
sub_terms
.iter()
.for_each(|term| parse_term(term, b, components));
});
}
});
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/generic_system.rs | examples/ecs/generic_system.rs | //! Generic types allow us to reuse logic across many related systems,
//! allowing us to specialize our function's behavior based on which type (or types) are passed in.
//!
//! This is commonly useful for working on related components or resources,
//! where we want to have unique types for querying purposes but want them all to work the same way.
//! This is particularly powerful when combined with user-defined traits to add more functionality to these related types.
//! Remember to insert a specialized copy of the system into the schedule for each type that you want to operate on!
//!
//! For more advice on working with generic types in Rust, check out <https://doc.rust-lang.org/book/ch10-01-syntax.html>
//! or <https://doc.rust-lang.org/rust-by-example/generics.html>
use bevy::prelude::*;
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, States)]
enum AppState {
#[default]
MainMenu,
InGame,
}
#[derive(Component)]
struct TextToPrint(String);
#[derive(Component, Deref, DerefMut)]
struct PrinterTick(Timer);
#[derive(Component)]
struct MenuClose;
#[derive(Component)]
struct LevelUnload;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_state::<AppState>()
.add_systems(Startup, setup_system)
.add_systems(
Update,
(
print_text_system,
transition_to_in_game_system.run_if(in_state(AppState::MainMenu)),
),
)
// Cleanup systems.
// Pass in the types your system should operate on using the ::<T> (turbofish) syntax
.add_systems(OnExit(AppState::MainMenu), cleanup_system::<MenuClose>)
.add_systems(OnExit(AppState::InGame), cleanup_system::<LevelUnload>)
.run();
}
fn setup_system(mut commands: Commands) {
commands.spawn((
PrinterTick(Timer::from_seconds(1.0, TimerMode::Repeating)),
TextToPrint("I will print until you press space.".to_string()),
MenuClose,
));
commands.spawn((
PrinterTick(Timer::from_seconds(1.0, TimerMode::Repeating)),
TextToPrint("I will always print".to_string()),
LevelUnload,
));
}
fn print_text_system(time: Res<Time>, mut query: Query<(&mut PrinterTick, &TextToPrint)>) {
for (mut timer, text) in &mut query {
if timer.tick(time.delta()).just_finished() {
info!("{}", text.0);
}
}
}
fn transition_to_in_game_system(
mut next_state: ResMut<NextState<AppState>>,
keyboard_input: Res<ButtonInput<KeyCode>>,
) {
if keyboard_input.pressed(KeyCode::Space) {
next_state.set(AppState::InGame);
}
}
// Type arguments on functions come after the function name, but before ordinary arguments.
// Here, the `Component` trait is a trait bound on T, our generic type
fn cleanup_system<T: Component>(mut commands: Commands, query: Query<Entity, With<T>>) {
for e in &query {
commands.entity(e).despawn();
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/run_conditions.rs | examples/ecs/run_conditions.rs | //! This example demonstrates how to use run conditions to control when systems run.
use bevy::prelude::*;
fn main() {
println!();
println!("For the first 2 seconds you will not be able to increment the counter");
println!("Once that time has passed you can press space, enter, left mouse, right mouse or touch the screen to increment the counter");
println!();
App::new()
.add_plugins(DefaultPlugins)
.init_resource::<InputCounter>()
.add_systems(
Update,
(
increment_input_counter
// The common_conditions module has a few useful run conditions
// for checking resources and states. These are included in the prelude.
.run_if(resource_exists::<InputCounter>)
// `.or()` is a run condition combinator that only evaluates the second condition
// if the first condition returns `false`. This behavior is known as "short-circuiting",
// and is how the `||` operator works in Rust (as well as most C-family languages).
// In this case, the `has_user_input` run condition will be evaluated since the `Unused` resource has not been initialized.
.run_if(resource_exists::<Unused>.or(
// This is a custom run condition, defined using a system that returns
// a `bool` and which has read-only `SystemParam`s.
// Only a single run condition must return `true` in order for the system to run.
has_user_input,
)),
print_input_counter
// `.and()` is a run condition combinator that only evaluates the second condition
// if the first condition returns `true`, analogous to the `&&` operator.
// In this case, the short-circuiting behavior prevents the second run condition from
// panicking if the `InputCounter` resource has not been initialized.
.run_if(resource_exists::<InputCounter>.and(
// This is a custom run condition in the form of a closure.
// This is useful for small, simple run conditions you don't need to reuse.
// All the normal rules still apply: all parameters must be read only except for local parameters.
|counter: Res<InputCounter>| counter.is_changed() && !counter.is_added(),
)),
print_time_message
// This function returns a custom run condition, much like the common conditions module.
// It will only return true once 2 seconds have passed.
.run_if(time_passed(2.0))
// You can use the `not` condition from the common_conditions module
// to inverse a run condition. In this case it will return true if
// less than 2.5 seconds have elapsed since the app started.
.run_if(not(time_passed(2.5))),
),
)
.run();
}
#[derive(Resource, Default)]
struct InputCounter(usize);
#[derive(Resource)]
struct Unused;
/// Return true if any of the defined inputs were just pressed.
///
/// This is a custom run condition, it can take any normal system parameters as long as
/// they are read only (except for local parameters which can be mutable).
/// It returns a bool which determines if the system should run.
fn has_user_input(
keyboard_input: Res<ButtonInput<KeyCode>>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
touch_input: Res<Touches>,
) -> bool {
keyboard_input.just_pressed(KeyCode::Space)
|| keyboard_input.just_pressed(KeyCode::Enter)
|| mouse_button_input.just_pressed(MouseButton::Left)
|| mouse_button_input.just_pressed(MouseButton::Right)
|| touch_input.any_just_pressed()
}
/// This is a function that returns a closure which can be used as a run condition.
///
/// This is useful because you can reuse the same run condition but with different variables.
/// This is how the common conditions module works.
fn time_passed(t: f32) -> impl FnMut(Local<f32>, Res<Time>) -> bool {
move |mut timer: Local<f32>, time: Res<Time>| {
// Tick the timer
*timer += time.delta_secs();
// Return true if the timer has passed the time
*timer >= t
}
}
/// SYSTEM: Increment the input counter
/// Notice how we can take just the `ResMut` and not have to wrap
/// it in an option in case it hasn't been initialized, this is because
/// it has a run condition that checks if the `InputCounter` resource exists
fn increment_input_counter(mut counter: ResMut<InputCounter>) {
counter.0 += 1;
}
/// SYSTEM: Print the input counter
fn print_input_counter(counter: Res<InputCounter>) {
println!("Input counter: {}", counter.0);
}
/// SYSTEM: Adds the input counter resource
fn print_time_message() {
println!("It has been more than 2 seconds since the program started and less than 2.5 seconds");
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/observer_propagation.rs | examples/ecs/observer_propagation.rs | //! Demonstrates how to propagate events through the hierarchy with observers.
use std::time::Duration;
use bevy::{log::LogPlugin, prelude::*, time::common_conditions::on_timer};
use rand::{rng, seq::IteratorRandom, Rng};
fn main() {
App::new()
.add_plugins((MinimalPlugins, LogPlugin::default()))
.add_systems(Startup, setup)
.add_systems(
Update,
attack_armor.run_if(on_timer(Duration::from_millis(200))),
)
// Add a global observer that will emit a line whenever an attack hits an entity.
.add_observer(attack_hits)
.run();
}
// In this example, we spawn a goblin wearing different pieces of armor. Each piece of armor
// is represented as a child entity, with an `Armor` component.
//
// We're going to model how attack damage can be partially blocked by the goblin's armor using
// event bubbling. Our events will target the armor, and if the armor isn't strong enough to block
// the attack it will continue up and hit the goblin.
fn setup(mut commands: Commands) {
commands
.spawn((Name::new("Goblin"), HitPoints(50)))
.observe(take_damage)
.with_children(|parent| {
parent
.spawn((Name::new("Helmet"), Armor(5)))
.observe(block_attack);
parent
.spawn((Name::new("Socks"), Armor(10)))
.observe(block_attack);
parent
.spawn((Name::new("Shirt"), Armor(15)))
.observe(block_attack);
});
}
// This event represents an attack we want to "bubble" up from the armor to the goblin.
//
// We enable propagation by adding the event attribute and specifying two important pieces of information.
//
// - **propagate:**
// Enables the default propagation behavior ("bubbling" up from child to parent using the ChildOf component).
//
// - **auto_propagate:**
// We can also choose whether or not this event will propagate by default when triggered. If this is
// false, it will only propagate following a call to `On::propagate(true)`.
#[derive(Clone, Component, EntityEvent)]
#[entity_event(propagate, auto_propagate)]
struct Attack {
entity: Entity,
damage: u16,
}
/// An entity that can take damage.
#[derive(Component, Deref, DerefMut)]
struct HitPoints(u16);
/// For damage to reach the wearer, it must exceed the armor.
#[derive(Component, Deref)]
struct Armor(u16);
/// A normal bevy system that attacks a piece of the goblin's armor on a timer.
fn attack_armor(entities: Query<Entity, With<Armor>>, mut commands: Commands) {
let mut rng = rng();
if let Some(entity) = entities.iter().choose(&mut rng) {
let damage = rng.random_range(1..20);
commands.trigger(Attack { damage, entity });
info!("⚔️ Attack for {} damage", damage);
}
}
fn attack_hits(attack: On<Attack>, name: Query<&Name>) {
if let Ok(name) = name.get(attack.entity) {
info!("Attack hit {}", name);
}
}
/// A callback placed on [`Armor`], checking if it absorbed all the [`Attack`] damage.
fn block_attack(mut attack: On<Attack>, armor: Query<(&Armor, &Name)>) {
let (armor, name) = armor.get(attack.entity).unwrap();
let damage = attack.damage.saturating_sub(**armor);
if damage > 0 {
info!("🩸 {} damage passed through {}", damage, name);
// The attack isn't stopped by the armor. We reduce the damage of the attack, and allow
// it to continue on to the goblin.
attack.damage = damage;
} else {
info!("🛡️ {} damage blocked by {}", attack.damage, name);
// Armor stopped the attack, the event stops here.
attack.propagate(false);
info!("(propagation halted early)\n");
}
}
/// A callback on the armor wearer, triggered when a piece of armor is not able to block an attack,
/// or the wearer is attacked directly.
fn take_damage(
attack: On<Attack>,
mut hp: Query<(&mut HitPoints, &Name)>,
mut commands: Commands,
mut app_exit: MessageWriter<AppExit>,
) {
let (mut hp, name) = hp.get_mut(attack.entity).unwrap();
**hp = hp.saturating_sub(attack.damage);
if **hp > 0 {
info!("{} has {:.1} HP", name, hp.0);
} else {
warn!("💀 {} has died a gruesome death", name);
commands.entity(attack.entity).despawn();
app_exit.write(AppExit::Success);
}
info!("(propagation reached root)\n");
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/custom_schedule.rs | examples/ecs/custom_schedule.rs | //! Demonstrates how to add custom schedules that run in Bevy's `Main` schedule, ordered relative to Bevy's built-in
//! schedules such as `Update` or `Last`.
use bevy::{
app::MainScheduleOrder,
ecs::schedule::{ExecutorKind, ScheduleLabel},
prelude::*,
};
#[derive(ScheduleLabel, Debug, Hash, PartialEq, Eq, Clone)]
struct SingleThreadedUpdate;
#[derive(ScheduleLabel, Debug, Hash, PartialEq, Eq, Clone)]
struct CustomStartup;
fn main() {
let mut app = App::new();
// Create a new [`Schedule`]. For demonstration purposes, we configure it to use a single threaded executor so that
// systems in this schedule are never run in parallel. However, this is not a requirement for custom schedules in
// general.
let mut custom_update_schedule = Schedule::new(SingleThreadedUpdate);
custom_update_schedule.set_executor_kind(ExecutorKind::SingleThreaded);
// Adding the schedule to the app does not automatically run the schedule. This merely registers the schedule so
// that systems can look it up using the `Schedules` resource.
app.add_schedule(custom_update_schedule);
// Bevy `App`s have a `main_schedule_label` field that configures which schedule is run by the App's `runner`.
// By default, this is `Main`. The `Main` schedule is responsible for running Bevy's main schedules such as
// `Update`, `Startup` or `Last`.
//
// We can configure the `Main` schedule to run our custom update schedule relative to the existing ones by modifying
// the `MainScheduleOrder` resource.
//
// Note that we modify `MainScheduleOrder` directly in `main` and not in a startup system. The reason for this is
// that the `MainScheduleOrder` cannot be modified from systems that are run as part of the `Main` schedule.
let mut main_schedule_order = app.world_mut().resource_mut::<MainScheduleOrder>();
main_schedule_order.insert_after(Update, SingleThreadedUpdate);
// Adding a custom startup schedule works similarly, but needs to use `insert_startup_after`
// instead of `insert_after`.
app.add_schedule(Schedule::new(CustomStartup));
let mut main_schedule_order = app.world_mut().resource_mut::<MainScheduleOrder>();
main_schedule_order.insert_startup_after(PreStartup, CustomStartup);
app.add_systems(SingleThreadedUpdate, single_threaded_update_system)
.add_systems(CustomStartup, custom_startup_system)
.add_systems(PreStartup, pre_startup_system)
.add_systems(Startup, startup_system)
.add_systems(First, first_system)
.add_systems(Update, update_system)
.add_systems(Last, last_system)
.run();
}
fn pre_startup_system() {
println!("Pre Startup");
}
fn startup_system() {
println!("Startup");
}
fn custom_startup_system() {
println!("Custom Startup");
}
fn first_system() {
println!("First");
}
fn update_system() {
println!("Update");
}
fn single_threaded_update_system() {
println!("Single Threaded Update");
}
fn last_system() {
println!("Last");
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/hierarchy.rs | examples/ecs/hierarchy.rs | //! Demonstrates techniques for creating a hierarchy of parent and child entities.
//!
//! When [`DefaultPlugins`] are added to your app, systems are automatically added to propagate
//! [`Transform`] and [`Visibility`] from parents to children down the hierarchy,
//! resulting in a final [`GlobalTransform`] and [`InheritedVisibility`] component for each entity.
use std::f32::consts::*;
use bevy::{color::palettes::css::*, prelude::*};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, rotate)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let texture = asset_server.load("branding/icon.png");
// Spawn a root entity with no parent
let parent = commands
.spawn((
Sprite::from_image(texture.clone()),
Transform::from_scale(Vec3::splat(0.75)),
))
// With that entity as a parent, run a lambda that spawns its children
.with_children(|parent| {
// parent is a ChildSpawnerCommands, which has a similar API to Commands
parent.spawn((
Transform::from_xyz(250.0, 0.0, 0.0).with_scale(Vec3::splat(0.75)),
Sprite {
image: texture.clone(),
color: BLUE.into(),
..default()
},
));
})
// Store parent entity for next sections
.id();
// Another way is to use the add_child function to add children after the parent
// entity has already been spawned.
let child = commands
.spawn((
Sprite {
image: texture,
color: LIME.into(),
..default()
},
Transform::from_xyz(0.0, 250.0, 0.0).with_scale(Vec3::splat(0.75)),
))
.id();
// Add child to the parent.
commands.entity(parent).add_child(child);
}
// A simple system to rotate the root entity, and rotate all its children separately
fn rotate(
mut commands: Commands,
time: Res<Time>,
mut parents_query: Query<(Entity, &Children), With<Sprite>>,
mut transform_query: Query<&mut Transform, With<Sprite>>,
) {
for (parent, children) in &mut parents_query {
if let Ok(mut transform) = transform_query.get_mut(parent) {
transform.rotate_z(-PI / 2. * time.delta_secs());
}
// To iterate through the entities children, just treat the Children component as a Vec
// Alternatively, you could query entities that have a ChildOf component
for child in children {
if let Ok(mut transform) = transform_query.get_mut(*child) {
transform.rotate_z(PI * time.delta_secs());
}
}
// To demonstrate removing children, we'll remove a child after a couple of seconds.
if time.elapsed_secs() >= 2.0 && children.len() == 2 {
let child = children.last().unwrap();
commands.entity(*child).despawn();
}
if time.elapsed_secs() >= 4.0 {
// This will remove the entity from its parent's list of children, as well as despawn
// any children the entity has.
commands.entity(parent).despawn();
}
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/system_stepping.rs | examples/ecs/system_stepping.rs | //! Demonstrate stepping through systems in order of execution.
//!
//! To run this example, you must enable the `bevy_debug_stepping` feature.
use bevy::{ecs::schedule::Stepping, log::LogPlugin, prelude::*};
fn main() {
let mut app = App::new();
app
// to display log messages from Stepping resource
.add_plugins(LogPlugin::default())
.add_systems(
Update,
(
update_system_one,
// establish a dependency here to simplify descriptions below
update_system_two.after(update_system_one),
update_system_three.after(update_system_two),
update_system_four,
),
)
.add_systems(PreUpdate, pre_update_system);
// For the simplicity of this example, we directly modify the `Stepping`
// resource here and run the systems with `App::update()`. Each call to
// `App::update()` is the equivalent of a single frame render when using
// `App::run()`.
//
// In a real-world situation, the `Stepping` resource would be modified by
// a system based on input from the user. A full demonstration of this can
// be found in the breakout example.
println!(
r#"
Actions: call app.update()
Result: All systems run normally"#
);
app.update();
println!(
r#"
Actions: Add the Stepping resource then call app.update()
Result: All systems run normally. Stepping has no effect unless explicitly
configured for a Schedule, and Stepping has been enabled."#
);
app.insert_resource(Stepping::new());
app.update();
println!(
r#"
Actions: Add the Update Schedule to Stepping; enable Stepping; call
app.update()
Result: Only the systems in PreUpdate run. When Stepping is enabled,
systems in the configured schedules will not run unless:
* Stepping::step_frame() is called
* Stepping::continue_frame() is called
* System has been configured to always run"#
);
let mut stepping = app.world_mut().resource_mut::<Stepping>();
stepping.add_schedule(Update).enable();
app.update();
println!(
r#"
Actions: call Stepping.step_frame(); call app.update()
Result: The PreUpdate systems run, and one Update system will run. In
Stepping, step means run the next system across all the schedules
that have been added to the Stepping resource."#
);
let mut stepping = app.world_mut().resource_mut::<Stepping>();
stepping.step_frame();
app.update();
println!(
r#"
Actions: call app.update()
Result: Only the PreUpdate systems run. The previous call to
Stepping::step_frame() only applies for the next call to
app.update()/the next frame rendered.
"#
);
app.update();
println!(
r#"
Actions: call Stepping::continue_frame(); call app.update()
Result: PreUpdate system will run, and all remaining Update systems will
run. Stepping::continue_frame() tells stepping to run all systems
starting after the last run system until it hits the end of the
frame, or it encounters a system with a breakpoint set. In this
case, we previously performed a step, running one system in Update.
This continue will cause all remaining systems in Update to run."#
);
let mut stepping = app.world_mut().resource_mut::<Stepping>();
stepping.continue_frame();
app.update();
println!(
r#"
Actions: call Stepping::step_frame() & app.update() four times in a row
Result: PreUpdate system runs every time we call app.update(), along with
one system from the Update schedule each time. This shows what
execution would look like to step through an entire frame of
systems."#
);
for _ in 0..4 {
let mut stepping = app.world_mut().resource_mut::<Stepping>();
stepping.step_frame();
app.update();
}
println!(
r#"
Actions: Stepping::always_run(Update, update_system_two); step through all
systems
Result: PreUpdate system and update_system_two() will run every time we
call app.update(). We'll also only need to step three times to
execute all systems in the frame. Stepping::always_run() allows
us to granularly allow systems to run when stepping is enabled."#
);
let mut stepping = app.world_mut().resource_mut::<Stepping>();
stepping.always_run(Update, update_system_two);
for _ in 0..3 {
let mut stepping = app.world_mut().resource_mut::<Stepping>();
stepping.step_frame();
app.update();
}
println!(
r#"
Actions: Stepping::never_run(Update, update_system_two); continue through
all systems
Result: All systems except update_system_two() will execute.
Stepping::never_run() allows us to disable systems while Stepping
is enabled."#
);
let mut stepping = app.world_mut().resource_mut::<Stepping>();
stepping.never_run(Update, update_system_two);
stepping.continue_frame();
app.update();
println!(
r#"
Actions: Stepping::set_breakpoint(Update, update_system_two); continue,
step, continue
Result: During the first continue, pre_update_system() and
update_system_one() will run. update_system_four() may also run
as it has no dependency on update_system_two() or
update_system_three(). Nether update_system_two() nor
update_system_three() will run in the first app.update() call as
they form a chained dependency on update_system_one() and run
in order of one, two, three. Stepping stops system execution in
the Update schedule when it encounters the breakpoint for
update_system_two().
During the step we run update_system_two() along with the
pre_update_system().
During the final continue pre_update_system() and
update_system_three() run."#
);
let mut stepping = app.world_mut().resource_mut::<Stepping>();
stepping.set_breakpoint(Update, update_system_two);
stepping.continue_frame();
app.update();
let mut stepping = app.world_mut().resource_mut::<Stepping>();
stepping.step_frame();
app.update();
let mut stepping = app.world_mut().resource_mut::<Stepping>();
stepping.continue_frame();
app.update();
println!(
r#"
Actions: Stepping::clear_breakpoint(Update, update_system_two); continue
through all systems
Result: All systems will run"#
);
let mut stepping = app.world_mut().resource_mut::<Stepping>();
stepping.clear_breakpoint(Update, update_system_two);
stepping.continue_frame();
app.update();
println!(
r#"
Actions: Stepping::disable(); app.update()
Result: All systems will run. With Stepping disabled, there's no need to
call Stepping::step_frame() or Stepping::continue_frame() to run
systems in the Update schedule."#
);
let mut stepping = app.world_mut().resource_mut::<Stepping>();
stepping.disable();
app.update();
}
fn pre_update_system() {
println!("▶ pre_update_system");
}
fn update_system_one() {
println!("▶ update_system_one");
}
fn update_system_two() {
println!("▶ update_system_two");
}
fn update_system_three() {
println!("▶ update_system_three");
}
fn update_system_four() {
println!("▶ update_system_four");
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/custom_query_param.rs | examples/ecs/custom_query_param.rs | //! This example illustrates the usage of the [`QueryData`] derive macro, which allows
//! defining custom query and filter types.
//!
//! While regular tuple queries work great in most of simple scenarios, using custom queries
//! declared as named structs can bring the following advantages:
//! - They help to avoid destructuring or using `q.0, q.1, ...` access pattern.
//! - Adding, removing components or changing items order with structs greatly reduces maintenance
//! burden, as you don't need to update statements that destructure tuples, care about order
//! of elements, etc. Instead, you can just add or remove places where a certain element is used.
//! - Named structs enable the composition pattern, that makes query types easier to re-use.
//! - You can bypass the limit of 15 components that exists for query tuples.
//!
//! For more details on the [`QueryData`] derive macro, see the trait documentation.
use bevy::{
ecs::query::{QueryData, QueryFilter},
prelude::*,
};
use std::fmt::Debug;
fn main() {
App::new()
.add_systems(Startup, spawn)
.add_systems(
Update,
(
print_components_read_only,
print_components_iter_mut,
print_components_iter,
print_components_tuple,
)
.chain(),
)
.run();
}
#[derive(Component, Debug)]
struct ComponentA;
#[derive(Component, Debug)]
struct ComponentB;
#[derive(Component, Debug)]
struct ComponentC;
#[derive(Component, Debug)]
struct ComponentD;
#[derive(Component, Debug)]
struct ComponentZ;
#[derive(QueryData)]
#[query_data(derive(Debug))]
struct ReadOnlyCustomQuery<T: Component + Debug, P: Component + Debug> {
entity: Entity,
a: &'static ComponentA,
b: Option<&'static ComponentB>,
nested: NestedQuery,
optional_nested: Option<NestedQuery>,
optional_tuple: Option<(&'static ComponentB, &'static ComponentZ)>,
generic: GenericQuery<T, P>,
empty: EmptyQuery,
}
fn print_components_read_only(
query: Query<
ReadOnlyCustomQuery<ComponentC, ComponentD>,
CustomQueryFilter<ComponentC, ComponentD>,
>,
) {
println!("Print components (read_only):");
for e in &query {
println!("Entity: {}", e.entity);
println!("A: {:?}", e.a);
println!("B: {:?}", e.b);
println!("Nested: {:?}", e.nested);
println!("Optional nested: {:?}", e.optional_nested);
println!("Optional tuple: {:?}", e.optional_tuple);
println!("Generic: {:?}", e.generic);
}
println!();
}
/// If you are going to mutate the data in a query, you must mark it with the `mutable` attribute.
///
/// The [`QueryData`] derive macro will still create a read-only version, which will be have `ReadOnly`
/// suffix.
/// Note: if you want to use derive macros with read-only query variants, you need to pass them with
/// using the `derive` attribute.
#[derive(QueryData)]
#[query_data(mutable, derive(Debug))]
struct CustomQuery<T: Component + Debug, P: Component + Debug> {
entity: Entity,
a: &'static mut ComponentA,
b: Option<&'static mut ComponentB>,
nested: NestedQuery,
optional_nested: Option<NestedQuery>,
optional_tuple: Option<(NestedQuery, &'static mut ComponentZ)>,
generic: GenericQuery<T, P>,
empty: EmptyQuery,
}
// This is a valid query as well, which would iterate over every entity.
#[derive(QueryData)]
#[query_data(derive(Debug))]
struct EmptyQuery {
empty: (),
}
#[derive(QueryData)]
#[query_data(derive(Debug))]
struct NestedQuery {
c: &'static ComponentC,
d: Option<&'static ComponentD>,
}
#[derive(QueryData)]
#[query_data(derive(Debug))]
struct GenericQuery<T: Component, P: Component> {
generic: (&'static T, &'static P),
}
#[derive(QueryFilter)]
struct CustomQueryFilter<T: Component, P: Component> {
_c: With<ComponentC>,
_d: With<ComponentD>,
_or: Or<(Added<ComponentC>, Changed<ComponentD>, Without<ComponentZ>)>,
_generic_tuple: (With<T>, With<P>),
}
fn spawn(mut commands: Commands) {
commands.spawn((ComponentA, ComponentB, ComponentC, ComponentD));
}
fn print_components_iter_mut(
mut query: Query<
CustomQuery<ComponentC, ComponentD>,
CustomQueryFilter<ComponentC, ComponentD>,
>,
) {
println!("Print components (iter_mut):");
for e in &mut query {
// Re-declaring the variable to illustrate the type of the actual iterator item.
let e: CustomQueryItem<'_, '_, _, _> = e;
println!("Entity: {}", e.entity);
println!("A: {:?}", e.a);
println!("B: {:?}", e.b);
println!("Optional nested: {:?}", e.optional_nested);
println!("Optional tuple: {:?}", e.optional_tuple);
println!("Nested: {:?}", e.nested);
println!("Generic: {:?}", e.generic);
}
println!();
}
fn print_components_iter(
query: Query<CustomQuery<ComponentC, ComponentD>, CustomQueryFilter<ComponentC, ComponentD>>,
) {
println!("Print components (iter):");
for e in &query {
// Re-declaring the variable to illustrate the type of the actual iterator item.
let e: CustomQueryReadOnlyItem<'_, '_, _, _> = e;
println!("Entity: {}", e.entity);
println!("A: {:?}", e.a);
println!("B: {:?}", e.b);
println!("Nested: {:?}", e.nested);
println!("Generic: {:?}", e.generic);
}
println!();
}
type NestedTupleQuery<'w> = (&'w ComponentC, &'w ComponentD);
type GenericTupleQuery<'w, T, P> = (&'w T, &'w P);
fn print_components_tuple(
query: Query<
(
Entity,
&ComponentA,
&ComponentB,
NestedTupleQuery,
GenericTupleQuery<ComponentC, ComponentD>,
),
(
With<ComponentC>,
With<ComponentD>,
Or<(Added<ComponentC>, Changed<ComponentD>, Without<ComponentZ>)>,
),
>,
) {
println!("Print components (tuple):");
for (entity, a, b, nested, (generic_c, generic_d)) in &query {
println!("Entity: {entity}");
println!("A: {a:?}");
println!("B: {b:?}");
println!("Nested: {:?} {:?}", nested.0, nested.1);
println!("Generic: {generic_c:?} {generic_d:?}");
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/parallel_query.rs | examples/ecs/parallel_query.rs | //! Illustrates parallel queries with `ParallelIterator`.
use bevy::{ecs::batching::BatchingStrategy, prelude::*};
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
#[derive(Component, Deref)]
struct Velocity(Vec2);
fn spawn_system(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let texture = asset_server.load("branding/icon.png");
// We're seeding the PRNG here to make this example deterministic for testing purposes.
// This isn't strictly required in practical use unless you need your app to be deterministic.
let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
for z in 0..128 {
commands.spawn((
Sprite::from_image(texture.clone()),
Transform::from_scale(Vec3::splat(0.1))
.with_translation(Vec2::splat(0.0).extend(z as f32)),
Velocity(20.0 * Vec2::new(rng.random::<f32>() - 0.5, rng.random::<f32>() - 0.5)),
));
}
}
// Move sprites according to their velocity
fn move_system(mut sprites: Query<(&mut Transform, &Velocity)>) {
// Compute the new location of each sprite in parallel on the
// ComputeTaskPool
//
// This example is only for demonstrative purposes. Using a
// ParallelIterator for an inexpensive operation like addition on only 128
// elements will not typically be faster than just using a normal Iterator.
// See the ParallelIterator documentation for more information on when
// to use or not use ParallelIterator over a normal Iterator.
sprites
.par_iter_mut()
.for_each(|(mut transform, velocity)| {
transform.translation += velocity.extend(0.0);
});
}
// Bounce sprites outside the window
fn bounce_system(window: Query<&Window>, mut sprites: Query<(&Transform, &mut Velocity)>) {
let Ok(window) = window.single() else {
return;
};
let width = window.width();
let height = window.height();
let left = width / -2.0;
let right = width / 2.0;
let bottom = height / -2.0;
let top = height / 2.0;
// The default batch size can also be overridden.
// In this case a batch size of 32 is chosen to limit the overhead of
// ParallelIterator, since negating a vector is very inexpensive.
sprites
.par_iter_mut()
.batching_strategy(BatchingStrategy::fixed(32))
.for_each(|(transform, mut v)| {
if !(left < transform.translation.x
&& transform.translation.x < right
&& bottom < transform.translation.y
&& transform.translation.y < top)
{
// For simplicity, just reverse the velocity; don't use realistic bounces
v.0 = -v.0;
}
});
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, spawn_system)
.add_systems(Update, (move_system, bounce_system))
.run();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/immutable_components.rs | examples/ecs/immutable_components.rs | //! This example demonstrates immutable components.
use bevy::{
ecs::{
component::{ComponentCloneBehavior, ComponentDescriptor, ComponentId, StorageType},
lifecycle::HookContext,
world::DeferredWorld,
},
platform::collections::HashMap,
prelude::*,
ptr::OwningPtr,
};
use core::alloc::Layout;
/// This component is mutable, the default case. This is indicated by components
/// implementing [`Component`] where [`Component::Mutability`] is [`Mutable`](bevy::ecs::component::Mutable).
#[derive(Component)]
pub struct MyMutableComponent(bool);
/// This component is immutable. Once inserted into the ECS, it can only be viewed,
/// or removed. Replacement is also permitted, as this is equivalent to removal
/// and insertion.
///
/// Adding the `#[component(immutable)]` attribute prevents the implementation of [`Component<Mutability = Mutable>`]
/// in the derive macro.
#[derive(Component)]
#[component(immutable)]
pub struct MyImmutableComponent(bool);
fn demo_1(world: &mut World) {
// Immutable components can be inserted just like mutable components.
let mut entity = world.spawn((MyMutableComponent(false), MyImmutableComponent(false)));
// But where mutable components can be mutated...
let mut my_mutable_component = entity.get_mut::<MyMutableComponent>().unwrap();
my_mutable_component.0 = true;
// ...immutable ones cannot. The below fails to compile as `MyImmutableComponent`
// is declared as immutable.
// let mut my_immutable_component = entity.get_mut::<MyImmutableComponent>().unwrap();
// Instead, you could take or replace the immutable component to update its value.
let mut my_immutable_component = entity.take::<MyImmutableComponent>().unwrap();
my_immutable_component.0 = true;
entity.insert(my_immutable_component);
}
/// This is an example of a component like [`Name`](bevy::prelude::Name), but immutable.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Component, Reflect)]
#[reflect(Hash, Component)]
#[component(
immutable,
// Since this component is immutable, we can fully capture all mutations through
// these component hooks. This allows for keeping other parts of the ECS synced
// to a component's value at all times.
on_insert = on_insert_name,
on_replace = on_replace_name,
)]
pub struct Name(pub &'static str);
/// This index allows for O(1) lookups of an [`Entity`] by its [`Name`].
#[derive(Resource, Default)]
struct NameIndex {
name_to_entity: HashMap<Name, Entity>,
}
impl NameIndex {
fn get_entity(&self, name: &'static str) -> Option<Entity> {
self.name_to_entity.get(&Name(name)).copied()
}
}
/// When a [`Name`] is inserted, we will add it to our [`NameIndex`].
///
/// Since all mutations to [`Name`] are captured by hooks, we know it is not currently
/// inserted in the index, and its value will not change without triggering a hook.
fn on_insert_name(mut world: DeferredWorld<'_>, HookContext { entity, .. }: HookContext) {
let Some(&name) = world.entity(entity).get::<Name>() else {
unreachable!("Insert hook guarantees `Name` is available on entity")
};
let Some(mut index) = world.get_resource_mut::<NameIndex>() else {
return;
};
index.name_to_entity.insert(name, entity);
}
/// When a [`Name`] is removed or replaced, remove it from our [`NameIndex`].
///
/// Since all mutations to [`Name`] are captured by hooks, we know it is currently
/// inserted in the index.
fn on_replace_name(mut world: DeferredWorld<'_>, HookContext { entity, .. }: HookContext) {
let Some(&name) = world.entity(entity).get::<Name>() else {
unreachable!("Replace hook guarantees `Name` is available on entity")
};
let Some(mut index) = world.get_resource_mut::<NameIndex>() else {
return;
};
index.name_to_entity.remove(&name);
}
fn demo_2(world: &mut World) {
// Setup our name index
world.init_resource::<NameIndex>();
// Spawn some entities!
let alyssa = world.spawn(Name("Alyssa")).id();
let javier = world.spawn(Name("Javier")).id();
// Check our index
let index = world.resource::<NameIndex>();
assert_eq!(index.get_entity("Alyssa"), Some(alyssa));
assert_eq!(index.get_entity("Javier"), Some(javier));
// Changing the name of an entity is also fully capture by our index
world.entity_mut(javier).insert(Name("Steven"));
// Javier changed their name to Steven
let steven = javier;
// Check our index
let index = world.resource::<NameIndex>();
assert_eq!(index.get_entity("Javier"), None);
assert_eq!(index.get_entity("Steven"), Some(steven));
}
/// This example demonstrates how to work with _dynamic_ immutable components.
#[expect(
unsafe_code,
reason = "Unsafe code is needed to work with dynamic components"
)]
fn demo_3(world: &mut World) {
// This is a list of dynamic components we will create.
// The first item is the name of the component, and the second is the size
// in bytes.
let my_dynamic_components = [("Foo", 1), ("Bar", 2), ("Baz", 4)];
// This pipeline takes our component descriptions, registers them, and gets
// their ComponentId's.
let my_registered_components = my_dynamic_components
.into_iter()
.map(|(name, size)| {
// SAFETY:
// - No drop command is required
// - The component will store [u8; size], which is Send + Sync
let descriptor = unsafe {
ComponentDescriptor::new_with_layout(
name.to_string(),
StorageType::Table,
Layout::array::<u8>(size).unwrap(),
None,
false,
ComponentCloneBehavior::Default,
None,
)
};
(name, size, descriptor)
})
.map(|(name, size, descriptor)| {
let component_id = world.register_component_with_descriptor(descriptor);
(name, size, component_id)
})
.collect::<Vec<(&str, usize, ComponentId)>>();
// Now that our components are registered, let's add them to an entity
let mut entity = world.spawn_empty();
for (_name, size, component_id) in &my_registered_components {
// We're just storing some zeroes for the sake of demonstration.
let data = core::iter::repeat_n(0, *size).collect::<Vec<u8>>();
OwningPtr::make(data, |ptr| {
// SAFETY:
// - ComponentId has been taken from the same world
// - Array is created to the layout specified in the world
unsafe {
entity.insert_by_id(*component_id, ptr);
}
});
}
for (_name, _size, component_id) in &my_registered_components {
// With immutable components, we can read the values...
assert!(entity.get_by_id(*component_id).is_ok());
// ...but we cannot gain a mutable reference.
assert!(entity.get_mut_by_id(*component_id).is_err());
// Instead, you must either remove or replace the value.
}
}
fn main() {
App::new()
.add_systems(Startup, demo_1)
.add_systems(Startup, demo_2)
.add_systems(Startup, demo_3)
.run();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/change_detection.rs | examples/ecs/change_detection.rs | //! This example illustrates how to react to component and resource changes.
use bevy::prelude::*;
use rand::Rng;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(
Update,
(
change_component,
change_component_2,
change_resource,
change_detection,
),
)
.run();
}
#[derive(Component, PartialEq, Debug)]
struct MyComponent(f32);
#[derive(Resource, PartialEq, Debug)]
struct MyResource(f32);
fn setup(mut commands: Commands) {
// Note the first change detection log correctly points to this line because the component is
// added. Although commands are deferred, they are able to track the original calling location.
commands.spawn(MyComponent(0.0));
commands.insert_resource(MyResource(0.0));
}
fn change_component(time: Res<Time>, mut query: Query<(Entity, &mut MyComponent)>) {
for (entity, mut component) in &mut query {
if rand::rng().random_bool(0.1) {
let new_component = MyComponent(time.elapsed_secs().round());
info!("New value: {new_component:?} {entity}");
// Change detection occurs on mutable dereference, and does not consider whether or not
// a value is actually equal. To avoid triggering change detection when nothing has
// actually changed, you can use the `set_if_neq` method on any component or resource
// that implements PartialEq.
component.set_if_neq(new_component);
}
}
}
/// This is a duplicate of the `change_component` system, added to show that change tracking can
/// help you find *where* your component is being changed, when there are multiple possible
/// locations.
fn change_component_2(time: Res<Time>, mut query: Query<(Entity, &mut MyComponent)>) {
for (entity, mut component) in &mut query {
if rand::rng().random_bool(0.1) {
let new_component = MyComponent(time.elapsed_secs().round());
info!("New value: {new_component:?} {entity}");
component.set_if_neq(new_component);
}
}
}
/// Change detection concepts for components apply similarly to resources.
fn change_resource(time: Res<Time>, mut my_resource: ResMut<MyResource>) {
if rand::rng().random_bool(0.1) {
let new_resource = MyResource(time.elapsed_secs().round());
info!("New value: {new_resource:?}");
my_resource.set_if_neq(new_resource);
}
}
/// Query filters like [`Changed<T>`] and [`Added<T>`] ensure only entities matching these filters
/// will be returned by the query.
///
/// Using the [`Ref<T>`] system param allows you to access change detection information, but does
/// not filter the query.
fn change_detection(
changed_components: Query<Ref<MyComponent>, Changed<MyComponent>>,
my_resource: Res<MyResource>,
) {
for component in &changed_components {
// By default, you can only tell that a component was changed.
//
// This is useful, but what if you have multiple systems modifying the same component, how
// will you know which system is causing the component to change?
warn!(
"Change detected!\n\t-> value: {:?}\n\t-> added: {}\n\t-> changed: {}\n\t-> changed by: {}",
component,
component.is_added(),
component.is_changed(),
// If you enable the `track_location` feature, you can unlock the `changed_by()`
// method. It returns the file and line number that the component or resource was
// changed in. It's not recommended for released games, but great for debugging!
component.changed_by()
);
}
if my_resource.is_changed() {
warn!(
"Change detected!\n\t-> value: {:?}\n\t-> added: {}\n\t-> changed: {}\n\t-> changed by: {}",
my_resource,
my_resource.is_added(),
my_resource.is_changed(),
my_resource.changed_by() // Like components, requires `track_location` feature.
);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/state_scoped.rs | examples/ecs/state_scoped.rs | //! Shows how to spawn entities that are automatically despawned either when
//! entering or exiting specific game states.
//!
//! This pattern is useful for managing menus, levels, or other state-specific
//! content that should only exist during certain states.
//!
//! If the entity was already despawned then no error will be logged. This means
//! that you don't have to worry about duplicate [`DespawnOnExit`] and
//! [`DespawnOnEnter`] components deep in your hierarchy.
use bevy::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_state::<GameState>()
.add_systems(Startup, setup_camera)
.add_systems(OnEnter(GameState::A), on_a_enter)
.add_systems(OnEnter(GameState::B), on_b_enter)
.add_systems(OnExit(GameState::A), on_a_exit)
.add_systems(OnExit(GameState::B), on_b_exit)
.add_systems(Update, toggle)
.insert_resource(TickTock(Timer::from_seconds(1.0, TimerMode::Repeating)))
.run();
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default, States)]
enum GameState {
#[default]
A,
B,
}
#[derive(Resource)]
struct TickTock(Timer);
fn on_a_enter(mut commands: Commands) {
info!("on_a_enter");
commands.spawn((
DespawnOnExit(GameState::A),
Text::new("Game is in state 'A'"),
TextFont {
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.5, 0.5, 1.0)),
Node {
position_type: PositionType::Absolute,
top: px(0),
left: px(0),
..default()
},
(children![DespawnOnExit(GameState::A)]),
));
}
fn on_a_exit(mut commands: Commands) {
info!("on_a_exit");
commands.spawn((
DespawnOnEnter(GameState::A),
Text::new("Game state 'A' will be back in 1 second"),
TextFont {
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.5, 0.5, 1.0)),
Node {
position_type: PositionType::Absolute,
top: px(0),
left: px(500),
..default()
},
// You can apply this even when the parent has a state scoped component.
// It is unnecessary but in complex hierarchies it saves you from having to
// mentally track which components are found at the top level.
(children![DespawnOnEnter(GameState::A)]),
));
}
fn on_b_enter(mut commands: Commands) {
info!("on_b_enter");
commands.spawn((
DespawnOnExit(GameState::B),
Text::new("Game is in state 'B'"),
TextFont {
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.5, 0.5, 1.0)),
Node {
position_type: PositionType::Absolute,
top: px(50),
left: px(0),
..default()
},
(children![DespawnOnExit(GameState::B)]),
));
}
fn on_b_exit(mut commands: Commands) {
info!("on_b_exit");
commands.spawn((
DespawnOnEnter(GameState::B),
Text::new("Game state 'B' will be back in 1 second"),
TextFont {
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.5, 0.5, 1.0)),
Node {
position_type: PositionType::Absolute,
top: px(50),
left: px(500),
..default()
},
(children![DespawnOnEnter(GameState::B)]),
));
}
fn setup_camera(mut commands: Commands) {
commands.spawn(Camera3d::default());
}
fn toggle(
time: Res<Time>,
mut timer: ResMut<TickTock>,
state: Res<State<GameState>>,
mut next_state: ResMut<NextState<GameState>>,
) {
if !timer.0.tick(time.delta()).is_finished() {
return;
}
*next_state = match state.get() {
GameState::A => NextState::Pending(GameState::B),
GameState::B => NextState::Pending(GameState::A),
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/one_shot_systems.rs | examples/ecs/one_shot_systems.rs | //! Demonstrates the use of "one-shot systems", which run once when triggered.
//!
//! These can be useful to help structure your logic in a push-based fashion,
//! reducing the overhead of running extremely rarely run systems
//! and improving schedule flexibility.
//!
//! See the [`World::run_system`](World::run_system) or
//! [`World::run_system_once`](World#method.run_system_once_with)
//! docs for more details.
use bevy::{
ecs::system::{RunSystemOnce, SystemId},
prelude::*,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(
Startup,
(
setup_ui,
setup_with_commands,
setup_with_world.after(setup_ui), // since we run `system_b` once in world it needs to run after `setup_ui`
),
)
.add_systems(Update, (trigger_system, evaluate_callbacks).chain())
.run();
}
#[derive(Component)]
struct Callback(SystemId);
#[derive(Component)]
struct Triggered;
#[derive(Component)]
struct A;
#[derive(Component)]
struct B;
fn setup_with_commands(mut commands: Commands) {
let system_id = commands.register_system(system_a);
commands.spawn((Callback(system_id), A));
}
fn setup_with_world(world: &mut World) {
// We can run it once manually
world.run_system_once(system_b).unwrap();
// Or with a Callback
let system_id = world.register_system(system_b);
world.spawn((Callback(system_id), B));
}
/// Tag entities that have callbacks we want to run with the `Triggered` component.
fn trigger_system(
mut commands: Commands,
query_a: Single<Entity, With<A>>,
query_b: Single<Entity, With<B>>,
input: Res<ButtonInput<KeyCode>>,
) {
if input.just_pressed(KeyCode::KeyA) {
let entity = *query_a;
commands.entity(entity).insert(Triggered);
}
if input.just_pressed(KeyCode::KeyB) {
let entity = *query_b;
commands.entity(entity).insert(Triggered);
}
}
/// Runs the systems associated with each `Callback` component if the entity also has a `Triggered` component.
///
/// This could be done in an exclusive system rather than using `Commands` if preferred.
fn evaluate_callbacks(query: Query<(Entity, &Callback), With<Triggered>>, mut commands: Commands) {
for (entity, callback) in query.iter() {
commands.run_system(callback.0);
commands.entity(entity).remove::<Triggered>();
}
}
fn system_a(entity_a: Single<Entity, With<Text>>, mut writer: TextUiWriter) {
*writer.text(*entity_a, 3) = String::from("A");
info!("A: One shot system registered with Commands was triggered");
}
fn system_b(entity_b: Single<Entity, With<Text>>, mut writer: TextUiWriter) {
*writer.text(*entity_b, 3) = String::from("B");
info!("B: One shot system registered with World was triggered");
}
fn setup_ui(mut commands: Commands) {
commands.spawn(Camera2d);
commands.spawn((
Text::default(),
TextLayout::new_with_justify(Justify::Center),
Node {
align_self: AlignSelf::Center,
justify_self: JustifySelf::Center,
..default()
},
children![
(TextSpan::new("Press A or B to trigger a one-shot system\n")),
(TextSpan::new("Last Triggered: ")),
(
TextSpan::new("-"),
TextColor(bevy::color::palettes::css::ORANGE.into()),
)
],
));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/iter_combinations.rs | examples/ecs/iter_combinations.rs | //! Shows how to iterate over combinations of query results.
use bevy::{color::palettes::css::ORANGE_RED, math::FloatPow, prelude::*};
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(ClearColor(Color::BLACK))
.add_systems(Startup, generate_bodies)
.add_systems(FixedUpdate, (interact_bodies, integrate))
.add_systems(Update, look_at_star)
.run();
}
const GRAVITY_CONSTANT: f32 = 0.001;
const NUM_BODIES: usize = 100;
#[derive(Component, Default)]
struct Mass(f32);
#[derive(Component, Default)]
struct Acceleration(Vec3);
#[derive(Component, Default)]
struct LastPos(Vec3);
#[derive(Component)]
struct Star;
#[derive(Bundle, Default)]
struct BodyBundle {
mesh: Mesh3d,
material: MeshMaterial3d<StandardMaterial>,
mass: Mass,
last_pos: LastPos,
acceleration: Acceleration,
}
fn generate_bodies(
time: Res<Time<Fixed>>,
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let mesh = meshes.add(Sphere::new(1.0).mesh().ico(3).unwrap());
let color_range = 0.5..1.0;
let vel_range = -0.5..0.5;
// We're seeding the PRNG here to make this example deterministic for testing purposes.
// This isn't strictly required in practical use unless you need your app to be deterministic.
let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
for _ in 0..NUM_BODIES {
let radius: f32 = rng.random_range(0.1..0.7);
let mass_value = FloatPow::cubed(radius) * 10.;
let position = Vec3::new(
rng.random_range(-1.0..1.0),
rng.random_range(-1.0..1.0),
rng.random_range(-1.0..1.0),
)
.normalize()
* ops::cbrt(rng.random_range(0.2f32..1.0))
* 15.;
commands.spawn((
BodyBundle {
mesh: Mesh3d(mesh.clone()),
material: MeshMaterial3d(materials.add(Color::srgb(
rng.random_range(color_range.clone()),
rng.random_range(color_range.clone()),
rng.random_range(color_range.clone()),
))),
mass: Mass(mass_value),
acceleration: Acceleration(Vec3::ZERO),
last_pos: LastPos(
position
- Vec3::new(
rng.random_range(vel_range.clone()),
rng.random_range(vel_range.clone()),
rng.random_range(vel_range.clone()),
) * time.timestep().as_secs_f32(),
),
},
Transform {
translation: position,
scale: Vec3::splat(radius),
..default()
},
));
}
// add bigger "star" body in the center
let star_radius = 1.;
commands
.spawn((
BodyBundle {
mesh: Mesh3d(meshes.add(Sphere::new(1.0).mesh().ico(5).unwrap())),
material: MeshMaterial3d(materials.add(StandardMaterial {
base_color: ORANGE_RED.into(),
emissive: LinearRgba::from(ORANGE_RED) * 2.,
..default()
})),
mass: Mass(500.0),
..default()
},
Transform::from_scale(Vec3::splat(star_radius)),
Star,
))
.with_child(PointLight {
color: Color::WHITE,
range: 100.0,
radius: star_radius,
..default()
});
commands.spawn((
Camera3d::default(),
Transform::from_xyz(0.0, 10.5, -30.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
fn interact_bodies(mut query: Query<(&Mass, &GlobalTransform, &mut Acceleration)>) {
let mut iter = query.iter_combinations_mut();
while let Some([(Mass(m1), transform1, mut acc1), (Mass(m2), transform2, mut acc2)]) =
iter.fetch_next()
{
let delta = transform2.translation() - transform1.translation();
let distance_sq: f32 = delta.length_squared();
let f = GRAVITY_CONSTANT / distance_sq;
let force_unit_mass = delta * f;
acc1.0 += force_unit_mass * *m2;
acc2.0 -= force_unit_mass * *m1;
}
}
fn integrate(time: Res<Time>, mut query: Query<(&mut Acceleration, &mut Transform, &mut LastPos)>) {
let dt_sq = time.delta_secs() * time.delta_secs();
for (mut acceleration, mut transform, mut last_pos) in &mut query {
// verlet integration
// x(t+dt) = 2x(t) - x(t-dt) + a(t)dt^2 + O(dt^4)
let new_pos = transform.translation * 2.0 - last_pos.0 + acceleration.0 * dt_sq;
acceleration.0 = Vec3::ZERO;
last_pos.0 = transform.translation;
transform.translation = new_pos;
}
}
fn look_at_star(
mut camera: Single<&mut Transform, (With<Camera>, Without<Star>)>,
star: Single<&Transform, With<Star>>,
) {
let new_rotation = camera
.looking_at(star.translation, Vec3::Y)
.rotation
.lerp(camera.rotation, 0.1);
camera.rotation = new_rotation;
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/observers.rs | examples/ecs/observers.rs | //! Demonstrates how to observe events: both component lifecycle events and custom events.
use bevy::{
platform::collections::{HashMap, HashSet},
prelude::*,
};
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_resource::<SpatialIndex>()
.add_systems(Startup, setup)
.add_systems(Update, (draw_shapes, handle_click))
// Observers are systems that run when an event is "triggered". This observer runs whenever
// `ExplodeMines` is triggered.
.add_observer(
|explode_mines: On<ExplodeMines>,
mines: Query<&Mine>,
index: Res<SpatialIndex>,
mut commands: Commands| {
// Access resources
for entity in index.get_nearby(explode_mines.pos) {
// Run queries
let mine = mines.get(entity).unwrap();
if mine.pos.distance(explode_mines.pos) < mine.size + explode_mines.radius {
// And queue commands, including triggering additional events
// Here we trigger the `Explode` event for entity `e`
commands.trigger(Explode { entity });
}
}
},
)
// This observer runs whenever the `Mine` component is added to an entity, and places it in a simple spatial index.
.add_observer(on_add_mine)
// This observer runs whenever the `Mine` component is removed from an entity (including despawning it)
// and removes it from the spatial index.
.add_observer(on_remove_mine)
.run();
}
#[derive(Component)]
struct Mine {
pos: Vec2,
size: f32,
}
impl Mine {
fn random(rand: &mut ChaCha8Rng) -> Self {
Mine {
pos: Vec2::new(
(rand.random::<f32>() - 0.5) * 1200.0,
(rand.random::<f32>() - 0.5) * 600.0,
),
size: 4.0 + rand.random::<f32>() * 16.0,
}
}
}
/// This is a normal [`Event`]. Any observer that watches for it will run when it is triggered.
#[derive(Event)]
struct ExplodeMines {
pos: Vec2,
radius: f32,
}
/// An [`EntityEvent`] is a specialized type of [`Event`] that can target a specific entity. In addition to
/// running normal "top level" observers when it is triggered (which target _any_ entity that Explodes), it will
/// also run any observers that target the _specific_ entity for that event.
#[derive(EntityEvent)]
struct Explode {
entity: Entity,
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
commands.spawn((
Text::new(
"Click on a \"Mine\" to trigger it.\n\
When it explodes it will trigger all overlapping mines.",
),
Node {
position_type: PositionType::Absolute,
top: px(12),
left: px(12),
..default()
},
));
let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
commands
.spawn(Mine::random(&mut rng))
// Observers can watch for events targeting a specific entity.
// This will create a new observer that runs whenever the Explode event
// is triggered for this spawned entity.
.observe(explode_mine);
// We want to spawn a bunch of mines. We could just call the code above for each of them.
// That would create a new observer instance for every Mine entity. Having duplicate observers
// generally isn't worth worrying about as the overhead is low. But if you want to be maximally efficient,
// you can reuse observers across entities.
//
// First, observers are actually just entities with the Observer component! The `observe()` functions
// you've seen so far in this example are just shorthand for manually spawning an observer.
let mut observer = Observer::new(explode_mine);
// As we spawn entities, we can make this observer watch each of them:
for _ in 0..1000 {
let entity = commands.spawn(Mine::random(&mut rng)).id();
observer.watch_entity(entity);
}
// By spawning the Observer component, it becomes active!
commands.spawn(observer);
}
fn on_add_mine(add: On<Add, Mine>, query: Query<&Mine>, mut index: ResMut<SpatialIndex>) {
let mine = query.get(add.entity).unwrap();
let tile = (
(mine.pos.x / CELL_SIZE).floor() as i32,
(mine.pos.y / CELL_SIZE).floor() as i32,
);
index.map.entry(tile).or_default().insert(add.entity);
}
// Remove despawned mines from our index
fn on_remove_mine(remove: On<Remove, Mine>, query: Query<&Mine>, mut index: ResMut<SpatialIndex>) {
let mine = query.get(remove.entity).unwrap();
let tile = (
(mine.pos.x / CELL_SIZE).floor() as i32,
(mine.pos.y / CELL_SIZE).floor() as i32,
);
index.map.entry(tile).and_modify(|set| {
set.remove(&remove.entity);
});
}
fn explode_mine(explode: On<Explode>, query: Query<&Mine>, mut commands: Commands) {
// Explode is an EntityEvent. `explode.entity` is the entity that Explode was triggered for.
let Ok(mut entity) = commands.get_entity(explode.entity) else {
return;
};
info!("Boom! {} exploded.", explode.entity);
entity.despawn();
let mine = query.get(explode.entity).unwrap();
// Trigger another explosion cascade.
commands.trigger(ExplodeMines {
pos: mine.pos,
radius: mine.size,
});
}
// Draw a circle for each mine using `Gizmos`
fn draw_shapes(mut gizmos: Gizmos, mines: Query<&Mine>) {
for mine in &mines {
gizmos.circle_2d(
mine.pos,
mine.size,
Color::hsl((mine.size - 4.0) / 16.0 * 360.0, 1.0, 0.8),
);
}
}
// Trigger `ExplodeMines` at the position of a given click
fn handle_click(
mouse_button_input: Res<ButtonInput<MouseButton>>,
camera: Single<(&Camera, &GlobalTransform)>,
windows: Query<&Window>,
mut commands: Commands,
) {
let Ok(windows) = windows.single() else {
return;
};
let (camera, camera_transform) = *camera;
if let Some(pos) = windows
.cursor_position()
.and_then(|cursor| camera.viewport_to_world(camera_transform, cursor).ok())
.map(|ray| ray.origin.truncate())
&& mouse_button_input.just_pressed(MouseButton::Left)
{
commands.trigger(ExplodeMines { pos, radius: 1.0 });
}
}
#[derive(Resource, Default)]
struct SpatialIndex {
map: HashMap<(i32, i32), HashSet<Entity>>,
}
/// Cell size has to be bigger than any `TriggerMine::radius`
const CELL_SIZE: f32 = 64.0;
impl SpatialIndex {
// Lookup all entities within adjacent cells of our spatial index
fn get_nearby(&self, pos: Vec2) -> Vec<Entity> {
let tile = (
(pos.x / CELL_SIZE).floor() as i32,
(pos.y / CELL_SIZE).floor() as i32,
);
let mut nearby = Vec::new();
for x in -1..2 {
for y in -1..2 {
if let Some(mines) = self.map.get(&(tile.0 + x, tile.1 + y)) {
nearby.extend(mines.iter());
}
}
}
nearby
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/entity_disabling.rs | examples/ecs/entity_disabling.rs | //! Disabling entities is a powerful feature that allows you to hide entities from the ECS without deleting them.
//!
//! This can be useful for implementing features like "sleeping" objects that are offscreen
//! or managing networked entities.
//!
//! While disabling entities *will* make them invisible,
//! that's not its primary purpose!
//! [`Visibility`] should be used to hide entities;
//! disabled entities are skipped entirely, which can lead to subtle bugs.
//!
//! # Default query filters
//!
//! Under the hood, Bevy uses a "default query filter" that skips entities with the
//! the [`Disabled`] component.
//! These filters act as a by-default exclusion list for all queries,
//! and can be bypassed by explicitly including these components in your queries.
//! For example, `Query<&A, With<Disabled>`, `Query<(Entity, Has<Disabled>>)` or
//! `Query<&A, Or<(With<Disabled>, With<B>)>>` will include disabled entities.
use bevy::ecs::entity_disabling::Disabled;
use bevy::prelude::*;
fn main() {
App::new()
.add_plugins((DefaultPlugins, MeshPickingPlugin))
.add_observer(disable_entities_on_click)
.add_systems(
Update,
(list_all_named_entities, reenable_entities_on_space),
)
.add_systems(Startup, (setup_scene, display_instructions))
.run();
}
#[derive(Component)]
struct DisableOnClick;
fn disable_entities_on_click(
click: On<Pointer<Click>>,
valid_query: Query<&DisableOnClick>,
mut commands: Commands,
) {
// Windows and text are entities and can be clicked!
// We definitely don't want to disable the window itself,
// because that would cause the app to close!
if valid_query.contains(click.entity) {
// Just add the `Disabled` component to the entity to disable it.
// Note that the `Disabled` component is *only* added to the entity,
// its children are not affected.
commands.entity(click.entity).insert(Disabled);
}
}
#[derive(Component)]
struct EntityNameText;
// The query here will not find entities with the `Disabled` component,
// because it does not explicitly include it.
fn list_all_named_entities(
query: Query<&Name>,
mut name_text_query: Query<&mut Text, With<EntityNameText>>,
mut commands: Commands,
) {
let mut text_string = String::from("Named entities found:\n");
// Query iteration order is not guaranteed, so we sort the names
// to ensure the output is consistent.
for name in query.iter().sort::<&Name>() {
text_string.push_str(&format!("{name:?}\n"));
}
if let Ok(mut text) = name_text_query.single_mut() {
*text = Text::new(text_string);
} else {
commands.spawn((
EntityNameText,
Text::default(),
Node {
position_type: PositionType::Absolute,
top: px(12),
right: px(12),
..default()
},
));
}
}
fn reenable_entities_on_space(
mut commands: Commands,
// This query can find disabled entities,
// because it explicitly includes the `Disabled` component.
disabled_entities: Query<Entity, With<Disabled>>,
input: Res<ButtonInput<KeyCode>>,
) {
if input.just_pressed(KeyCode::Space) {
for entity in disabled_entities.iter() {
// To re-enable an entity, just remove the `Disabled` component.
commands.entity(entity).remove::<Disabled>();
}
}
}
const X_EXTENT: f32 = 900.;
fn setup_scene(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
commands.spawn(Camera2d);
let named_shapes = [
(Name::new("Annulus"), meshes.add(Annulus::new(25.0, 50.0))),
(
Name::new("Bestagon"),
meshes.add(RegularPolygon::new(50.0, 6)),
),
(Name::new("Rhombus"), meshes.add(Rhombus::new(75.0, 100.0))),
];
let num_shapes = named_shapes.len();
for (i, (name, shape)) in named_shapes.into_iter().enumerate() {
// Distribute colors evenly across the rainbow.
let color = Color::hsl(360. * i as f32 / num_shapes as f32, 0.95, 0.7);
commands.spawn((
name,
DisableOnClick,
Mesh2d(shape),
MeshMaterial2d(materials.add(color)),
Transform::from_xyz(
// Distribute shapes from -X_EXTENT/2 to +X_EXTENT/2.
-X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
0.0,
0.0,
),
));
}
}
fn display_instructions(mut commands: Commands) {
commands.spawn((
Text::new(
"Click an entity to disable it.\n\nPress Space to re-enable all disabled entities.",
),
Node {
position_type: PositionType::Absolute,
top: px(12),
left: px(12),
..default()
},
));
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/system_closure.rs | examples/ecs/system_closure.rs | //! Shows how anonymous functions / closures can be used as systems.
use bevy::{log::LogPlugin, prelude::*};
fn main() {
// create a simple closure.
let simple_closure = || {
// this is a closure that does nothing.
info!("Hello from a simple closure!");
};
// create a closure, with an 'input' value.
let complex_closure = |mut value: String| {
move || {
info!("Hello from a complex closure! {}", value);
// we can modify the value inside the closure. this will be saved between calls.
value = format!("{value} - updated");
// you could also use an outside variable like presented in the inlined closures
// info!("outside_variable! {}", outside_variable);
}
};
let outside_variable = "bar".to_string();
App::new()
.add_plugins(LogPlugin::default())
// we can use a closure as a system
.add_systems(Update, simple_closure)
// or we can use a more complex closure, and pass an argument to initialize a Local variable.
.add_systems(Update, complex_closure("foo".into()))
// we can also inline a closure
.add_systems(Update, || {
info!("Hello from an inlined closure!");
})
// or use variables outside a closure
.add_systems(Update, move || {
info!(
"Hello from an inlined closure that captured the 'outside_variable'! {}",
outside_variable
);
// you can use outside_variable, or any other variables inside this closure.
// their states will be saved.
})
.run();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/relationships.rs | examples/ecs/relationships.rs | //! Entities generally don't exist in isolation. Instead, they are related to other entities in various ways.
//! While Bevy comes with a built-in [`ChildOf`]/[`Children`] relationship
//! (which enables transform and visibility propagation),
//! you can define your own relationships using components.
//!
//! We can define a custom relationship by creating two components:
//! one to store the relationship itself, and another to keep track of the reverse relationship.
//! Bevy's [`ChildOf`] component implements the [`Relationship`] trait, serving as the source of truth,
//! while the [`Children`] component implements the [`RelationshipTarget`] trait and is used to accelerate traversals down the hierarchy.
//!
//! In this example we're creating a [`Targeting`]/[`TargetedBy`] relationship,
//! demonstrating how you might model units which target a single unit in combat.
use bevy::ecs::entity::EntityHashSet;
use bevy::ecs::system::RunSystemOnce;
use bevy::prelude::*;
/// The entity that this entity is targeting.
///
/// This is the source of truth for the relationship,
/// and can be modified directly to change the target.
#[derive(Component, Debug)]
#[relationship(relationship_target = TargetedBy)]
struct Targeting(Entity);
/// All entities that are targeting this entity.
///
/// This component is updated reactively using the component hooks introduced by deriving
/// the [`Relationship`] trait. We should not modify this component directly,
/// but can safely read its field. In a larger project, we could enforce this through the use of
/// private fields and public getters.
#[derive(Component, Debug)]
#[relationship_target(relationship = Targeting)]
struct TargetedBy(Vec<Entity>);
fn main() {
// Operating on a raw `World` and running systems one at a time
// is great for writing tests and teaching abstract concepts!
let mut world = World::new();
// We're going to spawn a few entities and relate them to each other in a complex way.
// To start, Bob will target Alice, Charlie will target Bob,
// and Alice will target Charlie. This creates a loop in the relationship graph.
//
// Then, we'll spawn Devon, who will target Charlie,
// creating a more complex graph with a branching structure.
fn spawning_entities_with_relationships(mut commands: Commands) {
// Calling .id() after spawning an entity will return the `Entity` identifier of the spawned entity,
// even though the entity itself is not yet instantiated in the world.
// This works because Commands will reserve the entity ID before actually spawning the entity,
// through the use of atomic counters.
let alice = commands.spawn(Name::new("Alice")).id();
// Relations are just components, so we can add them into the bundle that we're spawning.
let bob = commands.spawn((Name::new("Bob"), Targeting(alice))).id();
// The `with_related` and `with_related_entities` helper methods on `EntityCommands` can be used to add relations in a more ergonomic way.
let charlie = commands
.spawn((Name::new("Charlie"), Targeting(bob)))
// The `with_related` method will spawn a bundle with `Targeting` relationship
.with_related::<Targeting>(Name::new("James"))
// The `with_related_entities` method will automatically add the `Targeting` component to any entities spawned within the closure,
// targeting the entity that we're calling `with_related` on.
.with_related_entities::<Targeting>(|related_spawner_commands| {
// We could spawn multiple entities here, and they would all target `charlie`.
related_spawner_commands.spawn(Name::new("Devon"));
})
.id();
// Simply inserting the `Targeting` component will automatically create and update the `TargetedBy` component on the target entity.
// We can do this at any point; not just when the entity is spawned.
commands.entity(alice).insert(Targeting(charlie));
}
world
.run_system_once(spawning_entities_with_relationships)
.unwrap();
fn debug_relationships(
// Not all of our entities are targeted by something, so we use `Option` in our query to handle this case.
relations_query: Query<(&Name, &Targeting, Option<&TargetedBy>)>,
name_query: Query<&Name>,
) {
let mut relationships = String::new();
for (name, targeting, maybe_targeted_by) in relations_query.iter() {
let targeting_name = name_query.get(targeting.0).unwrap();
let targeted_by_string = if let Some(targeted_by) = maybe_targeted_by {
let mut vec_of_names = Vec::<&Name>::new();
for entity in targeted_by.iter() {
let name = name_query.get(entity).unwrap();
vec_of_names.push(name);
}
// Convert this to a nice string for printing.
let vec_of_str: Vec<&str> = vec_of_names.iter().map(|name| name.as_str()).collect();
vec_of_str.join(", ")
} else {
"nobody".to_string()
};
relationships.push_str(&format!(
"{name} is targeting {targeting_name}, and is targeted by {targeted_by_string}\n",
));
}
println!("{relationships}");
}
world.run_system_once(debug_relationships).unwrap();
// Demonstrates how to correctly mutate relationships.
// Relationship components are immutable! We can't query for the `Targeting` component mutably and modify it directly,
// but we can insert a new `Targeting` component to replace the old one.
// This allows the hooks on the `Targeting` component to update the `TargetedBy` component correctly.
// The `TargetedBy` component will be updated automatically!
fn mutate_relationships(name_query: Query<(Entity, &Name)>, mut commands: Commands) {
// Let's find Devon by doing a linear scan of the entity names.
let devon = name_query
.iter()
.find(|(_entity, name)| name.as_str() == "Devon")
.unwrap()
.0;
let alice = name_query
.iter()
.find(|(_entity, name)| name.as_str() == "Alice")
.unwrap()
.0;
println!("Making Devon target Alice.\n");
commands.entity(devon).insert(Targeting(alice));
}
world.run_system_once(mutate_relationships).unwrap();
world.run_system_once(debug_relationships).unwrap();
// Systems can return errors,
// which can be used to signal that something went wrong during the system's execution.
#[derive(Debug)]
#[expect(
dead_code,
reason = "Rust considers types that are only used by their debug trait as dead code."
)]
struct TargetingCycle {
initial_entity: Entity,
visited: EntityHashSet,
}
/// Bevy's relationships come with all sorts of useful methods for traversal.
/// Here, we're going to look for cycles using a depth-first search.
fn check_for_cycles(
// We want to check every entity for cycles
query_to_check: Query<Entity, With<Targeting>>,
// Fetch the names for easier debugging.
name_query: Query<&Name>,
// The targeting_query allows us to traverse the relationship graph.
targeting_query: Query<&Targeting>,
) -> Result<(), TargetingCycle> {
for initial_entity in query_to_check.iter() {
let mut visited = EntityHashSet::new();
let mut targeting_name = name_query.get(initial_entity).unwrap().clone();
println!("Checking for cycles starting at {targeting_name}",);
// There's all sorts of methods like this; check the `Query` docs for more!
// This would also be easy to do by just manually checking the `Targeting` component,
// and calling `query.get(targeted_entity)` on the entity that it targets in a loop.
for targeting in targeting_query.iter_ancestors(initial_entity) {
let target_name = name_query.get(targeting).unwrap();
println!("{targeting_name} is targeting {target_name}",);
targeting_name = target_name.clone();
if !visited.insert(targeting) {
return Err(TargetingCycle {
initial_entity,
visited,
});
}
}
}
// If we've checked all the entities and haven't found a cycle, we're good!
Ok(())
}
// Calling `world.run_system_once` on systems which return Results gives us two layers of errors:
// the first checks if running the system failed, and the second checks if the system itself returned an error.
// We're unwrapping the first, but checking the output of the system itself.
let cycle_result = world.run_system_once(check_for_cycles).unwrap();
println!("{cycle_result:?} \n");
// We deliberately introduced a cycle during spawning!
assert!(cycle_result.is_err());
// Now, let's demonstrate removing relationships and break the cycle.
fn untarget(mut commands: Commands, name_query: Query<(Entity, &Name)>) {
// Let's find Charlie by doing a linear scan of the entity names.
let charlie = name_query
.iter()
.find(|(_entity, name)| name.as_str() == "Charlie")
.unwrap()
.0;
// We can remove the `Targeting` component to remove the relationship
// and break the cycle we saw earlier.
println!("Removing Charlie's targeting relationship.\n");
commands.entity(charlie).remove::<Targeting>();
}
world.run_system_once(untarget).unwrap();
world.run_system_once(debug_relationships).unwrap();
// Cycle free!
let cycle_result = world.run_system_once(check_for_cycles).unwrap();
println!("{cycle_result:?} \n");
assert!(cycle_result.is_ok());
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/send_and_receive_messages.rs | examples/ecs/send_and_receive_messages.rs | //! From time to time, you may find that you want to both send and receive a message of the same type in a single system.
//!
//! Of course, this results in an error: the borrows of [`MessageWriter`] and [`MessageReader`] overlap,
//! if and only if the [`Message`] type is the same.
//! One system parameter borrows the [`Messages`] resource mutably, and another system parameter borrows the [`Messages`] resource immutably.
//! If Bevy allowed this, this would violate Rust's rules against aliased mutability.
//! In other words, this would be Undefined Behavior (UB)!
//!
//! There are two ways to solve this problem:
//!
//! 1. Use [`ParamSet`] to check out the [`MessageWriter`] and [`MessageReader`] one at a time.
//! 2. Use a [`Local`] [`MessageCursor`] instead of a [`MessageReader`], and use [`ResMut`] to access [`Messages`].
//!
//! In the first case, you're being careful to only check out only one of the [`MessageWriter`] or [`MessageReader`] at a time.
//! By "temporally" separating them, you avoid the overlap.
//!
//! In the second case, you only ever have one access to the underlying [`Messages`] resource at a time.
//! But in exchange, you have to manually keep track of which messages you've already read.
//!
//! Let's look at an example of each.
use bevy::{diagnostic::FrameCount, ecs::message::MessageCursor, prelude::*};
fn main() {
let mut app = App::new();
app.add_plugins(MinimalPlugins)
.add_message::<DebugMessage>()
.add_message::<A>()
.add_message::<B>()
.add_systems(Update, read_and_write_different_message_types)
.add_systems(
Update,
(
send_messages,
debug_messages,
send_and_receive_param_set,
debug_messages,
send_and_receive_manual_message_reader,
debug_messages,
)
.chain(),
);
// We're just going to run a few frames, so we can see and understand the output.
app.update();
// By running for longer than one frame, we can see that we're caching our cursor in the message queue properly.
app.update();
}
#[derive(Message)]
struct A;
#[derive(Message)]
struct B;
// This works fine, because the types are different,
// so the borrows of the `MessageWriter` and `MessageReader` don't overlap.
// Note that these borrowing rules are checked at system initialization time,
// not at compile time, as Bevy uses internal unsafe code to split the `World` into disjoint pieces.
fn read_and_write_different_message_types(mut a: MessageWriter<A>, mut b: MessageReader<B>) {
for _ in b.read() {}
a.write(A);
}
/// A dummy message type.
#[derive(Debug, Clone, Message)]
struct DebugMessage {
resend_from_param_set: bool,
resend_from_local_message_reader: bool,
times_sent: u8,
}
/// A system that sends all combinations of messages.
fn send_messages(mut debug_messages: MessageWriter<DebugMessage>, frame_count: Res<FrameCount>) {
println!("Sending messages for frame {}", frame_count.0);
debug_messages.write(DebugMessage {
resend_from_param_set: false,
resend_from_local_message_reader: false,
times_sent: 1,
});
debug_messages.write(DebugMessage {
resend_from_param_set: true,
resend_from_local_message_reader: false,
times_sent: 1,
});
debug_messages.write(DebugMessage {
resend_from_param_set: false,
resend_from_local_message_reader: true,
times_sent: 1,
});
debug_messages.write(DebugMessage {
resend_from_param_set: true,
resend_from_local_message_reader: true,
times_sent: 1,
});
}
/// A system that prints all messages sent since the last time this system ran.
///
/// Note that some messages will be printed twice, because they were sent twice.
fn debug_messages(mut messages: MessageReader<DebugMessage>) {
for message in messages.read() {
println!("{message:?}");
}
}
/// A system that both sends and receives messages using [`ParamSet`].
fn send_and_receive_param_set(
mut param_set: ParamSet<(MessageReader<DebugMessage>, MessageWriter<DebugMessage>)>,
frame_count: Res<FrameCount>,
) {
println!(
"Sending and receiving messages for frame {} with a `ParamSet`",
frame_count.0
);
// We must collect the messages to resend, because we can't access the writer while we're iterating over the reader.
let mut messages_to_resend = Vec::new();
// This is p0, as the first parameter in the `ParamSet` is the reader.
for message in param_set.p0().read() {
if message.resend_from_param_set {
messages_to_resend.push(message.clone());
}
}
// This is p1, as the second parameter in the `ParamSet` is the writer.
for mut message in messages_to_resend {
message.times_sent += 1;
param_set.p1().write(message);
}
}
/// A system that both sends and receives messages using a [`Local`] [`MessageCursor`].
fn send_and_receive_manual_message_reader(
// The `Local` `SystemParam` stores state inside the system itself, rather than in the world.
// `MessageCursor<T>` is the internal state of `MessageReader<T>`, which tracks which messages have been seen.
mut local_message_reader: Local<MessageCursor<DebugMessage>>,
// We can access the `Messages` resource mutably, allowing us to both read and write its contents.
mut messages: ResMut<Messages<DebugMessage>>,
frame_count: Res<FrameCount>,
) {
println!(
"Sending and receiving messages for frame {} with a `Local<MessageCursor>",
frame_count.0
);
// We must collect the messages to resend, because we can't mutate messages while we're iterating over the messages.
let mut messages_to_resend = Vec::new();
for message in local_message_reader.read(&messages) {
if message.resend_from_local_message_reader {
// For simplicity, we're cloning the message.
// In this case, since we have mutable access to the `Messages` resource,
// we could also just mutate the message in-place,
// or drain the message queue into our `messages_to_resend` vector.
messages_to_resend.push(message.clone());
}
}
for mut message in messages_to_resend {
message.times_sent += 1;
messages.write(message);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/component_hooks.rs | examples/ecs/component_hooks.rs | //! This example illustrates the different ways you can employ component lifecycle hooks.
//!
//! Whenever possible, prefer using Bevy's change detection or Events for reacting to component changes.
//! Events generally offer better performance and more flexible integration into Bevy's systems.
//! Hooks are useful to enforce correctness but have limitations (only one hook per component,
//! less ergonomic than events).
//!
//! Here are some cases where components hooks might be necessary:
//!
//! - Maintaining indexes: If you need to keep custom data structures (like a spatial index) in
//! sync with the addition/removal of components.
//!
//! - Enforcing structural rules: When you have systems that depend on specific relationships
//! between components (like hierarchies or parent-child links) and need to maintain correctness.
use bevy::{
ecs::component::{Mutable, StorageType},
ecs::lifecycle::{ComponentHook, HookContext},
prelude::*,
};
use std::collections::HashMap;
#[derive(Debug)]
/// Hooks can also be registered during component initialization by
/// using [`Component`] derive macro:
/// ```no_run
/// #[derive(Component)]
/// #[component(on_add = ..., on_insert = ..., on_replace = ..., on_remove = ...)]
/// ```
struct MyComponent(KeyCode);
impl Component for MyComponent {
const STORAGE_TYPE: StorageType = StorageType::Table;
type Mutability = Mutable;
/// Hooks can also be registered during component initialization by
/// implementing the associated method
fn on_add() -> Option<ComponentHook> {
// We don't have an `on_add` hook so we'll just return None.
// Note that this is the default behavior when not implementing a hook.
None
}
}
#[derive(Resource, Default, Debug, Deref, DerefMut)]
struct MyComponentIndex(HashMap<KeyCode, Entity>);
#[derive(Message)]
struct MyMessage;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, trigger_hooks)
.init_resource::<MyComponentIndex>()
.add_message::<MyMessage>()
.run();
}
fn setup(world: &mut World) {
// In order to register component hooks the component must:
// - not be currently in use by any entities in the world
// - not already have a hook of that kind registered
// This is to prevent overriding hooks defined in plugins and other crates as well as keeping things fast
world
.register_component_hooks::<MyComponent>()
// There are 4 component lifecycle hooks: `on_add`, `on_insert`, `on_replace` and `on_remove`
// A hook has 2 arguments:
// - a `DeferredWorld`, this allows access to resource and component data as well as `Commands`
// - a `HookContext`, this provides access to the following contextual information:
// - the entity that triggered the hook
// - the component id of the triggering component, this is mostly used for dynamic components
// - the location of the code that caused the hook to trigger
//
// `on_add` will trigger when a component is inserted onto an entity without it
.on_add(
|mut world,
HookContext {
entity,
component_id,
caller,
..
}| {
// You can access component data from within the hook
let value = world.get::<MyComponent>(entity).unwrap().0;
println!(
"{component_id:?} added to {entity} with value {value:?}{}",
caller
.map(|location| format!("due to {location}"))
.unwrap_or_default()
);
// Or access resources
world
.resource_mut::<MyComponentIndex>()
.insert(value, entity);
// Or send messages
world.write_message(MyMessage);
},
)
// `on_insert` will trigger when a component is inserted onto an entity,
// regardless of whether or not it already had it and after `on_add` if it ran
.on_insert(|world, _| {
println!("Current Index: {:?}", world.resource::<MyComponentIndex>());
})
// `on_replace` will trigger when a component is inserted onto an entity that already had it,
// and runs before the value is replaced.
// Also triggers when a component is removed from an entity, and runs before `on_remove`
.on_replace(|mut world, context| {
let value = world.get::<MyComponent>(context.entity).unwrap().0;
world.resource_mut::<MyComponentIndex>().remove(&value);
})
// `on_remove` will trigger when a component is removed from an entity,
// since it runs before the component is removed you can still access the component data
.on_remove(
|mut world,
HookContext {
entity,
component_id,
caller,
..
}| {
let value = world.get::<MyComponent>(entity).unwrap().0;
println!(
"{component_id:?} removed from {entity} with value {value:?}{}",
caller
.map(|location| format!("due to {location}"))
.unwrap_or_default()
);
// You can also issue commands through `.commands()`
world.commands().entity(entity).despawn();
},
);
}
fn trigger_hooks(
mut commands: Commands,
keys: Res<ButtonInput<KeyCode>>,
index: Res<MyComponentIndex>,
) {
for (key, entity) in index.iter() {
if !keys.pressed(*key) {
commands.entity(*entity).remove::<MyComponent>();
}
}
for key in keys.get_just_pressed() {
commands.spawn(MyComponent(*key));
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/system_param.rs | examples/ecs/system_param.rs | //! This example creates a custom [`SystemParam`] struct that counts the number of players.
use bevy::{ecs::system::SystemParam, prelude::*};
fn main() {
App::new()
.insert_resource(PlayerCount(0))
.add_systems(Startup, spawn)
.add_systems(Update, count_players)
.run();
}
#[derive(Component)]
struct Player;
#[derive(Resource)]
struct PlayerCount(usize);
/// The [`SystemParam`] struct can contain any types that can also be included in a
/// system function signature.
///
/// In this example, it includes a query and a mutable resource.
#[derive(SystemParam)]
struct PlayerCounter<'w, 's> {
players: Query<'w, 's, &'static Player>,
count: ResMut<'w, PlayerCount>,
}
impl<'w, 's> PlayerCounter<'w, 's> {
fn count(&mut self) {
self.count.0 = self.players.iter().len();
}
}
/// Spawn some players to count
fn spawn(mut commands: Commands) {
commands.spawn(Player);
commands.spawn(Player);
commands.spawn(Player);
}
/// The [`SystemParam`] can be used directly in a system argument.
fn count_players(mut counter: PlayerCounter) {
counter.count();
println!("{} players in the game", counter.count.0);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/ecs_guide.rs | examples/ecs/ecs_guide.rs | //! This is a guided introduction to Bevy's "Entity Component System" (ECS)
//! All Bevy app logic is built using the ECS pattern, so definitely pay attention!
//!
//! Why ECS?
//! * Data oriented: Functionality is driven by data
//! * Clean Architecture: Loose coupling of functionality / prevents deeply nested inheritance
//! * High Performance: Massively parallel and cache friendly
//!
//! ECS Definitions:
//!
//! Component: just a normal Rust data type. generally scoped to a single piece of functionality
//! Examples: position, velocity, health, color, name
//!
//! Entity: a collection of components with a unique id
//! Examples: Entity1 { Name("Alice"), Position(0, 0) },
//! Entity2 { Name("Bill"), Position(10, 5) }
//!
//! Resource: a shared global piece of data
//! Examples: asset storage, messages, system state
//!
//! System: runs logic on entities, components, and resources
//! Examples: move system, damage system
//!
//! Now that you know a little bit about ECS, lets look at some Bevy code!
//! We will now make a simple "game" to illustrate what Bevy's ECS looks like in practice.
use bevy::{
app::{AppExit, ScheduleRunnerPlugin},
prelude::*,
};
use core::time::Duration;
use rand::random;
use std::fmt;
// COMPONENTS: Pieces of functionality we add to entities. These are just normal Rust data types
//
// Our game will have a number of "players". Each player has a name that identifies them
#[derive(Component)]
struct Player {
name: String,
}
// Each player also has a score. This component holds on to that score
#[derive(Component)]
struct Score {
value: usize,
}
// Enums can also be used as components.
// This component tracks how many consecutive rounds a player has/hasn't scored in.
#[derive(Component)]
enum PlayerStreak {
Hot(usize),
None,
Cold(usize),
}
impl fmt::Display for PlayerStreak {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PlayerStreak::Hot(n) => write!(f, "{n} round hot streak"),
PlayerStreak::None => write!(f, "0 round streak"),
PlayerStreak::Cold(n) => write!(f, "{n} round cold streak"),
}
}
}
// RESOURCES: "Global" state accessible by systems. These are also just normal Rust data types!
//
// This resource holds information about the game:
#[derive(Resource, Default)]
struct GameState {
current_round: usize,
total_players: usize,
winning_player: Option<String>,
}
// This resource provides rules for our "game".
#[derive(Resource)]
struct GameRules {
winning_score: usize,
max_rounds: usize,
max_players: usize,
}
// SYSTEMS: Logic that runs on entities, components, and resources. These generally run once each
// time the app updates.
//
// This is the simplest type of system. It just prints "This game is fun!" on each run:
fn print_message_system() {
println!("This game is fun!");
}
// Systems can also read and modify resources. This system starts a new "round" on each update:
// NOTE: "mut" denotes that the resource is "mutable"
// Res<GameRules> is read-only. ResMut<GameState> can modify the resource
fn new_round_system(game_rules: Res<GameRules>, mut game_state: ResMut<GameState>) {
game_state.current_round += 1;
println!(
"Begin round {} of {}",
game_state.current_round, game_rules.max_rounds
);
}
// This system updates the score for each entity with the `Player`, `Score` and `PlayerStreak` components.
fn score_system(mut query: Query<(&Player, &mut Score, &mut PlayerStreak)>) {
for (player, mut score, mut streak) in &mut query {
let scored_a_point = random::<bool>();
if scored_a_point {
// Accessing components immutably is done via a regular reference - `player`
// has type `&Player`.
//
// Accessing components mutably is performed via type `Mut<T>` - `score`
// has type `Mut<Score>` and `streak` has type `Mut<PlayerStreak>`.
//
// `Mut<T>` implements `Deref<T>`, so struct fields can be updated using
// standard field update syntax ...
score.value += 1;
// ... and matching against enums requires dereferencing them
*streak = match *streak {
PlayerStreak::Hot(n) => PlayerStreak::Hot(n + 1),
PlayerStreak::Cold(_) | PlayerStreak::None => PlayerStreak::Hot(1),
};
println!(
"{} scored a point! Their score is: {} ({})",
player.name, score.value, *streak
);
} else {
*streak = match *streak {
PlayerStreak::Hot(_) | PlayerStreak::None => PlayerStreak::Cold(1),
PlayerStreak::Cold(n) => PlayerStreak::Cold(n + 1),
};
println!(
"{} did not score a point! Their score is: {} ({})",
player.name, score.value, *streak
);
}
}
// this game isn't very fun is it :)
}
// This system runs on all entities with the `Player` and `Score` components, but it also
// accesses the `GameRules` resource to determine if a player has won.
fn score_check_system(
game_rules: Res<GameRules>,
mut game_state: ResMut<GameState>,
query: Query<(&Player, &Score)>,
) {
for (player, score) in &query {
if score.value == game_rules.winning_score {
game_state.winning_player = Some(player.name.clone());
}
}
}
// This system ends the game if we meet the right conditions. This fires an AppExit message, which
// tells our App to quit. Check out the "message.rs" example if you want to learn more about using
// messages.
fn game_over_system(
game_rules: Res<GameRules>,
game_state: Res<GameState>,
mut app_exit_writer: MessageWriter<AppExit>,
) {
if let Some(ref player) = game_state.winning_player {
println!("{player} won the game!");
app_exit_writer.write(AppExit::Success);
} else if game_state.current_round == game_rules.max_rounds {
println!("Ran out of rounds. Nobody wins!");
app_exit_writer.write(AppExit::Success);
}
}
// This is a "startup" system that runs exactly once when the app starts up. Startup systems are
// generally used to create the initial "state" of our game. The only thing that distinguishes a
// "startup" system from a "normal" system is how it is registered:
// Startup: app.add_systems(Startup, startup_system)
// Normal: app.add_systems(Update, normal_system)
fn startup_system(mut commands: Commands, mut game_state: ResMut<GameState>) {
// Create our game rules resource
commands.insert_resource(GameRules {
max_rounds: 10,
winning_score: 4,
max_players: 4,
});
// Add some players to our world. Players start with a score of 0 ... we want our game to be
// fair!
commands.spawn_batch(vec![
(
Player {
name: "Alice".to_string(),
},
Score { value: 0 },
PlayerStreak::None,
),
(
Player {
name: "Bob".to_string(),
},
Score { value: 0 },
PlayerStreak::None,
),
]);
// set the total players to "2"
game_state.total_players = 2;
}
// This system uses a command buffer to (potentially) add a new player to our game on each
// iteration. Normal systems cannot safely access the World instance directly because they run in
// parallel. Our World contains all of our components, so mutating arbitrary parts of it in parallel
// is not thread safe. Command buffers give us the ability to queue up changes to our World without
// directly accessing it
fn new_player_system(
mut commands: Commands,
game_rules: Res<GameRules>,
mut game_state: ResMut<GameState>,
) {
// Randomly add a new player
let add_new_player = random::<bool>();
if add_new_player && game_state.total_players < game_rules.max_players {
game_state.total_players += 1;
commands.spawn((
Player {
name: format!("Player {}", game_state.total_players),
},
Score { value: 0 },
PlayerStreak::None,
));
println!("Player {} joined the game!", game_state.total_players);
}
}
// If you really need full, immediate read/write access to the world or resources, you can use an
// "exclusive system".
// WARNING: These will block all parallel execution of other systems until they finish, so they
// should generally be avoided if you want to maximize parallelism.
fn exclusive_player_system(world: &mut World) {
// this does the same thing as "new_player_system"
let total_players = world.resource_mut::<GameState>().total_players;
let should_add_player = {
let game_rules = world.resource::<GameRules>();
let add_new_player = random::<bool>();
add_new_player && total_players < game_rules.max_players
};
// Randomly add a new player
if should_add_player {
println!("Player {} has joined the game!", total_players + 1);
world.spawn((
Player {
name: format!("Player {}", total_players + 1),
},
Score { value: 0 },
PlayerStreak::None,
));
let mut game_state = world.resource_mut::<GameState>();
game_state.total_players += 1;
}
}
// Sometimes systems need to be stateful. Bevy's ECS provides the `Local` system parameter
// for this case. A `Local<T>` refers to a value of type `T` that is owned by the system.
// This value is automatically initialized using `T`'s `FromWorld`* implementation upon the system's initialization.
// In this system's `Local` (`counter`), `T` is `u32`.
// Therefore, on the first turn, `counter` has a value of 0.
//
// *: `FromWorld` is a trait which creates a value using the contents of the `World`.
// For any type which is `Default`, like `u32` in this example, `FromWorld` creates the default value.
fn print_at_end_round(mut counter: Local<u32>) {
*counter += 1;
println!("In set 'Last' for the {}th time", *counter);
// Print an empty line between rounds
println!();
}
/// A group of related system sets, used for controlling the order of systems. Systems can be
/// added to any number of sets.
#[derive(SystemSet, Debug, Hash, PartialEq, Eq, Clone)]
enum MySystems {
BeforeRound,
Round,
AfterRound,
}
// Our Bevy app's entry point
fn main() {
// Bevy apps are created using the builder pattern. We use the builder to add systems,
// resources, and plugins to our app
App::new()
// Resources that implement the Default or FromWorld trait can be added like this:
.init_resource::<GameState>()
// Plugins are just a grouped set of app builder calls (just like we're doing here).
// We could easily turn our game into a plugin, but you can check out the plugin example for
// that :) The plugin below runs our app's "system schedule" once every 5 seconds.
.add_plugins(ScheduleRunnerPlugin::run_loop(Duration::from_secs(5)))
// `Startup` systems run exactly once BEFORE all other systems. These are generally used for
// app initialization code (ex: adding entities and resources)
.add_systems(Startup, startup_system)
// `Update` systems run once every update. These are generally used for "real-time app logic"
.add_systems(Update, print_message_system)
// SYSTEM EXECUTION ORDER
//
// Each system belongs to a `Schedule`, which controls the execution strategy and broad order
// of the systems within each tick. The `Startup` schedule holds
// startup systems, which are run a single time before `Update` runs. `Update` runs once per app update,
// which is generally one "frame" or one "tick".
//
// By default, all systems in a `Schedule` run in parallel, except when they require mutable access to a
// piece of data. This is efficient, but sometimes order matters.
// For example, we want our "game over" system to execute after all other systems to ensure
// we don't accidentally run the game for an extra round.
//
// You can force an explicit ordering between systems using the `.before` or `.after` methods.
// Systems will not be scheduled until all of the systems that they have an "ordering dependency" on have
// completed.
// There are other schedules, such as `Last` which runs at the very end of each run.
.add_systems(Last, print_at_end_round)
// We can also create new system sets, and order them relative to other system sets.
// Here is what our games execution order will look like:
// "before_round": new_player_system, new_round_system
// "round": print_message_system, score_system
// "after_round": score_check_system, game_over_system
.configure_sets(
Update,
// chain() will ensure sets run in the order they are listed
(
MySystems::BeforeRound,
MySystems::Round,
MySystems::AfterRound,
)
.chain(),
)
// The add_systems function is powerful. You can define complex system configurations with ease!
.add_systems(
Update,
(
// These `BeforeRound` systems will run before `Round` systems, thanks to the chained set configuration
(
// You can also chain systems! new_round_system will run first, followed by new_player_system
(new_round_system, new_player_system).chain(),
exclusive_player_system,
)
// All of the systems in the tuple above will be added to this set
.in_set(MySystems::BeforeRound),
// This `Round` system will run after the `BeforeRound` systems thanks to the chained set configuration
score_system.in_set(MySystems::Round),
// These `AfterRound` systems will run after the `Round` systems thanks to the chained set configuration
(
score_check_system,
// In addition to chain(), you can also use `before(system)` and `after(system)`. This also works
// with sets!
game_over_system.after(score_check_system),
)
.in_set(MySystems::AfterRound),
),
)
// This call to run() starts the app we just built!
.run();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/system_piping.rs | examples/ecs/system_piping.rs | //! Illustrates how to make a single system from multiple functions running in sequence,
//! passing the output of the first into the input of the next.
use bevy::prelude::*;
use std::num::ParseIntError;
use bevy::log::{debug, error, info, Level, LogPlugin};
fn main() {
App::new()
.insert_resource(Message("42".to_string()))
.insert_resource(OptionalWarning(Err("Got to rusty?".to_string())))
.add_plugins(LogPlugin {
level: Level::TRACE,
filter: "".to_string(),
..default()
})
.add_systems(
Update,
(
parse_message_system.pipe(handler_system),
data_pipe_system.map(|out| info!("{out}")),
parse_message_system.map(|out| debug!("{out:?}")),
warning_pipe_system.map(|out| {
if let Err(err) = out {
error!("{err}");
}
}),
parse_error_message_system.map(|out| {
if let Err(err) = out {
error!("{err}");
}
}),
parse_message_system.map(drop),
),
)
.run();
}
#[derive(Resource, Deref)]
struct Message(String);
#[derive(Resource, Deref)]
struct OptionalWarning(Result<(), String>);
// This system produces a Result<usize> output by trying to parse the Message resource.
fn parse_message_system(message: Res<Message>) -> Result<usize, ParseIntError> {
message.parse::<usize>()
}
// This system produces a Result<()> output by trying to parse the Message resource.
fn parse_error_message_system(message: Res<Message>) -> Result<(), ParseIntError> {
message.parse::<usize>()?;
Ok(())
}
// This system takes a Result<usize> input and either prints the parsed value or the error message
// Try changing the Message resource to something that isn't an integer. You should see the error
// message printed.
fn handler_system(In(result): In<Result<usize, ParseIntError>>) {
match result {
Ok(value) => println!("parsed message: {value}"),
Err(err) => println!("encountered an error: {err:?}"),
}
}
// This system produces a String output by trying to clone the String from the Message resource.
fn data_pipe_system(message: Res<Message>) -> String {
message.0.clone()
}
// This system produces a Result<String> output by trying to extract a String from the
// OptionalWarning resource. Try changing the OptionalWarning resource to None. You should
// not see the warning message printed.
fn warning_pipe_system(message: Res<OptionalWarning>) -> Result<(), String> {
message.0.clone()
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/fixed_timestep.rs | examples/ecs/fixed_timestep.rs | //! Shows how to create systems that run every fixed timestep, rather than every tick.
use bevy::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// this system will run once every update (it should match your screen's refresh rate)
.add_systems(Update, frame_update)
// add our system to the fixed timestep schedule
.add_systems(FixedUpdate, fixed_update)
// configure our fixed timestep schedule to run twice a second
.insert_resource(Time::<Fixed>::from_seconds(0.5))
.run();
}
fn frame_update(mut last_time: Local<f32>, time: Res<Time>) {
// Default `Time` is `Time<Virtual>` here
info!(
"time since last frame_update: {}",
time.elapsed_secs() - *last_time
);
*last_time = time.elapsed_secs();
}
fn fixed_update(mut last_time: Local<f32>, time: Res<Time>, fixed_time: Res<Time<Fixed>>) {
// Default `Time`is `Time<Fixed>` here
info!(
"time since last fixed_update: {}\n",
time.elapsed_secs() - *last_time
);
info!("fixed timestep: {}\n", time.delta_secs());
// If we want to see the overstep, we need to access `Time<Fixed>` specifically
info!(
"time accrued toward next fixed_update: {}\n",
fixed_time.overstep().as_secs_f32()
);
*last_time = time.elapsed_secs();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/hotpatching_systems.rs | examples/ecs/hotpatching_systems.rs | //! This example demonstrates how to hot patch systems.
//!
//! It needs to be run with the dioxus CLI:
//! ```sh
//! dx serve --hot-patch --example hotpatching_systems --features hotpatching
//! ```
//!
//! All systems are automatically hot patchable.
//!
//! You can change the text in the `update_text` system, or the color in the
//! `on_click` system, and those changes will be hotpatched into the running
//! application.
//!
//! It's also possible to make any function hot patchable by wrapping it with
//! `bevy::dev_tools::hotpatch::call`.
use std::time::Duration;
use bevy::{color::palettes, prelude::*};
fn main() {
let (sender, receiver) = crossbeam_channel::unbounded::<()>();
// This function is here to demonstrate how to make something hot patchable outside of a system
// It uses a thread for simplicity but could be an async task, an asset loader, ...
start_thread(receiver);
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(TaskSender(sender))
.add_systems(Startup, setup)
.add_systems(Update, update_text)
.run();
}
fn update_text(mut text: Single<&mut Text>) {
// Anything in the body of a system can be changed.
// Changes to this string should be immediately visible in the example.
text.0 = "before".to_string();
}
fn on_click(
_click: On<Pointer<Click>>,
mut color: Single<&mut TextColor>,
task_sender: Res<TaskSender>,
) {
// Observers are also hot patchable.
// If you change this color and click on the text in the example, it will have the new color.
color.0 = palettes::tailwind::RED_600.into();
let _ = task_sender.0.send(());
}
#[derive(Resource)]
struct TaskSender(crossbeam_channel::Sender<()>);
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
commands
.spawn((
Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
flex_direction: FlexDirection::Column,
..default()
},
children![(
Text::default(),
TextFont {
font_size: 100.0,
..default()
},
)],
))
.observe(on_click);
}
fn start_thread(receiver: crossbeam_channel::Receiver<()>) {
std::thread::spawn(move || {
while receiver.recv().is_ok() {
let start = bevy::platform::time::Instant::now();
// You can also make any part outside of a system hot patchable by wrapping it
// In this part, only the duration is hot patchable:
let duration = bevy::app::hotpatch::call(|| Duration::from_secs(2));
std::thread::sleep(duration);
info!("done after {:?}", start.elapsed());
}
});
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/error_handling.rs | examples/ecs/error_handling.rs | //! Showcases how fallible systems and observers can make use of Rust's powerful result handling
//! syntax.
use bevy::ecs::{error::warn, world::DeferredWorld};
use bevy::math::sampling::UniformMeshSampler;
use bevy::prelude::*;
use rand::distr::Distribution;
use rand::SeedableRng;
use rand_chacha::ChaCha8Rng;
fn main() {
let mut app = App::new();
// By default, fallible systems that return an error will panic.
//
// We can change this by setting a custom error handler, which applies to the entire app
// (you can also set it for specific `World`s).
// Here we are using one of the built-in error handlers.
// Bevy provides built-in handlers for `panic`, `error`, `warn`, `info`,
// `debug`, `trace` and `ignore`.
app.set_error_handler(warn);
app.add_plugins(DefaultPlugins);
#[cfg(feature = "mesh_picking")]
app.add_plugins(MeshPickingPlugin);
// Fallible systems can be used the same way as regular systems. The only difference is they
// return a `Result<(), BevyError>` instead of a `()` (unit) type. Bevy will handle both
// types of systems the same way, except for the error handling.
app.add_systems(Startup, setup);
// Commands can also return `Result`s, which are automatically handled by the global error handler
// if not explicitly handled by the user.
app.add_systems(Startup, failing_commands);
// Individual systems can also be handled by piping the output result:
app.add_systems(
PostStartup,
failing_system.pipe(|result: In<Result>| {
let _ = result.0.inspect_err(|err| info!("captured error: {err}"));
}),
);
// Fallible observers are also supported.
app.add_observer(fallible_observer);
// If we run the app, we'll see the following output at startup:
//
// WARN Encountered an error in system `fallible_systems::failing_system`: Resource not initialized
// ERROR fallible_systems::failing_system failed: Resource not initialized
// INFO captured error: Resource not initialized
app.run();
}
/// An example of a system that calls several fallible functions with the question mark operator.
///
/// See: <https://doc.rust-lang.org/reference/expressions/operator-expr.html#the-question-mark-operator>
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) -> Result {
let mut seeded_rng = ChaCha8Rng::seed_from_u64(19878367467712);
// Make a plane for establishing space.
commands.spawn((
Mesh3d(meshes.add(Plane3d::default().mesh().size(12.0, 12.0))),
MeshMaterial3d(materials.add(Color::srgb(0.3, 0.5, 0.3))),
Transform::from_xyz(0.0, -2.5, 0.0),
));
// Spawn a light:
commands.spawn((
PointLight {
shadows_enabled: true,
..default()
},
Transform::from_xyz(4.0, 8.0, 4.0),
));
// Spawn a camera:
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-2.0, 3.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
));
// Create a new sphere mesh:
let mut sphere_mesh = Sphere::new(1.0).mesh().ico(7)?;
sphere_mesh.generate_tangents()?;
// Spawn the mesh into the scene:
let mut sphere = commands.spawn((
Mesh3d(meshes.add(sphere_mesh.clone())),
MeshMaterial3d(materials.add(StandardMaterial::default())),
Transform::from_xyz(-1.0, 1.0, 0.0),
));
// Generate random sample points:
let triangles = sphere_mesh.triangles()?;
let distribution = UniformMeshSampler::try_new(triangles)?;
// Setup sample points:
let point_mesh = meshes.add(Sphere::new(0.01).mesh().ico(3)?);
let point_material = materials.add(StandardMaterial {
base_color: Srgba::RED.into(),
emissive: LinearRgba::rgb(1.0, 0.0, 0.0),
..default()
});
// Add sample points as children of the sphere:
for point in distribution.sample_iter(&mut seeded_rng).take(10000) {
sphere.with_child((
Mesh3d(point_mesh.clone()),
MeshMaterial3d(point_material.clone()),
Transform::from_translation(point),
));
}
// Indicate the system completed successfully:
Ok(())
}
// Observer systems can also return a `Result`.
fn fallible_observer(
pointer_move: On<Pointer<Move>>,
mut world: DeferredWorld,
mut step: Local<f32>,
) -> Result {
let mut transform = world
.get_mut::<Transform>(pointer_move.entity)
.ok_or("No transform found.")?;
*step = if transform.translation.x > 3. {
-0.1
} else if transform.translation.x < -3. || *step == 0. {
0.1
} else {
*step
};
transform.translation.x += *step;
Ok(())
}
#[derive(Resource)]
struct UninitializedResource;
fn failing_system(world: &mut World) -> Result {
world
// `get_resource` returns an `Option<T>`, so we use `ok_or` to convert it to a `Result` on
// which we can call `?` to propagate the error.
.get_resource::<UninitializedResource>()
// We can provide a `str` here because `BevyError` implements `From<&str>`.
.ok_or("Resource not initialized")?;
Ok(())
}
fn failing_commands(mut commands: Commands) {
commands
// This entity doesn't exist!
.entity(Entity::from_raw_u32(12345678).unwrap())
// Normally, this failed command would panic,
// but since we've set the global error handler to `warn`
// it will log a warning instead.
.insert(Transform::default());
// The error handlers for commands can be set individually as well,
// by using the queue_handled method.
commands.queue_handled(
|world: &mut World| -> Result {
world
.get_resource::<UninitializedResource>()
.ok_or("Resource not initialized when accessed in a command")?;
Ok(())
},
|error, context| {
error!("{error}, {context}");
},
);
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/message.rs | examples/ecs/message.rs | //! This example shows how to send, mutate, and receive, messages. It also demonstrates
//! how to control system ordering so that messages are processed in a specific order.
//! It does this by simulating a damage over time effect that you might find in a game.
use bevy::prelude::*;
// In order to send or receive messages first you must define them
// This message should be sent when something attempts to deal damage to another entity.
#[derive(Message, Debug)]
struct DealDamage {
pub amount: i32,
}
// This message should be sent when an entity receives damage.
#[derive(Message, Debug, Default)]
struct DamageReceived;
// This message should be sent when an entity blocks damage with armor.
#[derive(Message, Debug, Default)]
struct ArmorBlockedDamage;
// This resource represents a timer used to determine when to deal damage
// By default it repeats once per second
#[derive(Resource, Deref, DerefMut)]
struct DamageTimer(pub Timer);
impl Default for DamageTimer {
fn default() -> Self {
DamageTimer(Timer::from_seconds(1.0, TimerMode::Repeating))
}
}
// Next we define systems that send, mutate, and receive messages
// This system reads 'DamageTimer', updates it, then sends a 'DealDamage' message
// if the timer has finished.
//
// Messages are sent using an 'MessageWriter<T>' by calling 'write' or 'write_default'.
// The 'write_default' method will send the message with the default value if the message
// has a 'Default' implementation.
fn deal_damage_over_time(
time: Res<Time>,
mut state: ResMut<DamageTimer>,
mut deal_damage_writer: MessageWriter<DealDamage>,
) {
if state.tick(time.delta()).is_finished() {
// Messages can be sent with 'write' and constructed just like any other object.
deal_damage_writer.write(DealDamage { amount: 10 });
}
}
// This system mutates the 'DealDamage' messages to apply some armor value
// It also sends an 'ArmorBlockedDamage' message if the value of 'DealDamage' is zero
//
// Messages are mutated using an 'MessageMutator<T>' by calling 'read'. This returns an iterator
// over all the &mut T that this system has not read yet. Note, you can have multiple
// 'MessageReader', 'MessageWriter', and 'MessageMutator' in a given system, as long as the types (T) are different.
fn apply_armor_to_damage(
mut dmg_messages: MessageMutator<DealDamage>,
mut armor_messages: MessageWriter<ArmorBlockedDamage>,
) {
for message in dmg_messages.read() {
message.amount -= 1;
if message.amount <= 0 {
// Zero-sized messages can also be sent with 'send'
armor_messages.write(ArmorBlockedDamage);
}
}
}
// This system reads 'DealDamage' messages and sends 'DamageReceived' if the amount is non-zero
//
// Messages are read using an 'MessageReader<T>' by calling 'read'. This returns an iterator over all the &T
// that this system has not read yet, and must be 'mut' in order to track which messages have been read.
// Again, note you can have multiple 'MessageReader', 'MessageWriter', and 'MessageMutator' in a given system,
// as long as the types (T) are different.
fn apply_damage_to_health(
mut deal_damage_reader: MessageReader<DealDamage>,
mut damaged_received_writer: MessageWriter<DamageReceived>,
) {
for deal_damage in deal_damage_reader.read() {
info!("Applying {} damage", deal_damage.amount);
if deal_damage.amount > 0 {
// Messages with a 'Default' implementation can be written with 'write_default'
damaged_received_writer.write_default();
}
}
}
// Finally these two systems read 'DamageReceived' messages.
//
// The first system will play a sound.
// The second system will spawn a particle effect.
//
// As before, messages are read using an 'MessageReader' by calling 'read'. This returns an iterator over all the &T
// that this system has not read yet.
fn play_damage_received_sound(mut damage_received_reader: MessageReader<DamageReceived>) {
for _ in damage_received_reader.read() {
info!("Playing a sound.");
}
}
// Note that both systems receive the same 'DamageReceived' messages. Any number of systems can
// receive the same message type.
fn play_damage_received_particle_effect(mut damage_received_reader: MessageReader<DamageReceived>) {
for _ in damage_received_reader.read() {
info!("Playing particle effect.");
}
}
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// Messages must be added to the app before they can be used
// using the 'add_message' method
.add_message::<DealDamage>()
.add_message::<ArmorBlockedDamage>()
.add_message::<DamageReceived>()
.init_resource::<DamageTimer>()
// As always we must add our systems to the apps schedule.
// Here we add our systems to the schedule using 'chain()' so that they run in order
// This ensures that 'apply_armor_to_damage' runs before 'apply_damage_to_health'
// It also ensures that 'MessageWriters' are used before the associated 'MessageReaders'
.add_systems(
Update,
(
deal_damage_over_time,
apply_armor_to_damage,
apply_damage_to_health,
)
.chain(),
)
// These two systems are not guaranteed to run in order, nor are they guaranteed to run
// after the above chain. They may even run in parallel with each other.
// This means they may have a one frame delay in processing messages compared to the above chain
// In some instances this is fine. In other cases it can be an issue. See the docs for more information
.add_systems(
Update,
(
play_damage_received_sound,
play_damage_received_particle_effect,
),
)
.run();
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/startup_system.rs | examples/ecs/startup_system.rs | //! Demonstrates a startup system (one that runs once when the app starts up).
use bevy::prelude::*;
fn main() {
App::new()
.add_systems(Startup, startup_system)
.add_systems(Update, normal_system)
.run();
}
/// Startup systems are run exactly once when the app starts up.
/// They run right before "normal" systems run.
fn startup_system() {
println!("startup system ran first");
}
fn normal_system() {
println!("normal system ran second");
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/nondeterministic_system_order.rs | examples/ecs/nondeterministic_system_order.rs | //! By default, Bevy systems run in parallel with each other.
//! Unless the order is explicitly specified, their relative order is nondeterministic.
//!
//! In many cases, this doesn't matter and is in fact desirable!
//! Consider two systems, one which writes to resource A, and the other which writes to resource B.
//! By allowing their order to be arbitrary, we can evaluate them greedily, based on the data that is free.
//! Because their data accesses are **compatible**, there is no **observable** difference created based on the order they are run.
//!
//! But if instead we have two systems mutating the same data, or one reading it and the other mutating,
//! then the actual observed value will vary based on the nondeterministic order of evaluation.
//! These observable conflicts are called **system execution order ambiguities**.
//!
//! This example demonstrates how you might detect and resolve (or silence) these ambiguities.
use bevy::{
ecs::schedule::{LogLevel, ScheduleBuildSettings},
prelude::*,
};
fn main() {
App::new()
// We can modify the reporting strategy for system execution order ambiguities on a per-schedule basis.
// You must do this for each schedule you want to inspect; child schedules executed within an inspected
// schedule do not inherit this modification.
.edit_schedule(Update, |schedule| {
schedule.set_build_settings(ScheduleBuildSettings {
ambiguity_detection: LogLevel::Warn,
..default()
});
})
.init_resource::<A>()
.init_resource::<B>()
.add_systems(
Update,
(
// This pair of systems has an ambiguous order,
// as their data access conflicts, and there's no order between them.
reads_a,
writes_a,
// This pair of systems has conflicting data access,
// but it's resolved with an explicit ordering:
// the .after relationship here means that we will always double after adding.
adds_one_to_b,
doubles_b.after(adds_one_to_b),
// This system isn't ambiguous with adds_one_to_b,
// due to the transitive ordering created by our constraints:
// if A is before B is before C, then A must be before C as well.
reads_b.after(doubles_b),
// This system will conflict with all of our writing systems
// but we've silenced its ambiguity with adds_one_to_b.
// This should only be done in the case of clear false positives:
// leave a comment in your code justifying the decision!
reads_a_and_b.ambiguous_with(adds_one_to_b),
),
)
// Be mindful, internal ambiguities are reported too!
// If there are any ambiguities due solely to DefaultPlugins,
// or between DefaultPlugins and any of your third party plugins,
// please file a bug with the repo responsible!
// Only *you* can prevent nondeterministic bugs due to greedy parallelism.
.add_plugins(DefaultPlugins)
.run();
}
#[derive(Resource, Debug, Default)]
struct A(usize);
#[derive(Resource, Debug, Default)]
struct B(usize);
// Data access is determined solely on the basis of the types of the system's parameters
// Every implementation of the `SystemParam` and `WorldQuery` traits must declare which data is used
// and whether or not it is mutably accessed.
fn reads_a(_a: Res<A>) {}
fn writes_a(mut a: ResMut<A>) {
a.0 += 1;
}
fn adds_one_to_b(mut b: ResMut<B>) {
b.0 = b.0.saturating_add(1);
}
fn doubles_b(mut b: ResMut<B>) {
// This will overflow pretty rapidly otherwise
b.0 = b.0.saturating_mul(2);
}
fn reads_b(b: Res<B>) {
// This invariant is always true,
// because we've fixed the system order so doubling always occurs after adding.
assert!((b.0.is_multiple_of(2)) || (b.0 == usize::MAX));
}
fn reads_a_and_b(a: Res<A>, b: Res<B>) {
// Only display the first few steps to avoid burying the ambiguities in the console
if b.0 < 10 {
info!("{}, {}", a.0, b.0);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/fallible_params.rs | examples/ecs/fallible_params.rs | //! This example demonstrates how fallible parameters can prevent their systems
//! from running if their acquiry conditions aren't met.
//!
//! Fallible system parameters include:
//! - [`Res<R>`], [`ResMut<R>`] - Resource has to exist, and the [`World::default_error_handler`] will be called if it doesn't.
//! - [`Single<D, F>`] - There must be exactly one matching entity, but the system will be silently skipped otherwise.
//! - [`Option<Single<D, F>>`] - There must be zero or one matching entity. The system will be silently skipped if there are more.
//! - [`Populated<D, F>`] - There must be at least one matching entity, but the system will be silently skipped otherwise.
//!
//! Other system parameters, such as [`Query`], will never fail validation: returning a query with no matching entities is valid.
//!
//! The result of failed system parameter validation is determined by the [`SystemParamValidationError`] returned
//! by [`SystemParam::validate_param`] for each system parameter.
//! Each system will pass if all of its parameters are valid, or else return [`SystemParamValidationError`] for the first failing parameter.
//!
//! To learn more about setting the fallback behavior for [`SystemParamValidationError`] failures,
//! please see the `error_handling.rs` example.
//!
//! [`SystemParamValidationError`]: bevy::ecs::system::SystemParamValidationError
//! [`SystemParam::validate_param`]: bevy::ecs::system::SystemParam::validate_param
use bevy::ecs::error::warn;
use bevy::prelude::*;
use rand::Rng;
fn main() {
println!();
println!("Press 'A' to add enemy ships and 'R' to remove them.");
println!("Player ship will wait for enemy ships and track one if it exists,");
println!("but will stop tracking if there are more than one.");
println!();
App::new()
// By default, if a parameter fail to be fetched,
// `World::get_default_error_handler` will be used to handle the error,
// which by default is set to panic.
.set_error_handler(warn)
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, (user_input, move_targets, track_targets).chain())
// This system will always fail validation, because we never create an entity with both `Player` and `Enemy` components.
.add_systems(Update, do_nothing_fail_validation)
.run();
}
/// Enemy component stores data for movement in a circle.
#[derive(Component, Default)]
struct Enemy {
origin: Vec2,
radius: f32,
rotation: f32,
rotation_speed: f32,
}
/// Player component stores data for going after enemies.
#[derive(Component, Default)]
struct Player {
speed: f32,
rotation_speed: f32,
min_follow_radius: f32,
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Spawn 2D camera.
commands.spawn(Camera2d);
// Spawn player.
let texture = asset_server.load("textures/simplespace/ship_C.png");
commands.spawn((
Player {
speed: 100.0,
rotation_speed: 2.0,
min_follow_radius: 50.0,
},
Sprite {
image: texture,
color: bevy::color::palettes::tailwind::BLUE_800.into(),
..Default::default()
},
Transform::from_translation(Vec3::ZERO),
));
}
/// System that reads user input.
/// If user presses 'A' we spawn a new random enemy.
/// If user presses 'R' we remove a random enemy (if any exist).
fn user_input(
mut commands: Commands,
enemies: Query<Entity, With<Enemy>>,
keyboard_input: Res<ButtonInput<KeyCode>>,
asset_server: Res<AssetServer>,
) {
let mut rng = rand::rng();
if keyboard_input.just_pressed(KeyCode::KeyA) {
let texture = asset_server.load("textures/simplespace/enemy_A.png");
commands.spawn((
Enemy {
origin: Vec2::new(
rng.random_range(-200.0..200.0),
rng.random_range(-200.0..200.0),
),
radius: rng.random_range(50.0..150.0),
rotation: rng.random_range(0.0..std::f32::consts::TAU),
rotation_speed: rng.random_range(0.5..1.5),
},
Sprite {
image: texture,
color: bevy::color::palettes::tailwind::RED_800.into(),
..default()
},
Transform::from_translation(Vec3::ZERO),
));
}
if keyboard_input.just_pressed(KeyCode::KeyR)
&& let Some(entity) = enemies.iter().next()
{
commands.entity(entity).despawn();
}
}
// System that moves the enemies in a circle.
// Only runs if there are enemies, due to the `Populated` parameter.
fn move_targets(mut enemies: Populated<(&mut Transform, &mut Enemy)>, time: Res<Time>) {
for (mut transform, mut target) in &mut *enemies {
target.rotation += target.rotation_speed * time.delta_secs();
transform.rotation = Quat::from_rotation_z(target.rotation);
let offset = transform.right() * target.radius;
transform.translation = target.origin.extend(0.0) + offset;
}
}
/// System that moves the player, causing them to track a single enemy.
/// If there is exactly one, player will track it.
/// Otherwise, the player will search for enemies.
fn track_targets(
// `Single` ensures the system runs ONLY when exactly one matching entity exists.
mut player: Single<(&mut Transform, &Player)>,
// `Option<Single>` never prevents the system from running, but will be `None` if there is not exactly one matching entity.
enemy: Option<Single<&Transform, (With<Enemy>, Without<Player>)>>,
time: Res<Time>,
) {
let (player_transform, player) = &mut *player;
if let Some(enemy_transform) = enemy {
// Enemy found, rotate and move towards it.
let delta = enemy_transform.translation - player_transform.translation;
let distance = delta.length();
let front = delta / distance;
let up = Vec3::Z;
let side = front.cross(up);
player_transform.rotation = Quat::from_mat3(&Mat3::from_cols(side, front, up));
let max_step = distance - player.min_follow_radius;
if 0.0 < max_step {
let velocity = (player.speed * time.delta_secs()).min(max_step);
player_transform.translation += front * velocity;
}
} else {
// 0 or multiple enemies found, keep searching.
player_transform.rotate_axis(Dir3::Z, player.rotation_speed * time.delta_secs());
}
}
/// This system always fails param validation, because we never
/// create an entity with both [`Player`] and [`Enemy`] components.
fn do_nothing_fail_validation(_: Single<(), (With<Player>, With<Enemy>)>) {}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
bevyengine/bevy | https://github.com/bevyengine/bevy/blob/51a6fedb06a022ab5d39e099413caa882e1b022d/examples/ecs/removal_detection.rs | examples/ecs/removal_detection.rs | //! This example shows how you can know when a [`Component`] has been removed, so you can react to it.
//!
//! When a [`Component`] is removed from an [`Entity`], all [`Observer`] with an [`Remove`] trigger for
//! that [`Component`] will be notified. These observers will be called immediately after the
//! [`Component`] is removed. For more info on observers, see the
//! [observers example](https://github.com/bevyengine/bevy/blob/main/examples/ecs/observers.rs).
//!
//! Advanced users may also consider using a lifecycle hook
//! instead of an observer, as it incurs less overhead for a case like this.
//! See the [component hooks example](https://github.com/bevyengine/bevy/blob/main/examples/ecs/component_hooks.rs).
use bevy::prelude::*;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
// This system will remove a component after two seconds.
.add_systems(Update, remove_component)
// This observer will react to the removal of the component.
.add_observer(react_on_removal)
.run();
}
/// This `struct` is just used for convenience in this example. This is the [`Component`] we'll be
/// giving to the `Entity` so we have a [`Component`] to remove in `remove_component()`.
#[derive(Component)]
struct MyComponent;
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
commands.spawn((
Sprite::from_image(asset_server.load("branding/icon.png")),
// Add the `Component`.
MyComponent,
));
}
fn remove_component(
time: Res<Time>,
mut commands: Commands,
query: Query<Entity, With<MyComponent>>,
) {
// After two seconds have passed the `Component` is removed.
if time.elapsed_secs() > 2.0
&& let Some(entity) = query.iter().next()
{
commands.entity(entity).remove::<MyComponent>();
}
}
fn react_on_removal(remove: On<Remove, MyComponent>, mut query: Query<&mut Sprite>) {
// The `Remove` event was automatically triggered for the `Entity` that had its `MyComponent` removed.
if let Ok(mut sprite) = query.get_mut(remove.entity) {
sprite.color = Color::srgb(0.5, 1., 1.);
}
}
| rust | Apache-2.0 | 51a6fedb06a022ab5d39e099413caa882e1b022d | 2026-01-04T15:31:59.438636Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/tests/src/tests.rs | tests/src/tests.rs | //! Typst's test runner.
mod args;
mod collect;
mod custom;
mod logger;
mod output;
mod pdftags;
mod run;
mod world;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use std::time::Duration;
use clap::Parser;
use parking_lot::{Mutex, RwLock};
use rayon::iter::{ParallelBridge, ParallelIterator};
use rustc_hash::FxHashMap;
use crate::args::{CliArguments, Command};
use crate::collect::Test;
use crate::logger::{Logger, TestResult};
/// The parsed command line arguments.
static ARGS: LazyLock<CliArguments> = LazyLock::new(CliArguments::parse);
/// The directory where the test suite is located.
const SUITE_PATH: &str = "tests/suite";
/// The directory where the full test results are stored.
const STORE_PATH: &str = "tests/store";
/// The directory where syntax trees are stored.
const SYNTAX_PATH: &str = "tests/store/syntax";
/// The directory where the reference output is stored.
const REF_PATH: &str = "tests/ref";
/// The file where the skipped tests are stored.
const SKIP_PATH: &str = "tests/skip.txt";
/// The maximum size of reference output that isn't marked as `large`.
const REF_LIMIT: usize = 20 * 1024;
fn main() {
setup();
match &ARGS.command {
None => test(),
Some(Command::Clean) => clean(),
Some(Command::Undangle) => undangle(),
}
}
fn setup() {
// Make all paths relative to the workspace. That's nicer for IDEs when
// clicking on paths printed to the terminal.
let workspace_dir =
Path::new(env!("CARGO_MANIFEST_DIR")).join(std::path::Component::ParentDir);
std::env::set_current_dir(workspace_dir).unwrap();
// Create the storage.
for ext in ["render", "html", "pdf", "pdftags", "svg"] {
std::fs::create_dir_all(Path::new(STORE_PATH).join(ext)).unwrap();
}
// Set up the thread pool.
if let Some(num_threads) = ARGS.num_threads {
rayon::ThreadPoolBuilder::new()
.num_threads(num_threads)
.build_global()
.unwrap();
}
}
fn test() {
let (tests, skipped) = match crate::collect::collect() {
Ok(output) => output,
Err(errors) => {
eprintln!("failed to collect tests");
for error in errors {
eprintln!("❌ {error}");
}
std::process::exit(1);
}
};
let selected = tests.len();
if ARGS.list {
for test in tests.iter() {
println!("{test}");
}
eprintln!("{selected} selected, {skipped} skipped");
return;
} else if selected == 0 {
eprintln!("no test selected");
return;
}
let parser_dirs = ARGS.parser_compare.clone().map(create_syntax_store);
let hashes: [_; 2] = std::array::from_fn(|_| RwLock::new(FxHashMap::default()));
let runner = |test: &Test| {
if let Some((live_path, ref_path)) = &parser_dirs {
run_parser_test(test, live_path, ref_path)
} else {
run::run(&hashes, test)
}
};
// Run the tests.
let logger = Mutex::new(Logger::new(selected, skipped));
std::thread::scope(|scope| {
let logger = &logger;
let (sender, receiver) = std::sync::mpsc::channel();
// Regularly refresh the logger in case we make no progress.
scope.spawn(move || {
while receiver.recv_timeout(Duration::from_millis(500)).is_err() {
if !logger.lock().refresh() {
eprintln!("tests seem to be stuck");
std::process::exit(1);
}
}
});
// Run the tests.
//
// We use `par_bridge` instead of `par_iter` because the former
// results in a stack overflow during PDF export. Probably related
// to `typst::utils::Deferred` yielding.
tests.iter().par_bridge().for_each(|test| {
logger.lock().start(test);
// This is in fact not formally unwind safe, but the code paths that
// hold a lock of the hashes are quite short and shouldn't panic.
let closure = std::panic::AssertUnwindSafe(|| runner(test));
let result = std::panic::catch_unwind(closure);
logger.lock().end(test, result);
});
sender.send(()).unwrap();
});
run::update_hash_refs::<output::Pdf>(&hashes);
run::update_hash_refs::<output::Svg>(&hashes);
let passed = logger.into_inner().finish();
if !passed {
std::process::exit(1);
}
}
fn clean() {
std::fs::remove_dir_all(STORE_PATH).unwrap();
}
fn undangle() {
match crate::collect::collect() {
Ok(_) => eprintln!("no danging reference output"),
Err(errors) => {
for error in errors {
if error.message == "dangling reference output" {
std::fs::remove_file(&error.pos.path).unwrap();
eprintln!("✅ deleted {}", error.pos.path.display());
}
}
}
}
}
fn create_syntax_store(ref_path: Option<PathBuf>) -> (&'static Path, Option<PathBuf>) {
if ref_path.as_ref().is_some_and(|p| !p.exists()) {
eprintln!("syntax reference path doesn't exist");
std::process::exit(1);
}
let live_path = Path::new(SYNTAX_PATH);
std::fs::remove_dir_all(live_path).ok();
std::fs::create_dir_all(live_path).unwrap();
(live_path, ref_path)
}
fn run_parser_test(
test: &Test,
live_path: &Path,
ref_path: &Option<PathBuf>,
) -> TestResult {
let mut result = TestResult {
errors: String::new(),
infos: String::new(),
mismatched_output: false,
};
let syntax_file = live_path.join(format!("{}.syntax", test.name));
let tree = format!("{:#?}\n", test.source.root());
std::fs::write(syntax_file, &tree).unwrap();
let Some(ref_path) = ref_path else { return result };
let ref_file = ref_path.join(format!("{}.syntax", test.name));
match std::fs::read_to_string(&ref_file) {
Ok(ref_tree) => {
if tree != ref_tree {
result.errors = "differs".to_string();
}
}
Err(_) => {
result.errors = format!("missing reference: {}", ref_file.display());
}
}
result
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/tests/src/pdftags.rs | tests/src/pdftags.rs | use std::collections::HashMap;
use std::fmt::Write;
use std::sync::{Arc, LazyLock};
use ecow::eco_format;
use hayro_syntax::content::ops::TypedInstruction;
use hayro_syntax::object::dict::keys;
use hayro_syntax::object::{Array, Dict, Name, Object, Stream};
use hayro_syntax::object::{Number, ObjRef};
use indexmap::IndexMap;
use roxmltree::{Document, Node};
use typst::diag::{StrResult, bail};
/// The context used while formatting the PDF tag tree.
struct Formatter<'a> {
pages: &'a IndexMap<ObjRef, PageContent<'a>>,
buf: String,
indent: usize,
/// Whether the last character written was a newline and an indent should
/// be applied to the next line. This isn't done directly because the
/// indent might be changed before writing any other content.
pending_indent: bool,
/// A string that is used to pad the following content, if there is any
/// on the same line. If a newline is written, discard this padding so there
/// isn't any trailing whitespace.
maybe_space: Option<&'static str>,
}
/// The marked content sequences in a PDF page.
struct PageContent<'a> {
idx: usize,
marked_content: HashMap<i64, MarkedContent<'a>>,
}
/// The properties of a marked content sequence.
struct MarkedContent<'a> {
props: Dict<'a>,
}
impl<'a> Formatter<'a> {
/// Create a new formatter.
pub fn new(pages: &'a IndexMap<ObjRef, PageContent<'a>>) -> Self {
Self {
pages,
buf: String::new(),
indent: 0,
pending_indent: false,
maybe_space: None,
}
}
}
impl std::fmt::Write for Formatter<'_> {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
if self.pending_indent {
let indent = 2 * self.indent;
write!(&mut self.buf, "{:indent$}", "").ok();
self.pending_indent = false;
}
if let Some(space) = self.maybe_space.take()
&& !s.starts_with('\n')
{
self.buf.push_str(space);
}
let mut lines = s.lines();
if let Some(first) = lines.next() {
self.buf.push_str(first);
}
for l in lines {
let indent = 2 * self.indent;
write!(&mut self.buf, "\n{:indent$}", "").ok();
self.buf.push_str(l);
}
if s.ends_with('\n') {
self.buf.push('\n');
self.pending_indent = true;
}
Ok(())
}
}
/// Format the tag tree of a PDF document as YAML.
pub fn format(doc: &[u8]) -> StrResult<String> {
let pdf = hayro_syntax::Pdf::new(Arc::new(doc.to_vec()))
.map_err(|e| eco_format!("couldn't load PDF: {e:?}"))?;
let catalog_ref = pdf.xref().root_id();
let catalog = pdf.xref().get::<Dict>(catalog_ref).ok_or("missing catalog")?;
let pages = catalog.get::<Dict>(keys::PAGES).ok_or("missing pages")?;
let page_array = pages.get::<Array>(keys::KIDS).ok_or("missing page kids")?;
let page_refs = page_array
.raw_iter()
.map(|o| o.as_obj_ref().ok_or("expected page obj ref"));
let page_contents = pdf
.pages()
.iter()
.enumerate()
.zip(page_refs)
.map(|((idx, page), page_ref)| {
let page_ref = page_ref?;
let marked_content = page
.typed_operations()
.filter_map(|op| match op {
TypedInstruction::MarkedContentPointWithProperties(mc) => {
let props = mc.1.into_dict()?;
let mcid = props.get(keys::MCID)?;
Some((mcid, MarkedContent { props }))
}
TypedInstruction::BeginMarkedContentWithProperties(mc) => {
let props = mc.1.into_dict()?;
let mcid = props.get(keys::MCID)?;
Some((mcid, MarkedContent { props }))
}
_ => None,
})
.collect();
Ok((page_ref, PageContent { idx, marked_content }))
})
.collect::<StrResult<_>>()?;
let struct_tree: Dict =
catalog.get(keys::STRUCT_TREE_ROOT).ok_or("struct tree root")?;
let kids = struct_tree.get::<Array>(keys::K).ok_or("struct tree kids")?;
let document = kids.iter::<Dict>().next().ok_or("document tag")?;
let kids = document.get::<Array>(keys::K).ok_or("document kids")?;
let mut f = Formatter::new(&page_contents);
if let Some(stream) = catalog.get::<Stream>(keys::METADATA) {
format_xmp_metadata(&mut f, stream)
.map_err(|e| eco_format!("error formatting XMP metadata: {e}"))?;
}
format_tag_children(&mut f, &document, &kids)?;
Ok(f.buf)
}
/// Format the XMP metadata of a PDF document.
fn format_xmp_metadata(f: &mut Formatter, stream: Stream) -> StrResult<()> {
fn child<'a, 'input>(
node: &Node<'a, 'input>,
name: &str,
) -> Option<Node<'a, 'input>> {
node.children().find(|c| c.tag_name().name() == name)
}
let bytes = stream
.decoded()
.map_err(|e| eco_format!("failed to decode stream: {e:?}"))?;
let xml_str =
std::str::from_utf8(&bytes).map_err(|e| eco_format!("invalid UTF-8: {e}"))?;
let xmp = Document::parse(xml_str).map_err(|e| eco_format!("invalid XML: {e}"))?;
let xmpmeta = xmp.root_element();
let rdf = child(&xmpmeta, "RDF").ok_or("missing rdf:RDF")?;
let description = child(&rdf, "Description").ok_or("missing rdf:Description")?;
if let Some(dc_lang) = child(&description, "language") {
let bag = child(&dc_lang, "Bag").ok_or("missing rdf:Bag")?;
let item = bag.first_element_child().ok_or("missing rdf:li")?;
assert_eq!(item.tag_name().name(), "li");
let lang = item.text().ok_or("missing text")?;
// Only write language if it deviates from the default.
if lang != "en" {
writeln!(f, "lang: {lang:?}").ok();
}
}
if !f.buf.is_empty() {
writeln!(f, "---").ok();
}
Ok(())
}
/// Format a PDF structure element (tag).
fn format_tag(f: &mut Formatter, tag: &Dict) -> StrResult<()> {
assert_type(tag, keys::STRUCT_ELEM)?;
let ty = tag.get::<Name>(keys::S).ok_or("missing structure type")?;
let ty = ty.as_str();
writeln!(f, "- Tag: {ty}").ok();
f.indent += 1;
format_tag_attrs(f, tag).map_err(|e| eco_format!("{ty}: {e}"))?;
let Some(kids) = tag.get::<Array>(keys::K) else { bail!("{ty}: missing kids array") };
if kids.raw_iter().next().is_some() {
writeln!(f, "/K:").ok();
f.indent += 1;
format_tag_children(f, tag, &kids).map_err(|e| eco_format!("{ty}: {e}"))?;
f.indent -= 1;
}
f.indent -= 1;
Ok(())
}
/// Format either a child structure element (tag), a marked-content sequence or
/// an annotation.
fn format_tag_children(f: &mut Formatter, tag: &Dict, kids: &Array) -> StrResult<()> {
for kid in kids.iter::<Object>() {
match kid {
Object::Number(mcid) => {
let page_ref = tag
.get_ref(keys::PG)
.ok_or("missing page ref on structure element")?;
format_marked_content(f, page_ref, mcid.as_i64())
.map_err(|e| eco_format!("error formatting marked-content: {e}"))?;
}
Object::Dict(dict) => {
let ty = dict.get::<Name>(keys::TYPE).ok_or("missing object type")?;
match &*ty {
b"MCR" => {
let mcid = dict.get(keys::MCID).ok_or("missing content id")?;
let page_ref = dict
.get_ref(keys::PG)
.ok_or("missing page ref on marked-content reference")?;
format_marked_content(f, page_ref, mcid).map_err(|e| {
eco_format!("error formatting marked-content: {e}")
})?;
}
keys::OBJR => {
let annot = dict
.get::<Dict>(keys::OBJ)
.ok_or("missing referenced obj")?;
let page_ref = dict
.get_ref(keys::PG)
.ok_or("missing page ref on object reference")?;
format_annotation(f, page_ref, &annot).map_err(|e| {
eco_format!("error formatting annotation: {e}")
})?;
}
_ => format_tag(f, &dict)?,
}
}
_ => bail!("unexpected object {kid:?}"),
}
}
Ok(())
}
/// Format a marked content sequence.
fn format_marked_content(
f: &mut Formatter,
page_ref: ObjRef,
mcid: i64,
) -> StrResult<()> {
let page = &f.pages[&page_ref];
let page_idx = page.idx;
let mc = &page.marked_content[&mcid];
writeln!(f, "- Content: page={page_idx} mcid={mcid}").ok();
f.indent += 1;
if let Some(val) = mc.props.get::<Object>(keys::LANG) {
format_attr(f, "Lang", val, format_str)?;
}
if let Some(val) = mc.props.get::<Object>(keys::ALT) {
format_attr(f, "Alt", val, format_str)?;
}
if let Some(val) = mc.props.get::<Object>(keys::E) {
format_attr(f, "Expanded", val, format_str)?;
}
if let Some(val) = mc.props.get::<Object>(keys::ACTUAL_TEXT) {
format_attr(f, "ActualText", val, format_str)?;
}
f.indent -= 1;
Ok(())
}
/// Format a link annotation.
fn format_annotation(f: &mut Formatter, page_ref: ObjRef, annot: &Dict) -> StrResult<()> {
assert_type(annot, keys::ANNOT)?;
let subtype = annot.get::<Name>(keys::SUBTYPE).ok_or("missing subtype")?;
let subtype = subtype.as_str();
let page = &f.pages[&page_ref];
let page_idx = page.idx;
writeln!(f, "- Annotation: page={page_idx} subtype={subtype}").ok();
f.indent += 1;
if let Some(val) = annot.get::<Object>(keys::CONTENTS) {
format_attr(f, "Contents", val, format_str)?;
}
if let Some(action) = annot.get::<Dict>(keys::A) {
assert_type(&action, b"Action")?;
if let Some(val) = action.get(keys::URI) {
format_attr(f, "URI", val, format_str)?;
}
}
f.indent -= 1;
Ok(())
}
/// Format the attributes of a structure element (tag).
fn format_tag_attrs(f: &mut Formatter, tag: &Dict) -> StrResult<()> {
if let Some(val) = tag.get::<Object>(keys::ID) {
format_attr(f, "Id", val, format_byte_str)?;
}
if let Some(val) = tag.get::<Object>(keys::LANG) {
format_attr(f, "Lang", val, format_str)?;
}
if let Some(val) = tag.get::<Object>(keys::ALT) {
format_attr(f, "Alt", val, format_str)?;
}
if let Some(val) = tag.get::<Object>(keys::E) {
format_attr(f, "Expanded", val, format_str)?;
}
if let Some(val) = tag.get::<Object>(keys::ACTUAL_TEXT) {
format_attr(f, "ActualText", val, format_str)?;
}
if let Some(val) = tag.get::<Object>(keys::T) {
format_attr(f, "T", val, format_str)?;
}
if let Some(attrs_array) = tag.get::<Array>(keys::A) {
for attrs in attrs_array.iter::<Dict>() {
// Attributes are stored in a hash map. Sort the keys by a
// predefined order so the formatted tag tree is deterministic.
let attribute_map = &*ATTRIBUTE_MAP;
let mut indices = attrs
.keys()
.filter(|name| {
// Ignore the attribute owner
name.as_str() != "O"
})
.map(|name| {
let Some(idx) = attribute_map.get(name.as_str()) else {
bail!("unhandled key `{}`", name.as_str())
};
Ok(*idx)
})
.collect::<StrResult<Vec<_>>>()?;
indices.sort();
for idx in indices {
let (name, fmt) = ATTRIBUTES[idx];
let val = attrs.get::<Object>(name.as_bytes()).unwrap();
format_attr(f, name, val, fmt)?;
}
}
}
Ok(())
}
type FmtValFn = fn(f: &mut Formatter, val: &Object) -> Result<(), ()>;
/// The sorted list of PDF structure element attributes and how to format them.
const ATTRIBUTES: [(&str, FmtValFn); 36] = [
// List
("ListNumbering", format_name),
// Table
("Summary", format_str),
("Scope", format_name),
("Headers", |f, val| format_array(f, val, format_byte_str)),
("RowSpan", format_int),
("ColSpan", format_int),
// Layout
("Placement", format_name),
("WritingMode", format_name),
("BBox", |f, val| format_array(f, val, format_float)),
("Width", format_float),
("Height", format_float),
("BackgroundColor", format_color),
("BorderColor", |f, val| format_sides(f, val, format_color)),
("BorderStyle", |f, val| format_sides(f, val, format_name)),
("BorderThickness", |f, val| format_sides(f, val, format_float)),
("Padding", |f, val| format_sides(f, val, format_float)),
("Color", format_color),
("SpaceBefore", format_float),
("SpaceAfter", format_float),
("StartIndent", format_float),
("EndIndent", format_float),
("TextIndent", format_float),
("TextAlign", format_name),
("BlockAlign", format_name),
("InlineAlign", format_name),
("TBorderStyle", |f, val| format_sides(f, val, format_name)),
("TPadding", |f, val| format_sides(f, val, format_float)),
("BaselineShift", format_float),
("LineHeight", |f, val| format_one_of(f, val, [format_float, format_name])),
("TextDecorationColor", format_color),
("TextDecorationThickness", format_float),
("TextDecorationType", format_name),
("GlyphOrientationVertical", |f, val| {
format_one_of(f, val, [format_int, format_name])
}),
("ColumnCount", format_int),
("ColumnGap", |f, val| format_array(f, val, format_float)),
("ColumnWidths", |f, val| format_array(f, val, format_float)),
];
/// A lookup table from an attribute name to its index in the attribute array.
static ATTRIBUTE_MAP: LazyLock<HashMap<&str, usize>> =
LazyLock::new(|| ATTRIBUTES.into_iter().map(|(name, _)| name).zip(0..).collect());
fn format_attr(
f: &mut Formatter,
name: &str,
val: Object,
fmt: FmtValFn,
) -> StrResult<()> {
write!(f, "/{name}:").ok();
f.maybe_space = Some(" ");
f.indent += 1;
if fmt(f, &val).is_err() {
bail!("couldn't format `{name}`: `{val:?}`");
}
f.indent -= 1;
writeln!(f).ok();
Ok(())
}
fn format_int(f: &mut Formatter, val: &Object) -> Result<(), ()> {
let Object::Number(val) = val else { return Err(()) };
write!(f, "{}", val.as_i64()).ok();
Ok(())
}
fn format_float(f: &mut Formatter, val: &Object) -> Result<(), ()> {
let Object::Number(val) = val else { return Err(()) };
write!(f, "{:7.3}", val.as_f64()).ok();
Ok(())
}
fn format_name(f: &mut Formatter, val: &Object) -> Result<(), ()> {
let Object::Name(val) = val else { return Err(()) };
f.write_str(val.as_str()).ok();
Ok(())
}
fn format_str(f: &mut Formatter, val: &Object) -> Result<(), ()> {
const UTF_16_BE_BOM: [u8; 2] = *b"\xFE\xFF";
let Object::String(val) = val else { return Err(()) };
let bytes = val.get();
if let Some(data) = bytes.strip_prefix(&UTF_16_BE_BOM) {
let code_units = data.chunks(2).map(|c| u16::from_be_bytes([c[0], c[1]]));
let str = std::char::decode_utf16(code_units)
.collect::<Result<String, _>>()
.unwrap();
write!(f, "{str:?}").ok();
} else {
let str = std::str::from_utf8(&bytes).unwrap();
write!(f, "{str:?}").ok();
}
Ok(())
}
fn format_byte_str(f: &mut Formatter, val: &Object) -> Result<(), ()> {
let Object::String(val) = val else { return Err(()) };
let bytes = val.get();
if bytes.iter().all(
|b| matches!(b, b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z' | b' ' | b'-' | b'_'),
) {
let str = std::str::from_utf8(&bytes).unwrap();
write!(f, "{str:?}").ok();
} else {
write!(f, "0x").ok();
for b in bytes.iter() {
write!(f, "{b:02x}").ok();
}
}
Ok(())
}
fn format_color(f: &mut Formatter, val: &Object) -> Result<(), ()> {
let Object::Array(array) = val else { return Err(()) };
if array.raw_iter().count() != 3 {
return Err(());
};
let mut iter = array.iter::<Number>();
let [r, g, b] = std::array::from_fn(|_| {
let n = iter.next().unwrap().as_f64();
(255.0 * n).round() as u8
});
write!(f, "#{r:02x}{g:02x}{b:02x}").ok();
Ok(())
}
fn format_array(f: &mut Formatter, val: &Object, fmt: FmtValFn) -> Result<(), ()> {
match val {
Object::Array(array) => {
f.indent += 1;
write!(f, "[").ok();
for (i, val) in array.iter().enumerate() {
if i != 0 {
write!(f, ", ").ok();
}
fmt(f, &val)?;
}
write!(f, "]").ok();
f.indent -= 1;
Ok(())
}
val => fmt(f, val),
}
}
fn format_sides(f: &mut Formatter, val: &Object, fmt: FmtValFn) -> Result<(), ()> {
match val {
Object::Array(array) if array.raw_iter().count() == 4 => {
let mut iter = array.iter::<Object>();
let values: [_; 4] = std::array::from_fn(|_| iter.next().unwrap());
#[rustfmt::skip]
const NAMES: [(&str, &str); 4] = [
("before", " "),
("after", " "),
("start", " "),
("end", " "),
];
for ((name, space), val) in NAMES.iter().zip(values) {
write!(f, "\n{name}:").ok();
f.maybe_space = Some(space);
f.indent += 1;
fmt(f, &val)?;
f.indent -= 1;
}
Ok(())
}
val => fmt(f, val),
}
}
fn format_one_of<const N: usize>(
f: &mut Formatter,
val: &Object,
fmt: [FmtValFn; N],
) -> Result<(), ()> {
for fmt in fmt {
if fmt(f, val).is_ok() {
return Ok(());
}
}
Err(())
}
#[track_caller]
fn assert_type(obj: &Dict, expected: &[u8]) -> StrResult<()> {
let ty = obj.get::<Name>(keys::TYPE).ok_or("missing object type")?;
if &*ty != expected {
let found = ty.as_str();
let expected = std::str::from_utf8(expected).unwrap();
bail!("expected object type `{expected}` found `{found}`")
}
Ok(())
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/tests/src/world.rs | tests/src/world.rs | use std::borrow::Cow;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::OnceLock;
use comemo::Tracked;
use parking_lot::Mutex;
use rustc_hash::FxHashMap;
use typst::diag::{At, FileError, FileResult, SourceResult, StrResult, bail};
use typst::engine::Engine;
use typst::foundations::{
Array, Bytes, Context, Datetime, IntoValue, NoneValue, Repr, Smart, Value, func,
};
use typst::layout::{Abs, Margin, PageElem};
use typst::model::{Numbering, NumberingPattern};
use typst::syntax::{FileId, Source, Span};
use typst::text::{Font, FontBook, TextElem, TextSize};
use typst::utils::{LazyHash, singleton};
use typst::visualize::Color;
use typst::{Feature, Library, LibraryExt, World};
use typst_syntax::Lines;
/// A world that provides access to the tests environment.
#[derive(Clone)]
pub struct TestWorld {
main: Source,
base: &'static TestBase,
}
impl TestWorld {
/// Create a new world for a single test.
///
/// This is cheap because the shared base for all test runs is lazily
/// initialized just once.
pub fn new(source: Source) -> Self {
Self {
main: source,
base: singleton!(TestBase, TestBase::default()),
}
}
}
impl World for TestWorld {
fn library(&self) -> &LazyHash<Library> {
&self.base.library
}
fn book(&self) -> &LazyHash<FontBook> {
&self.base.book
}
fn main(&self) -> FileId {
self.main.id()
}
fn source(&self, id: FileId) -> FileResult<Source> {
if id == self.main.id() {
Ok(self.main.clone())
} else {
self.slot(id, FileSlot::source)
}
}
fn file(&self, id: FileId) -> FileResult<Bytes> {
self.slot(id, FileSlot::file)
}
fn font(&self, index: usize) -> Option<Font> {
self.base.fonts.get(index).cloned()
}
fn today(&self, _: Option<i64>) -> Option<Datetime> {
Some(Datetime::from_ymd(1970, 1, 1).unwrap())
}
}
impl TestWorld {
/// Access the canonical slot for the given file id.
fn slot<F, T>(&self, id: FileId, f: F) -> T
where
F: FnOnce(&mut FileSlot) -> T,
{
let mut map = self.base.slots.lock();
f(map.entry(id).or_insert_with(|| FileSlot::new(id)))
}
/// Lookup line metadata for a file by id.
#[track_caller]
pub(crate) fn lookup(&self, id: FileId) -> Lines<String> {
self.slot(id, |slot| {
if let Some(source) = slot.source.get() {
let source = source.as_ref().expect("file is not valid");
source.lines().clone()
} else if let Some(bytes) = slot.file.get() {
let bytes = bytes.as_ref().expect("file is not valid");
Lines::try_from(bytes).expect("file is not valid UTF-8")
} else {
panic!("file id does not point to any source file");
}
})
}
}
/// Shared foundation of all test worlds.
struct TestBase {
library: LazyHash<Library>,
book: LazyHash<FontBook>,
fonts: Vec<Font>,
slots: Mutex<FxHashMap<FileId, FileSlot>>,
}
impl Default for TestBase {
fn default() -> Self {
let fonts: Vec<_> = typst_assets::fonts()
.chain(typst_dev_assets::fonts())
.flat_map(|data| Font::iter(Bytes::new(data)))
.collect();
Self {
library: LazyHash::new(library()),
book: LazyHash::new(FontBook::from_fonts(&fonts)),
fonts,
slots: Mutex::new(FxHashMap::default()),
}
}
}
/// Holds the processed data for a file ID.
#[derive(Clone)]
struct FileSlot {
id: FileId,
source: OnceLock<FileResult<Source>>,
file: OnceLock<FileResult<Bytes>>,
}
impl FileSlot {
/// Create a new file slot.
fn new(id: FileId) -> Self {
Self { id, file: OnceLock::new(), source: OnceLock::new() }
}
/// Retrieve the source for this file.
fn source(&mut self) -> FileResult<Source> {
self.source
.get_or_init(|| {
let buf = read(&system_path(self.id)?)?;
let text = String::from_utf8(buf.into_owned())?;
Ok(Source::new(self.id, text))
})
.clone()
}
/// Retrieve the file's bytes.
fn file(&mut self) -> FileResult<Bytes> {
self.file
.get_or_init(|| {
read(&system_path(self.id)?).map(|cow| match cow {
Cow::Owned(buf) => Bytes::new(buf),
Cow::Borrowed(buf) => Bytes::new(buf),
})
})
.clone()
}
}
/// The file system path for a file ID.
pub(crate) fn system_path(id: FileId) -> FileResult<PathBuf> {
let root: PathBuf = match id.package() {
Some(spec) => format!("tests/packages/{}-{}", spec.name, spec.version).into(),
None => PathBuf::new(),
};
id.vpath().resolve(&root).ok_or(FileError::AccessDenied)
}
/// Read a file.
pub(crate) fn read(path: &Path) -> FileResult<Cow<'static, [u8]>> {
// Resolve asset.
if let Ok(suffix) = path.strip_prefix("assets/") {
return typst_dev_assets::get(&suffix.to_string_lossy())
.map(Cow::Borrowed)
.ok_or_else(|| FileError::NotFound(path.into()));
}
let f = |e| FileError::from_io(e, path);
if fs::metadata(path).map_err(f)?.is_dir() {
Err(FileError::IsDirectory)
} else {
fs::read(path).map(Cow::Owned).map_err(f)
}
}
/// The extended standard library for testing.
fn library() -> Library {
// Set page width to 120pt with 10pt margins, so that the inner page is
// exactly 100pt wide. Page height is unbounded and font size is 10pt so
// that it multiplies to nice round numbers.
let mut lib = Library::builder()
.with_features([Feature::Html, Feature::A11yExtras].into_iter().collect())
.build();
// Hook up helpers into the global scope.
lib.global.scope_mut().define_func::<test>();
lib.global.scope_mut().define_func::<test_repr>();
lib.global.scope_mut().define_func::<print>();
lib.global.scope_mut().define_func::<lines>();
lib.global
.scope_mut()
.define("conifer", Color::from_u8(0x9f, 0xEB, 0x52, 0xFF));
lib.global
.scope_mut()
.define("forest", Color::from_u8(0x43, 0xA1, 0x27, 0xFF));
// Hook up default styles.
lib.styles.set(PageElem::width, Smart::Custom(Abs::pt(120.0).into()));
lib.styles.set(PageElem::height, Smart::Auto);
lib.styles
.set(PageElem::margin, Margin::splat(Some(Smart::Custom(Abs::pt(10.0).into()))));
lib.styles.set(TextElem::size, TextSize(Abs::pt(10.0).into()));
lib
}
#[func]
fn test(lhs: Value, rhs: Value) -> StrResult<NoneValue> {
if lhs != rhs {
bail!("Assertion failed: {} != {}", lhs.repr(), rhs.repr());
}
Ok(NoneValue)
}
#[func]
fn test_repr(lhs: Value, rhs: Value) -> StrResult<NoneValue> {
if lhs.repr() != rhs.repr() {
bail!("Assertion failed: {} != {}", lhs.repr(), rhs.repr());
}
Ok(NoneValue)
}
#[func]
fn print(#[variadic] values: Vec<Value>) -> NoneValue {
let mut out = std::io::stdout().lock();
write!(out, "> ").unwrap();
for (i, value) in values.into_iter().enumerate() {
if i > 0 {
write!(out, ", ").unwrap();
}
write!(out, "{value:?}").unwrap();
}
writeln!(out).unwrap();
NoneValue
}
/// Generates `count` lines of text based on the numbering.
#[func]
fn lines(
engine: &mut Engine,
context: Tracked<Context>,
span: Span,
count: u64,
#[default(Numbering::Pattern(NumberingPattern::from_str("A").unwrap()))]
numbering: Numbering,
) -> SourceResult<Value> {
(1..=count)
.map(|n| numbering.apply(engine, context, &[n]))
.collect::<SourceResult<Array>>()?
.join(Some('\n'.into_value()), None, None)
.at(span)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/tests/src/collect.rs | tests/src/collect.rs | use std::fmt::{self, Display, Formatter};
use std::io::IsTerminal;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::LazyLock;
use bitflags::{Flags, bitflags};
use ecow::{EcoString, eco_format};
use rustc_hash::{FxHashMap, FxHashSet};
use typst::foundations::Bytes;
use typst_pdf::PdfStandard;
use typst_syntax::package::PackageVersion;
use typst_syntax::{
FileId, Lines, Source, VirtualPath, is_id_continue, is_ident, is_newline,
};
use unscanny::Scanner;
use crate::output::HashedRefs;
use crate::world::{read, system_path};
use crate::{ARGS, REF_PATH, STORE_PATH, SUITE_PATH};
/// Collects all tests from all files.
///
/// Returns:
/// - the tests and the number of skipped tests in the success case.
/// - parsing errors in the failure case.
pub fn collect() -> Result<(Vec<Test>, usize), Vec<TestParseError>> {
Collector::new().collect()
}
/// A single test.
pub struct Test {
pub pos: FilePos,
pub name: EcoString,
pub attrs: Attrs,
pub source: Source,
pub notes: Vec<Note>,
}
impl Display for Test {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
// underline path
if std::io::stdout().is_terminal() {
write!(f, "{} (\x1B[4m{}\x1B[0m)", self.name, self.pos)
} else {
write!(f, "{} ({})", self.name, self.pos)
}
}
}
/// A position in a file.
#[derive(Clone)]
pub struct FilePos {
pub path: PathBuf,
pub line: usize,
}
impl FilePos {
fn new(path: impl Into<PathBuf>, line: usize) -> Self {
Self { path: path.into(), line }
}
}
impl Display for FilePos {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.line > 0 {
write!(f, "{}:{}", self.path.display(), self.line)
} else {
write!(f, "{}", self.path.display())
}
}
}
bitflags! {
/// Just used for parsing attribute flags.
#[derive(Copy, Clone)]
struct AttrFlags: u16 {
const LARGE = 1 << 0;
}
}
/// The parsed and evaluated test attributes specified in the test header.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
pub struct Attrs {
pub large: bool,
pub pdf_standard: Option<PdfStandard>,
/// The test stages that are either directly specified or are implied by a
/// test attribute. If not specified otherwise by the `--stages` flag a
/// reference output will be generated.
pub stages: TestStages,
}
impl Attrs {
/// Whether the reference output should be compared and saved.
pub fn should_check_ref(&self, output: TestOutput) -> bool {
// TODO: Enable PDF and SVG once we have a diffing tool for hashed references.
ARGS.should_run(self.stages & output.into())
&& output != TestOutput::Pdf
&& output != TestOutput::Svg
}
}
pub trait TestStage: Into<TestStages> + Display + Copy {}
bitflags! {
/// The stages a test in ran through. This combines both compilation targets
/// and output formats.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
pub struct TestStages: u8 {
const PAGED = 1 << 0;
const RENDER = 1 << 1;
const PDF = 1 << 2;
const PDFTAGS = 1 << 3;
const SVG = 1 << 4;
const HTML = 1 << 5;
}
}
macro_rules! union {
($union:expr) => {
$union
};
($a:expr, $b:expr $(,$flag:expr)*$(,)?) => {
union!($a.union($b) $(,$flag)*)
};
}
impl TestStages {
/// All stages that require the paged target.
pub const PAGED_STAGES: Self = union!(
TestStages::PAGED,
TestStages::RENDER,
TestStages::PDF,
TestStages::PDFTAGS,
TestStages::SVG,
);
/// All stages that require a pdf document.
pub const PDF_STAGES: Self = union!(TestStages::PDF, TestStages::PDFTAGS);
/// The union the supplied stages and their implied stages.
///
/// The `paged` target will test `render`, `pdf`, and `svg` by default.
pub fn with_implied(&self) -> TestStages {
let mut res = *self;
for flag in self.iter() {
res |= bitflags::bitflags_match!(flag, {
TestStages::PAGED => TestStages::RENDER | TestStages::PDF | TestStages::SVG,
TestStages::RENDER => TestStages::empty(),
TestStages::PDF => TestStages::empty(),
TestStages::PDFTAGS => TestStages::empty(),
TestStages::SVG => TestStages::empty(),
TestStages::HTML => TestStages::empty(),
_ => unreachable!(),
});
}
res
}
}
impl Display for TestStages {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
for (i, flag) in self.iter().enumerate() {
if i != 0 {
f.write_str(", ")?;
}
bitflags::bitflags_match!(flag, {
TestStages::PAGED => Display::fmt(&TestTarget::Paged, f),
TestStages::RENDER => Display::fmt(&TestOutput::Render, f),
TestStages::PDF => Display::fmt(&TestOutput::Pdf, f),
TestStages::PDFTAGS => Display::fmt(&TestOutput::Pdftags, f),
TestStages::SVG => Display::fmt(&TestOutput::Svg, f),
TestStages::HTML => Display::fmt(&TestTarget::Html, f),
_ => unreachable!(),
})?;
}
Ok(())
}
}
/// A compilation target, analog to [`typst::Target`].
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(u8)]
pub enum TestTarget {
Paged = TestStages::PAGED.bits(),
Html = TestStages::HTML.bits(),
}
impl TestStage for TestTarget {}
impl From<TestTarget> for TestStages {
fn from(value: TestTarget) -> Self {
TestStages::from_bits(value as u8).unwrap()
}
}
impl Display for TestTarget {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(match self {
TestTarget::Paged => "paged",
TestTarget::Html => "html",
})
}
}
/// A test output format.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[repr(u8)]
pub enum TestOutput {
Render = TestStages::RENDER.bits(),
Pdf = TestStages::PDF.bits(),
Pdftags = TestStages::PDFTAGS.bits(),
Svg = TestStages::SVG.bits(),
Html = TestStages::HTML.bits(),
}
impl TestOutput {
pub const ALL: [Self; 5] =
[Self::Render, Self::Pdf, Self::Pdftags, Self::Svg, Self::Html];
fn from_sub_dir(dir: &str) -> Option<Self> {
Self::ALL.into_iter().find(|o| o.sub_dir() == dir)
}
/// The sub directory inside the [`REF_PATH`] and [`STORE_PATH`].
pub const fn sub_dir(&self) -> &'static str {
match self {
Self::Render => "render",
Self::Pdf => "pdf",
Self::Pdftags => "pdftags",
Self::Svg => "svg",
Self::Html => "html",
}
}
/// The file extension used for live outputs and file references.
pub const fn extension(&self) -> &'static str {
match self {
Self::Render => "png",
Self::Pdf => "pdf",
Self::Pdftags => "yml",
Self::Svg => "svg",
Self::Html => "html",
}
}
/// The path at which the live output will be stored for inspection.
pub fn live_path(&self, name: &str) -> PathBuf {
let dir = self.sub_dir();
let ext = self.extension();
PathBuf::from(format!("{STORE_PATH}/{dir}/{name}.{ext}"))
}
/// The path at which file references will be saved.
pub fn file_ref_path(&self, name: &str) -> PathBuf {
let dir = self.sub_dir();
let ext = self.extension();
PathBuf::from(format!("{REF_PATH}/{dir}/{name}.{ext}"))
}
/// The path at which hashed references will be saved.
pub fn hashed_ref_path(self, source_path: &Path) -> PathBuf {
let sub_dir = self.sub_dir();
let sub_path = source_path.strip_prefix(SUITE_PATH).unwrap();
let trimmed_path = sub_path.to_str().unwrap().strip_suffix(".typ");
let file_name = trimmed_path.unwrap().replace("/", "-");
PathBuf::from(format!("{REF_PATH}/{sub_dir}/{file_name}.txt"))
}
/// The output kind.
fn kind(&self) -> TestOutputKind {
match self {
TestOutput::Render | TestOutput::Pdftags | TestOutput::Html => {
TestOutputKind::File
}
TestOutput::Pdf | TestOutput::Svg => TestOutputKind::Hash,
}
}
}
impl TestStage for TestOutput {}
impl From<TestOutput> for TestStages {
fn from(value: TestOutput) -> Self {
TestStages::from_bits(value as u8).unwrap()
}
}
impl Display for TestOutput {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(self.sub_dir())
}
}
/// Whether the output format produces hashed or file references.
enum TestOutputKind {
Hash,
File,
}
/// The size of a file.
pub struct FileSize(pub usize);
impl Display for FileSize {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{:.2} KiB", (self.0 as f64) / 1024.0)
}
}
/// An annotation like `// Error: 2-6 message` in a test.
pub struct Note {
pub pos: FilePos,
pub kind: NoteKind,
/// The file [`Self::range`] belongs to.
pub file: FileId,
pub range: Option<Range<usize>>,
pub message: String,
}
/// A kind of annotation in a test.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum NoteKind {
Error,
Warning,
Hint,
}
impl FromStr for NoteKind {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"Error" => Self::Error,
"Warning" => Self::Warning,
"Hint" => Self::Hint,
_ => return Err(()),
})
}
}
impl Display for NoteKind {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(match self {
Self::Error => "Error",
Self::Warning => "Warning",
Self::Hint => "Hint",
})
}
}
/// Collects all tests from all files.
struct Collector {
tests: Vec<Test>,
errors: Vec<TestParseError>,
seen: FxHashMap<EcoString, (FilePos, Attrs)>,
skipped: usize,
}
impl Collector {
/// Creates a new test collector.
fn new() -> Self {
Self {
tests: vec![],
errors: vec![],
seen: FxHashMap::default(),
skipped: 0,
}
}
/// Collects tests from all files.
fn collect(mut self) -> Result<(Vec<Test>, usize), Vec<TestParseError>> {
self.walk_files();
self.walk_references();
if self.errors.is_empty() {
Ok((self.tests, self.skipped))
} else {
Err(self.errors)
}
}
/// Walks through all test files and collects the tests.
fn walk_files(&mut self) {
for entry in walkdir::WalkDir::new(crate::SUITE_PATH).sort_by_file_name() {
let entry = entry.unwrap();
let path = entry.path();
if path.extension().is_none_or(|ext| ext != "typ") {
continue;
}
let text = std::fs::read_to_string(path).unwrap();
if text.starts_with("// SKIP") {
continue;
}
Parser::new(self, path, &text).parse();
}
}
/// Walks through all reference outputs and ensures that a matching test
/// exists.
fn walk_references(&mut self) {
for entry in walkdir::WalkDir::new(crate::REF_PATH).sort_by_file_name() {
let entry = entry.unwrap();
if !entry.file_type().is_file() {
continue;
}
let path = entry.path();
let sub_path = path.strip_prefix(crate::REF_PATH).unwrap();
let sub_dir = sub_path.components().next().unwrap();
let Some(output) =
TestOutput::from_sub_dir(sub_dir.as_os_str().to_str().unwrap())
else {
continue;
};
match output.kind() {
TestOutputKind::File => self.check_dangling_file_references(path, output),
TestOutputKind::Hash => {
self.check_dangling_hashed_references(path, output)
}
}
}
}
fn check_dangling_file_references(&mut self, path: &Path, output: TestOutput) {
let stem = path.file_stem().unwrap().to_string_lossy();
let name = &*stem;
let Some((pos, attrs)) = self.seen.get(name) else {
self.errors.push(TestParseError {
pos: FilePos::new(path, 0),
message: "dangling reference output".into(),
});
return;
};
if !attrs.stages.contains(output.into()) {
self.errors.push(TestParseError {
pos: FilePos::new(path, 0),
message: "dangling reference output".into(),
});
}
let len = path.metadata().unwrap().len() as usize;
if !attrs.large && len > crate::REF_LIMIT {
self.errors.push(TestParseError {
pos: pos.clone(),
message: format!(
"reference output size exceeds {}, but the test is not marked as `large`",
FileSize(crate::REF_LIMIT),
),
});
}
}
fn check_dangling_hashed_references(&mut self, path: &Path, output: TestOutput) {
let string = std::fs::read_to_string(path).unwrap_or_default();
let Ok(hashed_refs) = HashedRefs::from_str(&string) else { return };
if hashed_refs.is_empty() {
self.errors.push(TestParseError {
pos: FilePos::new(path, 0),
message: "dangling empty reference hash file".into(),
});
}
let mut right_file = 0;
let mut wrong_file = Vec::new();
for (line, name) in hashed_refs.names().enumerate() {
let Some((pos, attrs)) = self.seen.get(name) else {
self.errors.push(TestParseError {
pos: FilePos::new(path, line),
message: format!("dangling reference hash ({name})"),
});
continue;
};
if !attrs.stages.contains(output.into()) {
self.errors.push(TestParseError {
pos: FilePos::new(path, line),
message: format!("dangling reference hash ({name})"),
});
continue;
}
if output.hashed_ref_path(&pos.path) == path {
right_file += 1;
} else {
wrong_file.push((line, name));
}
}
if !wrong_file.is_empty() {
if right_file == 0 {
self.errors.push(TestParseError {
pos: FilePos::new(path, 0),
message: "dangling reference hash file".into(),
});
} else {
for (line, name) in wrong_file {
self.errors.push(TestParseError {
pos: FilePos::new(path, line),
message: format!("dangling reference hash ({name})"),
});
}
}
}
}
}
/// Parses a single test file.
struct Parser<'a> {
collector: &'a mut Collector,
path: &'a Path,
s: Scanner<'a>,
test_start_line: usize,
line: usize,
}
impl<'a> Parser<'a> {
/// Creates a new parser for a file.
fn new(collector: &'a mut Collector, path: &'a Path, source: &'a str) -> Self {
Self {
collector,
path,
s: Scanner::new(source),
test_start_line: 1,
line: 1,
}
}
/// Parses an individual file.
fn parse(&mut self) {
self.skip_preamble();
while !self.s.done() {
let mut name = EcoString::new();
let mut attrs = Attrs::default();
let mut notes = vec![];
if self.s.eat_if("---") {
self.s.eat_while(' ');
name = self.s.eat_until(char::is_whitespace).into();
self.s.eat_while(' ');
if name.is_empty() {
self.error("expected test name");
} else if !is_ident(&name) {
self.error(format!("test name `{name}` is not a valid identifier"));
} else {
attrs = self.parse_attrs();
}
} else {
self.error("expected opening ---");
}
if self.collector.seen.contains_key(&name) {
self.error(format!("duplicate test {name}"));
}
if self.s.eat_newline() {
self.line += 1;
}
let start = self.s.cursor();
self.test_start_line = self.line;
let pos = FilePos::new(self.path, self.test_start_line);
self.collector.seen.insert(name.clone(), (pos.clone(), attrs));
while !self.s.done() && !self.s.at("---") {
self.s.eat_until(is_newline);
if self.s.eat_newline() {
self.line += 1;
}
}
let text = self.s.from(start);
if !ARGS.should_run(attrs.stages)
|| !selected(&name, self.path.canonicalize().unwrap())
{
self.collector.skipped += 1;
continue;
}
let vpath = VirtualPath::new(self.path);
let source = Source::new(FileId::new(None, vpath), text.into());
self.s.jump(start);
self.line = self.test_start_line;
while !self.s.done() && !self.s.at("---") {
self.s.eat_while(' ');
if self.s.eat_if("// ") {
notes.extend(self.parse_note(&source));
}
self.s.eat_until(is_newline);
if self.s.eat_newline() {
self.line += 1;
}
}
self.collector.tests.push(Test { pos, name, source, notes, attrs });
}
}
/// Parse the test attributes inside a test header.
fn parse_attrs(&mut self) -> Attrs {
let mut stages = TestStages::empty();
let mut flags = AttrFlags::empty();
let mut pdf_standard = None;
while !self.s.eat_if("---") {
let attr_name = self.s.eat_while(is_id_continue);
let mut attr_params = None;
if self.s.eat_if('(') {
attr_params = Some(self.s.eat_until(')'));
if !self.s.eat_if(')') {
self.error("expected closing parenthesis");
}
}
if !self.s.at(' ') {
self.error("expected a space after an attribute");
}
match attr_name {
"paged" => self.set_attr(attr_name, &mut stages, TestStages::PAGED),
"pdftags" => self.set_attr(attr_name, &mut stages, TestStages::PDFTAGS),
"pdfstandard" => {
let Some(param) = attr_params.take() else {
self.error("expected parameter for `pdfstandard`");
continue;
};
pdf_standard = serde_yaml::from_str(param)
.inspect_err(|e| {
self.error(format!("unknown pdf standard `{param}`: {e}"))
})
.ok();
}
"html" => self.set_attr(attr_name, &mut stages, TestStages::HTML),
"large" => self.set_attr(attr_name, &mut flags, AttrFlags::LARGE),
found => {
self.error(format!(
"expected attribute or closing ---, found `{found}`"
));
break;
}
}
if attr_params.is_some() {
self.error("unexpected attribute parameters");
}
self.s.eat_while(' ');
}
if stages.is_empty() {
self.error("tests must specify at least one target or output");
}
Attrs {
large: flags.contains(AttrFlags::LARGE),
pdf_standard,
stages: stages.with_implied(),
}
}
/// Set an attribute flag and check for duplicates.
fn set_attr<F: Flags + Copy>(&mut self, attr: &str, flags: &mut F, flag: F) {
if flags.contains(flag) {
self.error(format!("duplicate attribute `{attr}`"));
}
flags.insert(flag);
}
/// Skips the preamble of a test.
fn skip_preamble(&mut self) {
let mut errored = false;
while !self.s.done() && !self.s.at("---") {
let line = self.s.eat_until(is_newline).trim();
if !errored && !line.is_empty() && !line.starts_with("//") {
self.error("test preamble may only contain comments and blank lines");
errored = true;
}
if self.s.eat_newline() {
self.line += 1;
}
}
}
/// Parses an annotation in a test.
fn parse_note(&mut self, source: &Source) -> Option<Note> {
let head = self.s.eat_while(is_id_continue);
if !self.s.eat_if(':') {
return None;
}
let kind: NoteKind = head.parse().ok()?;
self.s.eat_if(' ');
let mut file = None;
if self.s.eat_if('"') {
let path = self.s.eat_until(|c| is_newline(c) || c == '"');
if !self.s.eat_if('"') {
self.error("expected closing quote after file path");
return None;
}
let vpath = VirtualPath::new(path);
file = Some(FileId::new(None, vpath));
self.s.eat_if(' ');
}
let mut range = None;
if self.s.at('-') || self.s.at(char::is_numeric) {
if let Some(file) = file {
range = self.parse_range_external(file);
} else {
range = self.parse_range(source);
}
if range.is_none() {
self.error("range is malformed");
return None;
}
}
let message = self
.s
.eat_until(is_newline)
.trim()
.replace("VERSION", &eco_format!("{}", PackageVersion::compiler()))
.replace("\\n", "\n");
Some(Note {
pos: FilePos::new(self.path, self.line),
kind,
file: file.unwrap_or(source.id()),
range,
message,
})
}
/// Parse a range in an external file, optionally abbreviated as just a position
/// if the range is empty.
fn parse_range_external(&mut self, file: FileId) -> Option<Range<usize>> {
let path = match system_path(file) {
Ok(path) => path,
Err(err) => {
self.error(err.to_string());
return None;
}
};
let bytes = match read(&path) {
Ok(data) => Bytes::new(data),
Err(err) => {
self.error(err.to_string());
return None;
}
};
let start = self.parse_line_col()?;
let lines = Lines::try_from(&bytes).expect(
"errors shouldn't be annotated for files \
that aren't human readable (not valid UTF-8)",
);
let range = if self.s.eat_if('-') {
let (line, col) = start;
let start = lines.line_column_to_byte(line, col);
let (line, col) = self.parse_line_col()?;
let end = lines.line_column_to_byte(line, col);
Option::zip(start, end).map(|(a, b)| a..b)
} else {
let (line, col) = start;
lines.line_column_to_byte(line, col).map(|i| i..i)
};
if range.is_none() {
self.error("range is out of bounds");
}
range
}
/// Parses absolute `line:column` indices in an external file.
fn parse_line_col(&mut self) -> Option<(usize, usize)> {
let line = self.parse_number()?;
if !self.s.eat_if(':') {
self.error("positions in external files always require both `<line>:<col>`");
return None;
}
let col = self.parse_number()?;
if line < 0 || col < 0 {
self.error("line and column numbers must be positive");
return None;
}
Some(((line as usize).saturating_sub(1), (col as usize).saturating_sub(1)))
}
/// Parse a range, optionally abbreviated as just a position if the range
/// is empty.
fn parse_range(&mut self, source: &Source) -> Option<Range<usize>> {
let start = self.parse_position(source)?;
let end = if self.s.eat_if('-') { self.parse_position(source)? } else { start };
Some(start..end)
}
/// Parses a relative `(line:)?column` position.
fn parse_position(&mut self, source: &Source) -> Option<usize> {
let first = self.parse_number()?;
let (line_delta, column) =
if self.s.eat_if(':') { (first, self.parse_number()?) } else { (1, first) };
let text = source.text();
let line_idx_in_test = self.line - self.test_start_line;
let comments = text
.lines()
.skip(line_idx_in_test + 1)
.take_while(|line| line.trim().starts_with("//"))
.count();
let line_idx = (line_idx_in_test + comments).checked_add_signed(line_delta)?;
let column_idx = if column < 0 {
// Negative column index is from the back.
let range = source.lines().line_to_range(line_idx)?;
text[range].chars().count().saturating_add_signed(column)
} else {
usize::try_from(column).ok()?.checked_sub(1)?
};
source.lines().line_column_to_byte(line_idx, column_idx)
}
/// Parse a number.
fn parse_number(&mut self) -> Option<isize> {
let start = self.s.cursor();
self.s.eat_if('-');
self.s.eat_while(char::is_numeric);
self.s.from(start).parse().ok()
}
/// Stores a test parsing error.
fn error(&mut self, message: impl Into<String>) {
self.collector.errors.push(TestParseError {
pos: FilePos::new(self.path, self.line),
message: message.into(),
});
}
}
/// Whether a test is within the selected set to run.
fn selected(name: &str, abs: PathBuf) -> bool {
static SKIPPED: LazyLock<FxHashSet<&'static str>> = LazyLock::new(|| {
String::leak(std::fs::read_to_string(crate::SKIP_PATH).unwrap())
.lines()
.map(|line| line.trim())
.filter(|line| !line.is_empty() && !line.starts_with("//"))
.collect()
});
if SKIPPED.contains(name) {
return false;
}
let paths = &crate::ARGS.path;
if !paths.is_empty() && !paths.iter().any(|path| abs.starts_with(path)) {
return false;
}
let exact = crate::ARGS.exact;
let patterns = &crate::ARGS.pattern;
patterns.is_empty()
|| patterns.iter().any(|pattern: ®ex::Regex| {
if exact { name == pattern.as_str() } else { pattern.is_match(name) }
})
}
/// An error in a test file.
pub struct TestParseError {
pub pos: FilePos,
pub message: String,
}
impl Display for TestParseError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{} ({})", self.message, self.pos)
}
}
trait ScannerExt {
fn eat_newline(&mut self) -> bool;
}
impl ScannerExt for Scanner<'_> {
fn eat_newline(&mut self) -> bool {
let ate = self.eat_if(is_newline);
if ate && self.before().ends_with('\r') {
self.eat_if('\n');
}
ate
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/tests/src/logger.rs | tests/src/logger.rs | use std::io::{self, IsTerminal, StderrLock, Write};
use std::time::{Duration, Instant};
use crate::collect::Test;
/// The result of running a single test.
pub struct TestResult {
/// The error log for this test. If empty, the test passed.
pub errors: String,
/// The info log for this test.
pub infos: String,
/// Whether the output was mismatched.
pub mismatched_output: bool,
}
/// Receives status updates by individual test runs.
pub struct Logger<'a> {
selected: usize,
passed: usize,
failed: usize,
skipped: usize,
mismatched_output: bool,
active: Vec<&'a Test>,
last_change: Instant,
temp_lines: usize,
terminal: bool,
}
impl<'a> Logger<'a> {
/// Create a new logger.
pub fn new(selected: usize, skipped: usize) -> Self {
Self {
selected,
passed: 0,
failed: 0,
skipped,
mismatched_output: false,
active: vec![],
temp_lines: 0,
last_change: Instant::now(),
terminal: std::io::stderr().is_terminal(),
}
}
/// Register the start of a test.
pub fn start(&mut self, test: &'a Test) {
self.active.push(test);
self.last_change = Instant::now();
self.refresh();
}
/// Register a finished test.
pub fn end(&mut self, test: &'a Test, result: std::thread::Result<TestResult>) {
self.active.retain(|t| t.name != test.name);
let result = match result {
Ok(result) => result,
Err(_) => {
self.failed += 1;
self.temp_lines = 0;
self.print(move |out| {
writeln!(out, "❌ {test} panicked")?;
Ok(())
})
.unwrap();
return;
}
};
if result.errors.is_empty() {
self.passed += 1;
} else {
self.failed += 1;
}
self.mismatched_output |= result.mismatched_output;
self.last_change = Instant::now();
self.print(move |out| {
if !result.errors.is_empty() {
writeln!(out, "❌ {test}")?;
if !crate::ARGS.compact {
for line in result.errors.lines() {
writeln!(out, " {line}")?;
}
}
} else if crate::ARGS.verbose || !result.infos.is_empty() {
writeln!(out, "✅ {test}")?;
}
for line in result.infos.lines() {
writeln!(out, " {line}")?;
}
Ok(())
})
.unwrap();
}
/// Prints a summary and returns whether the test suite passed.
pub fn finish(&self) -> bool {
let Self { selected, passed, failed, skipped, .. } = *self;
eprintln!("{passed} passed, {failed} failed, {skipped} skipped");
assert_eq!(selected, passed + failed, "not all tests were executed successfully");
if self.mismatched_output {
eprintln!(" pass the --update flag to update the reference output");
}
self.failed == 0
}
/// Refresh the status. Returns whether we still seem to be making progress.
pub fn refresh(&mut self) -> bool {
self.print(|_| Ok(())).unwrap();
self.last_change.elapsed() < Duration::from_secs(10)
}
/// Refresh the status print.
fn print(
&mut self,
inner: impl FnOnce(&mut StderrLock<'_>) -> io::Result<()>,
) -> io::Result<()> {
let mut out = std::io::stderr().lock();
// Clear the status lines.
for _ in 0..self.temp_lines {
write!(out, "\x1B[1F\x1B[0J")?;
self.temp_lines = 0;
}
// Print the result of a finished test.
inner(&mut out)?;
// Print the status line.
let done = self.failed + self.passed;
if done < self.selected {
if self.last_change.elapsed() > Duration::from_secs(2) {
for test in &self.active {
writeln!(out, "⏰ {test} is taking a long time ...")?;
if self.terminal {
self.temp_lines += 1;
}
}
}
if self.terminal {
writeln!(out, "💨 {done} / {}", self.selected)?;
self.temp_lines += 1;
}
}
Ok(())
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/tests/src/args.rs | tests/src/args.rs | use std::path::PathBuf;
use std::sync::atomic::{AtomicU8, Ordering};
use clap::{Parser, Subcommand, ValueEnum};
use regex::Regex;
use crate::collect::TestStages;
/// Typst's test runner.
#[derive(Debug, Clone, Parser)]
#[command(bin_name = "cargo test --workspace --test tests --")]
#[clap(name = "typst-test", author)]
pub struct CliArguments {
/// The command to run.
#[command(subcommand)]
pub command: Option<Command>,
/// All the tests whose names match the test name pattern will be run.
#[arg(value_parser = Regex::new)]
pub pattern: Vec<Regex>,
/// Restricts test selection within the given path.
#[arg(short, long, value_parser = |s: &str| PathBuf::from(s).canonicalize())]
pub path: Vec<PathBuf>,
/// Only selects the test that matches with the test name verbatim.
#[arg(short, long)]
pub exact: bool,
/// Lists what tests will be run, without actually running them.
#[arg(long, group = "action")]
pub list: bool,
/// Updates the reference output of non-passing tests.
#[arg(short, long, group = "action")]
pub update: bool,
/// Specify which test targets/outputs to run.
///
/// This is useful to only update specific reference outputs of a test.
#[arg(long, value_delimiter = ',')]
pub stages: Vec<TestStage>,
/// The scaling factor to render the output image with.
///
/// Does not affect the comparison or the reference image.
#[arg(short, long, default_value_t = 1.0)]
pub scale: f32,
/// Displays the syntax tree before running tests.
///
/// Note: This is ignored if using '--syntax-compare'.
#[arg(long)]
pub syntax: bool,
/// Displays only one line per test, hiding details about failures.
#[arg(short, long)]
pub compact: bool,
/// Prevents the terminal from being cleared of test names.
#[arg(short, long)]
pub verbose: bool,
/// How many threads to spawn when running the tests.
#[arg(short = 'j', long)]
pub num_threads: Option<usize>,
/// Changes testing behavior for debugging the parser: With no argument,
/// outputs the concrete syntax trees of tests as files in
/// 'tests/store/syntax/'. With a directory as argument, will treat it as a
/// reference of correct syntax tree files and will print which output
/// syntax trees differ (viewing the diffs is on you).
///
/// This overrides the normal testing system. It parses, but does not run
/// the test suite.
///
/// If `cargo test` is run with `--no-default-features`, then compiling will
/// not include Typst's core crates, only typst-syntax, greatly speeding up
/// debugging when changing the parser.
///
/// You can generate a correct reference directory by running on a known
/// good commit and copying the generated outputs to a new directory.
/// `_things` may be a good location as it is in the top-level gitignore.
///
/// You can view diffs in VS Code with: `code --diff <ref_dir>/<test>.syntax
/// tests/store/syntax/<test>.syntax`
#[arg(long)]
pub parser_compare: Option<Option<PathBuf>>,
// ^ I'm not using a subcommand here because then test patterns don't parse
// how you would expect and I'm too lazy to try to fix it.
}
impl CliArguments {
/// The stages which should be run depending on the `--stages` flag.
pub fn stages(&self) -> TestStages {
static CACHED: AtomicU8 = AtomicU8::new(0xFF);
if CACHED.load(Ordering::Relaxed) == 0xFF {
let mut stages = TestStages::empty();
if self.stages.is_empty() {
stages = TestStages::all();
} else {
for &s in self.stages.iter() {
stages |= s.into();
}
stages = stages.with_implied();
};
CACHED.store(stages.bits(), Ordering::Relaxed);
}
TestStages::from_bits(CACHED.load(Ordering::Relaxed)).unwrap()
}
/// Whether the stage should be run depending on the `--stages` flag.
pub fn should_run(&self, stage: TestStages) -> bool {
self.stages().intersects(stage)
}
}
/// What to do.
#[derive(Debug, Clone, Subcommand)]
#[command()]
pub enum Command {
/// Clears the on-disk test artifact store.
Clean,
/// Deletes all dangling reference output.
Undangle,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, ValueEnum)]
pub enum TestStage {
Paged,
Render,
Pdf,
Pdftags,
Svg,
Html,
}
impl From<TestStage> for TestStages {
fn from(value: TestStage) -> Self {
match value {
TestStage::Paged => TestStages::PAGED,
TestStage::Render => TestStages::RENDER,
TestStage::Pdf => TestStages::PDF,
TestStage::Pdftags => TestStages::PDFTAGS,
TestStage::Svg => TestStages::SVG,
TestStage::Html => TestStages::HTML,
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/tests/src/run.rs | tests/src/run.rs | use std::fmt::Write;
use std::ops::Range;
use std::str::FromStr;
use std::sync::LazyLock;
use parking_lot::RwLock;
use regex::{Captures, Regex};
use rustc_hash::FxHashMap;
use typst::diag::{SourceDiagnostic, Warned};
use typst::layout::PagedDocument;
use typst::{Document, WorldExt};
use typst_html::HtmlDocument;
use typst_syntax::{FileId, Lines, VirtualPath};
use crate::collect::{FileSize, NoteKind, Test, TestStage, TestStages, TestTarget};
use crate::logger::TestResult;
use crate::output::{FileOutputType, HashOutputType, HashedRefs, OutputType};
use crate::world::{TestWorld, system_path};
use crate::{ARGS, custom, output};
type OutputHashes = FxHashMap<&'static VirtualPath, HashedRefs>;
/// Runs a single test.
///
/// Returns whether the test passed.
pub fn run(hashes: &[RwLock<OutputHashes>], test: &Test) -> TestResult {
Runner::new(hashes, test).run()
}
/// Write all hashed references that have been updated
pub fn update_hash_refs<T: HashOutputType>(hashes: &[RwLock<OutputHashes>]) {
#[allow(clippy::iter_over_hash_type)]
for (source_path, hashed_refs) in hashes[T::INDEX].write().iter_mut() {
hashed_refs.sort();
if !hashed_refs.changed {
continue;
}
let ref_path = T::OUTPUT.hashed_ref_path(source_path.as_rootless_path());
if hashed_refs.is_empty() {
std::fs::remove_file(ref_path).ok();
} else {
std::fs::write(ref_path, hashed_refs.to_string()).unwrap();
}
}
}
/// Write a line to a log sink, defaulting to the test's error log.
macro_rules! log {
(into: $sink:expr, $($tts:tt)*) => {
writeln!($sink, $($tts)*).unwrap();
};
($runner:expr, $($tts:tt)*) => {
writeln!(&mut $runner.result.errors, $($tts)*).unwrap();
};
}
/// Runs a single test.
pub struct Runner<'a> {
hashes: &'a [RwLock<OutputHashes>],
test: &'a Test,
world: TestWorld,
/// In which targets the note has been seen.
seen: Vec<TestStages>,
result: TestResult,
not_annotated: String,
}
impl<'a> Runner<'a> {
/// Create a new test runner.
fn new(hashes: &'a [RwLock<OutputHashes>], test: &'a Test) -> Self {
Self {
hashes,
test,
world: TestWorld::new(test.source.clone()),
seen: vec![TestStages::empty(); test.notes.len()],
result: TestResult {
errors: String::new(),
infos: String::new(),
mismatched_output: false,
},
not_annotated: String::new(),
}
}
/// Run the test.
fn run(mut self) -> TestResult {
if crate::ARGS.syntax {
log!(into: self.result.infos, "tree: {:#?}", self.test.source.root());
}
// Only compile paged document when the paged target is specified or
// implied. If so, run tests for all paged outputs unless excluded by
// the `--stages` flag. The test attribute still control which
// reference outputs are saved and compared though.
if ARGS.should_run(self.test.attrs.stages & TestStages::PAGED_STAGES) {
let mut doc = self.compile::<PagedDocument>(TestTarget::Paged);
if let Some(doc) = &mut doc
&& doc.info.title.is_none()
{
doc.info.title = Some(self.test.name.clone());
}
let errors = custom::check(self.test, &self.world, doc.as_ref());
if !errors.is_empty() {
log!(self, "custom check failed");
for line in errors.lines() {
log!(self, " {line}");
}
}
if ARGS.should_run(self.test.attrs.stages & TestStages::RENDER) {
self.run_file_test::<output::Render>(doc.as_ref());
}
if ARGS.should_run(self.test.attrs.stages & TestStages::PDF_STAGES) {
let pdf = self.run_hash_test::<output::Pdf>(doc.as_ref());
if ARGS.should_run(TestStages::PDFTAGS) {
self.run_file_test::<output::Pdftags>(pdf.as_ref());
}
}
if ARGS.should_run(self.test.attrs.stages & TestStages::SVG) {
self.run_hash_test::<output::Svg>(doc.as_ref());
}
}
// Only compile html document when the html target is specified.
if ARGS.should_run(self.test.attrs.stages & TestStages::HTML) {
let doc = self.compile::<HtmlDocument>(TestTarget::Html);
self.run_file_test::<output::Html>(doc.as_ref());
}
self.handle_not_emitted();
self.handle_not_annotated();
self.result
}
/// Handle errors that weren't annotated.
fn handle_not_annotated(&mut self) {
if !self.not_annotated.is_empty() {
log!(self, "not annotated");
self.result.errors.push_str(&self.not_annotated);
}
}
/// Handle notes that weren't handled before.
fn handle_not_emitted(&mut self) {
let mut first = true;
for (note, &seen) in self.test.notes.iter().zip(&self.seen) {
let mut missing_stages = TestStages::empty();
let required_stages = ARGS.stages() & self.test.attrs.stages;
// If a test stage requiring the paged target has been specified,
// require the annotated diagnostics to be present in any paged
// stage. For example if `pdftags` is specified and an error is
// emitted in the pdf stage, that is ok.
if !(required_stages & TestStages::PAGED_STAGES).is_empty()
&& (seen & TestStages::PAGED_STAGES).is_empty()
{
missing_stages |= TestStages::PAGED;
}
if !(required_stages & TestStages::HTML).is_empty()
&& (seen & TestStages::HTML).is_empty()
{
missing_stages |= TestStages::HTML;
}
if missing_stages.is_empty() {
continue;
}
let note_range = self.format_range(note.file, ¬e.range);
if first {
log!(self, "not emitted [{missing_stages}]");
first = false;
}
log!(self, " {}: {note_range} {} ({})", note.kind, note.message, note.pos,);
}
}
/// Compile a document with the specified target.
fn compile<D: Document>(&mut self, target: TestTarget) -> Option<D> {
let Warned { output, warnings } = typst::compile::<D>(&self.world);
for warning in &warnings {
self.check_diagnostic(NoteKind::Warning, warning, target);
}
if let Err(errors) = &output {
for error in errors.iter() {
self.check_diagnostic(NoteKind::Error, error, target);
}
}
output.ok()
}
/// Run test for an output format that produces a file reference.
fn run_file_test<T: FileOutputType>(
&mut self,
doc: Option<&T::Doc>,
) -> Option<T::Live> {
let output = self.run_test::<T>(doc);
if self.test.attrs.should_check_ref(T::OUTPUT) {
self.check_file_ref::<T>(&output)
}
output.map(|(_, live)| live)
}
/// Run test for an output format that produces a hashed reference.
fn run_hash_test<T: HashOutputType>(
&mut self,
doc: Option<&T::Doc>,
) -> Option<T::Live> {
let output = self.run_test::<T>(doc);
if self.test.attrs.should_check_ref(T::OUTPUT) {
self.check_hash_ref::<T>(&output)
}
output.map(|(_, live)| live)
}
/// Run test for a specific output format, and save the live output to disk.
fn run_test<'d, T: OutputType>(
&mut self,
doc: Option<&'d T::Doc>,
) -> Option<(&'d T::Doc, T::Live)> {
let live_path = T::OUTPUT.live_path(&self.test.name);
let output = doc.and_then(|doc| match T::make_live(self.test, doc) {
Ok(live) => Some((doc, live)),
Err(errors) => {
if errors.is_empty() {
log!(self, "no document, but also no errors");
}
for error in errors.iter() {
self.check_diagnostic(NoteKind::Error, error, T::OUTPUT);
}
None
}
});
let skippable = match &output {
Some((doc, live)) => T::is_skippable(doc, live).unwrap_or(true),
None => false,
};
match &output {
Some((doc, live)) if !skippable => {
// Convert and save live version.
let live_data = T::save_live(doc, live);
std::fs::write(&live_path, live_data).unwrap();
}
_ => {
// Clean live output.
std::fs::remove_file(&live_path).ok();
}
}
output
}
/// Check that the document output matches the existing file reference.
/// On mismatch, (over-)write or remove the reference if the `--update` flag
/// is provided.
fn check_file_ref<T: FileOutputType>(&mut self, output: &Option<(&T::Doc, T::Live)>) {
let live_path = T::OUTPUT.live_path(&self.test.name);
let ref_path = T::OUTPUT.file_ref_path(&self.test.name);
let old_ref_data = std::fs::read(&ref_path);
let Some((doc, live)) = output else {
if old_ref_data.is_ok() {
log!(self, "missing document");
log!(self, " ref | {}", ref_path.display());
}
return;
};
let skippable = match T::is_skippable(doc, live) {
Ok(skippable) => skippable,
Err(()) => {
log!(self, "document has zero pages");
return;
}
};
// Tests without visible output and no reference output don't need to be
// compared.
if skippable && old_ref_data.is_err() {
return;
}
// Compare against reference output if available.
// Test that is ok doesn't need to be updated.
if old_ref_data.as_ref().is_ok_and(|r| T::matches(r, live)) {
return;
}
if crate::ARGS.update {
if skippable {
std::fs::remove_file(&ref_path).unwrap();
log!(
into: self.result.infos,
"removed reference output ({})", ref_path.display()
);
} else {
let new_ref_data = T::make_ref(live);
let new_ref_data = new_ref_data.as_ref();
if !self.test.attrs.large && new_ref_data.len() > crate::REF_LIMIT {
log!(self, "reference output would exceed maximum size");
log!(self, " maximum | {}", FileSize(crate::REF_LIMIT));
log!(self, " size | {}", FileSize(new_ref_data.len()));
log!(
self,
"please try to minimize the size of the test (smaller pages, less text, etc.)"
);
log!(
self,
"if you think the test cannot be reasonably minimized, mark it as `large`"
);
return;
}
std::fs::write(&ref_path, new_ref_data).unwrap();
log!(
into: self.result.infos,
"updated reference output ({}, {})",
ref_path.display(),
FileSize(new_ref_data.len()),
);
}
} else {
self.result.mismatched_output = true;
if old_ref_data.is_ok() {
log!(self, "mismatched output");
log!(self, " live | {}", live_path.display());
log!(self, " ref | {}", ref_path.display());
} else {
log!(self, "missing reference output");
log!(self, " live | {}", live_path.display());
}
}
}
/// Check that the document output matches the existing hashed reference.
/// On mismatch, (over-)write or remove the reference if the `--update` flag
/// is provided.
fn check_hash_ref<T: HashOutputType>(&mut self, output: &Option<(&T::Doc, T::Live)>) {
let live_path = T::OUTPUT.live_path(&self.test.name);
let source_path = self.test.source.id().vpath();
let old_ref_hash =
if let Some(hashed_refs) = self.hashes[T::INDEX].read().get(source_path) {
hashed_refs.get(&self.test.name)
} else {
let ref_path = T::OUTPUT.hashed_ref_path(source_path.as_rootless_path());
let string = std::fs::read_to_string(&ref_path).unwrap_or_default();
let hashed_refs = HashedRefs::from_str(&string)
.inspect_err(|e| {
log!(self, "error parsing hashed refs: {e}");
})
.unwrap_or_default();
let mut hashes = self.hashes[T::INDEX].write();
let entry = hashes.entry(source_path).insert_entry(hashed_refs);
entry.get().get(&self.test.name)
};
let Some((doc, live)) = output else {
if old_ref_hash.is_some() {
log!(self, "missing document");
log!(self, " ref | {}", self.test.name);
}
return;
};
let skippable = match T::is_skippable(doc, live) {
Ok(skippable) => skippable,
Err(()) => {
log!(self, "document has zero pages");
return;
}
};
// Tests without visible output and no reference output don't need to be
// compared.
if skippable && old_ref_hash.is_none() {
return;
}
// Compare against reference output if available.
// Test that is ok doesn't need to be updated.
let new_ref_hash = T::make_hash(live);
if old_ref_hash.as_ref().is_some_and(|h| *h == new_ref_hash) {
return;
}
if crate::ARGS.update {
let mut hashes = self.hashes[T::INDEX].write();
let hashed_refs = hashes.get_mut(source_path).unwrap();
let ref_path = T::OUTPUT.hashed_ref_path(source_path.as_rootless_path());
if skippable {
hashed_refs.remove(&self.test.name);
log!(
into: self.result.infos,
"removed reference hash ({})", ref_path.display()
);
} else {
hashed_refs.update(self.test.name.clone(), new_ref_hash);
log!(
into: self.result.infos,
"updated reference hash ({}, {new_ref_hash})",
ref_path.display(),
);
}
} else {
self.result.mismatched_output = true;
if let Some(old_ref_hash) = old_ref_hash {
log!(self, "mismatched output");
log!(self, " live | {}", live_path.display());
log!(self, " old | {old_ref_hash}");
log!(self, " new | {new_ref_hash}");
} else {
log!(self, "missing reference output");
log!(self, " live | {}", live_path.display());
}
}
}
/// Compare a subset of notes with a given kind against diagnostics of
/// that same kind.
fn check_diagnostic(
&mut self,
kind: NoteKind,
diag: &SourceDiagnostic,
stage: impl TestStage,
) {
// TODO: remove this once HTML export is stable
if diag.message == "html export is under active development and incomplete" {
return;
}
let range = self.world.range(diag.span);
self.validate_note(kind, diag.span.id(), range, &diag.message, stage);
// Check hints.
for hint in &diag.hints {
// HACK: This hint only gets emitted in debug builds, so filter it
// out to make the test suite also pass for release builds.
if hint.v == "set `RUST_BACKTRACE` to `1` or `full` to capture a backtrace" {
continue;
}
let span = hint.span.or(diag.span);
let range = self.world.range(span);
self.validate_note(NoteKind::Hint, span.id(), range, &hint.v, stage);
}
}
/// Try to find a matching note for the given `kind`, `range`, and
/// `message`.
///
/// - If found, marks it as seen and returns it.
/// - If none was found, emits a "Not annotated" error and returns nothing.
fn validate_note(
&mut self,
kind: NoteKind,
file: Option<FileId>,
range: Option<Range<usize>>,
message: &str,
stage: impl TestStage,
) {
// HACK: Replace backslashes path sepators with slashes for cross
// platform reproducible error messages.
static RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new("\\((.*) (at|in) (.+)\\)").unwrap());
let message = RE.replace(message, |caps: &Captures| {
let path = caps[3].replace('\\', "/");
format!("({} {} {})", &caps[1], &caps[2], path)
});
// Try to find perfect match.
let file = file.unwrap_or(self.test.source.id());
if let Some((i, _)) = self.test.notes.iter().enumerate().find(|&(i, note)| {
!self.seen[i].contains(stage.into())
&& note.kind == kind
&& note.range == range
&& note.message == message
&& note.file == file
}) {
self.seen[i] |= stage.into();
return;
}
// Try to find closely matching annotation. If the note has the same
// range or message, it's most likely the one we're interested in.
let Some((i, note)) = self.test.notes.iter().enumerate().find(|&(i, note)| {
!self.seen[i].contains(stage.into())
&& note.kind == kind
&& (note.range == range || note.message == message)
}) else {
// Not even a close match, diagnostic is not annotated.
let diag_range = self.format_range(file, &range);
log!(into: self.not_annotated, " {kind} [{stage}]: {diag_range} {}", message);
return;
};
// Mark this annotation as visited and return it.
self.seen[i] |= stage.into();
// Range is wrong.
if range != note.range {
let note_range = self.format_range(note.file, ¬e.range);
let note_text = self.text_for_range(note.file, ¬e.range);
let diag_range = self.format_range(file, &range);
let diag_text = self.text_for_range(file, &range);
log!(self, "mismatched range [{stage}] ({}):", note.pos);
log!(self, " message | {}", note.message);
log!(self, " annotated | {note_range:<9} | {note_text}");
log!(self, " emitted | {diag_range:<9} | {diag_text}");
}
// Message is wrong.
if message != note.message {
log!(self, "mismatched message [{stage}] ({}):", note.pos);
log!(self, " annotated | {}", note.message);
log!(self, " emitted | {message}");
}
}
/// Display the text for a range.
fn text_for_range(&self, file: FileId, range: &Option<Range<usize>>) -> String {
let Some(range) = range else { return "No text".into() };
if range.is_empty() {
return "(empty)".into();
}
let lines = self.lookup(file);
lines.text()[range.clone()].replace('\n', "\\n").replace('\r', "\\r")
}
/// Display a byte range as a line:column range.
fn format_range(&self, file: FileId, range: &Option<Range<usize>>) -> String {
let Some(range) = range else { return "No range".into() };
let mut preamble = String::new();
if file != self.test.source.id() {
preamble = format!("\"{}\" ", system_path(file).unwrap().display());
}
if range.start == range.end {
format!("{preamble}{}", self.format_pos(file, range.start))
} else {
format!(
"{preamble}{}-{}",
self.format_pos(file, range.start),
self.format_pos(file, range.end)
)
}
}
/// Display a position as a line:column pair.
fn format_pos(&self, file: FileId, pos: usize) -> String {
let lines = self.lookup(file);
let res = lines.byte_to_line_column(pos).map(|(line, col)| (line + 1, col + 1));
let Some((line, col)) = res else {
return "oob".into();
};
if line == 1 { format!("{col}") } else { format!("{line}:{col}") }
}
#[track_caller]
fn lookup(&self, file: FileId) -> Lines<String> {
if self.test.source.id() == file {
self.test.source.lines().clone()
} else {
self.world.lookup(file)
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/tests/src/output.rs | tests/src/output.rs | use std::fmt::Display;
use std::str::FromStr;
use ecow::EcoString;
use indexmap::IndexMap;
use rustc_hash::FxBuildHasher;
use tiny_skia as sk;
use typst::diag::{At, SourceResult, StrResult, bail};
use typst::layout::{Abs, Frame, FrameItem, PagedDocument, Transform};
use typst::visualize::Color;
use typst_html::HtmlDocument;
use typst_pdf::{PdfOptions, PdfStandard, PdfStandards};
use typst_syntax::Span;
use crate::collect::{Test, TestOutput};
use crate::pdftags;
/// A map from a test name to the corresponding reference hash.
#[derive(Default)]
pub struct HashedRefs {
/// Whether a reference hash has been added/removed/updated and the hash
/// file on disk should be updated.
pub changed: bool,
refs: IndexMap<EcoString, HashedRef, FxBuildHasher>,
}
impl HashedRefs {
/// Get the reference hash for a test.
pub fn get(&self, name: &str) -> Option<HashedRef> {
self.refs.get(name).copied()
}
/// Whether the map is empty.
pub fn is_empty(&self) -> bool {
self.refs.is_empty()
}
/// Remove a reference hash.
pub fn remove(&mut self, name: &str) {
self.changed = true;
self.refs.shift_remove(name);
}
/// Update a reference hash.
pub fn update(&mut self, name: EcoString, hashed_ref: HashedRef) {
self.changed = true;
self.refs.insert(name, hashed_ref);
}
/// Sort the reference hashes lexicographically.
pub fn sort(&mut self) {
if !self.refs.keys().is_sorted() {
self.changed = true;
self.refs.sort_keys();
}
}
/// The names of all tests in this map.
pub fn names(&self) -> impl Iterator<Item = &EcoString> {
self.refs.keys()
}
}
impl Display for HashedRefs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for (name, hash) in self.refs.iter() {
writeln!(f, "{hash} {name}")?;
}
Ok(())
}
}
impl FromStr for HashedRefs {
type Err = EcoString;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let refs = s
.lines()
.map(|line| {
let mut parts = line.split_whitespace();
let Some(hash) = parts.next() else { bail!("found empty line") };
let hash = hash.parse()?;
let Some(name) = parts.next() else { bail!("missing test name") };
if parts.next().is_some() {
bail!("found trailing characters");
}
Ok((name.into(), hash))
})
.collect::<StrResult<IndexMap<_, _, _>>>()?;
Ok(HashedRefs { changed: false, refs })
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct HashedRef(u128);
impl Display for HashedRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:032x}", self.0)
}
}
impl FromStr for HashedRef {
type Err = EcoString;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.len() != 32 {
bail!("invalid hash: hexadecimal length must be 32");
}
if !s.chars().all(|c| c.is_ascii_hexdigit()) {
bail!("invalid hash: not a valid hexadecimal digit");
}
let val = u128::from_str_radix(s, 16).unwrap();
Ok(HashedRef(val))
}
}
/// An output type we can test.
pub trait OutputType: Sized {
/// The document type this output requires.
type Doc;
/// The type that represents live output.
type Live;
/// The test output format.
const OUTPUT: TestOutput;
/// Whether the test output is trivial and needs no reference output.
fn is_skippable(_doc: &Self::Doc, _live: &Self::Live) -> Result<bool, ()> {
Ok(false)
}
/// Produces the live output.
fn make_live(test: &Test, doc: &Self::Doc) -> SourceResult<Self::Live>;
/// Converts the live output to bytes that can be saved to disk.
fn save_live(doc: &Self::Doc, live: &Self::Live) -> impl AsRef<[u8]>;
}
/// An output type that produces file references.
pub trait FileOutputType: OutputType {
/// Produces the reference output from the live output.
fn make_ref(live: &Self::Live) -> impl AsRef<[u8]>;
/// Checks whether the reference output matches.
fn matches(old: &[u8], new: &Self::Live) -> bool;
}
/// An output type that produces hashed references.
pub trait HashOutputType: OutputType {
/// The index into the [`crate::run::HASHES`] array.
const INDEX: usize;
/// Produces the reference output from the live output.
fn make_hash(live: &Self::Live) -> HashedRef;
}
pub struct Render;
impl OutputType for Render {
type Doc = PagedDocument;
type Live = tiny_skia::Pixmap;
const OUTPUT: TestOutput = TestOutput::Render;
fn is_skippable(doc: &Self::Doc, _: &Self::Live) -> Result<bool, ()> {
is_empty_paged_document(doc)
}
fn make_live(_: &Test, doc: &Self::Doc) -> SourceResult<Self::Live> {
Ok(render(doc, 1.0))
}
fn save_live(doc: &Self::Doc, live: &Self::Live) -> impl AsRef<[u8]> {
// Save live version, possibly rerendering if different scale is
// requested.
let mut pixmap_live = live;
let slot;
let scale = crate::ARGS.scale;
if scale != 1.0 {
slot = render(doc, scale);
pixmap_live = &slot;
}
pixmap_live.encode_png().unwrap()
}
}
impl FileOutputType for Render {
fn make_ref(live: &Self::Live) -> impl AsRef<[u8]> {
let opts = oxipng::Options::max_compression();
let data = live.encode_png().unwrap();
oxipng::optimize_from_memory(&data, &opts).unwrap()
}
fn matches(old: &[u8], new: &Self::Live) -> bool {
let old_pixmap = sk::Pixmap::decode_png(old).unwrap();
approx_equal(&old_pixmap, new)
}
}
pub struct Pdf;
impl OutputType for Pdf {
type Doc = PagedDocument;
type Live = Vec<u8>;
const OUTPUT: TestOutput = TestOutput::Pdf;
fn make_live(test: &Test, doc: &Self::Doc) -> SourceResult<Self::Live> {
// Always run the default PDF export and PDF/UA-1 export, to detect
// crashes, since there are quite a few different code paths involved.
// If another standard is specified in the test, run that as well.
let default_pdf = generate_pdf(doc, None);
let ua1_pdf = generate_pdf(doc, Some(PdfStandard::Ua_1));
match test.attrs.pdf_standard {
Some(PdfStandard::Ua_1) => ua1_pdf,
Some(other) => generate_pdf(doc, Some(other)),
None => default_pdf,
}
}
fn save_live(_: &Self::Doc, live: &Self::Live) -> impl AsRef<[u8]> {
live
}
}
impl HashOutputType for Pdf {
const INDEX: usize = 0;
fn make_hash(live: &Self::Live) -> HashedRef {
HashedRef(typst_utils::hash128(live))
}
}
fn generate_pdf(
doc: &PagedDocument,
standard: Option<PdfStandard>,
) -> SourceResult<Vec<u8>> {
let standards = PdfStandards::new(standard.as_slice()).unwrap();
let options = PdfOptions { standards, ..Default::default() };
typst_pdf::pdf(doc, &options)
}
pub struct Pdftags;
impl OutputType for Pdftags {
type Doc = Vec<u8>;
type Live = String;
const OUTPUT: TestOutput = TestOutput::Pdftags;
fn is_skippable(_: &Self::Doc, live: &Self::Live) -> Result<bool, ()> {
Ok(live.is_empty())
}
fn make_live(_: &Test, doc: &Self::Doc) -> SourceResult<Self::Live> {
pdftags::format(doc).at(Span::detached())
}
fn save_live(_: &Self::Doc, live: &Self::Live) -> impl AsRef<[u8]> {
live
}
}
impl FileOutputType for Pdftags {
fn make_ref(live: &Self::Live) -> impl AsRef<[u8]> {
live
}
fn matches(old: &[u8], new: &Self::Live) -> bool {
old == new.as_bytes()
}
}
pub struct Svg;
impl OutputType for Svg {
type Doc = PagedDocument;
type Live = String;
const OUTPUT: TestOutput = TestOutput::Svg;
fn is_skippable(_: &Self::Doc, live: &Self::Live) -> Result<bool, ()> {
Ok(live.is_empty())
}
fn make_live(_: &Test, doc: &Self::Doc) -> SourceResult<Self::Live> {
Ok(typst_svg::svg_merged(doc, Abs::pt(1.0)))
}
fn save_live(_: &Self::Doc, live: &Self::Live) -> impl AsRef<[u8]> {
live
}
}
impl HashOutputType for Svg {
const INDEX: usize = 1;
fn make_hash(live: &Self::Live) -> HashedRef {
HashedRef(typst_utils::hash128(live))
}
}
pub struct Html;
impl OutputType for Html {
type Doc = HtmlDocument;
type Live = String;
const OUTPUT: TestOutput = TestOutput::Html;
fn is_skippable(_: &Self::Doc, live: &Self::Live) -> Result<bool, ()> {
Ok(live.is_empty())
}
fn make_live(_: &Test, doc: &Self::Doc) -> SourceResult<Self::Live> {
typst_html::html(doc)
}
fn save_live(_: &Self::Doc, live: &Self::Live) -> impl AsRef<[u8]> {
live
}
}
impl FileOutputType for Html {
fn make_ref(live: &Self::Live) -> impl AsRef<[u8]> {
live
}
fn matches(old: &[u8], new: &Self::Live) -> bool {
old == new.as_bytes()
}
}
/// Whether rendering of this document can be skipped.
fn is_empty_paged_document(doc: &PagedDocument) -> Result<bool, ()> {
fn skippable_frame(frame: &Frame) -> bool {
frame.items().all(|(_, item)| match item {
FrameItem::Group(group) => skippable_frame(&group.frame),
FrameItem::Tag(_) => true,
_ => false,
})
}
match doc.pages.as_slice() {
[] => Err(()),
[page] => Ok(page.frame.width().approx_eq(Abs::pt(120.0))
&& page.frame.height().approx_eq(Abs::pt(20.0))
&& page.fill.is_auto()
&& skippable_frame(&page.frame)),
_ => Ok(false),
}
}
/// Draw all frames into one image with padding in between.
fn render(document: &PagedDocument, pixel_per_pt: f32) -> sk::Pixmap {
for page in &document.pages {
let limit = Abs::cm(100.0);
if page.frame.width() > limit || page.frame.height() > limit {
panic!("overlarge frame: {:?}", page.frame.size());
}
}
let gap = Abs::pt(1.0);
let mut pixmap =
typst_render::render_merged(document, pixel_per_pt, gap, Some(Color::BLACK));
let gap = (pixel_per_pt * gap.to_pt() as f32).round();
let mut y = 0.0;
for page in &document.pages {
let ts =
sk::Transform::from_scale(pixel_per_pt, pixel_per_pt).post_translate(0.0, y);
render_links(&mut pixmap, ts, &page.frame);
y += (pixel_per_pt * page.frame.height().to_pt() as f32).round().max(1.0) + gap;
}
pixmap
}
/// Draw extra boxes for links so we can see whether they are there.
fn render_links(canvas: &mut sk::Pixmap, ts: sk::Transform, frame: &Frame) {
for (pos, item) in frame.items() {
let ts = ts.pre_translate(pos.x.to_pt() as f32, pos.y.to_pt() as f32);
match *item {
FrameItem::Group(ref group) => {
let ts = ts.pre_concat(to_sk_transform(&group.transform));
render_links(canvas, ts, &group.frame);
}
FrameItem::Link(_, size) => {
let w = size.x.to_pt() as f32;
let h = size.y.to_pt() as f32;
let rect = sk::Rect::from_xywh(0.0, 0.0, w, h).unwrap();
let mut paint = sk::Paint::default();
paint.set_color_rgba8(40, 54, 99, 40);
canvas.fill_rect(rect, &paint, ts, None);
}
_ => {}
}
}
}
/// Whether two pixel images are approximately equal.
fn approx_equal(a: &sk::Pixmap, b: &sk::Pixmap) -> bool {
a.width() == b.width()
&& a.height() == b.height()
&& a.data().iter().zip(b.data()).all(|(&a, &b)| a.abs_diff(b) <= 1)
}
/// Convert a Typst transform to a tiny-skia transform.
fn to_sk_transform(transform: &Transform) -> sk::Transform {
let Transform { sx, ky, kx, sy, tx, ty } = *transform;
sk::Transform::from_row(
sx.get() as _,
ky.get() as _,
kx.get() as _,
sy.get() as _,
tx.to_pt() as f32,
ty.to_pt() as f32,
)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/tests/src/custom.rs | tests/src/custom.rs | use std::fmt::Write;
use typst::World;
use typst::foundations::Smart;
use typst::introspection::{Location, Tag};
use typst::layout::{Frame, FrameItem, PagedDocument};
use typst::model::DocumentInfo;
use crate::collect::Test;
use crate::world::TestWorld;
/// We don't want to panic when there is a failure.
macro_rules! test_eq {
($sink:expr, $lhs:expr, $rhs:expr) => {
if $lhs != $rhs {
writeln!(&mut $sink, "{:?} != {:?}", $lhs, $rhs).unwrap();
}
};
}
/// Run special checks for specific tests for which it is not worth it to create
/// custom annotations.
pub fn check(test: &Test, world: &TestWorld, doc: Option<&PagedDocument>) -> String {
let mut sink = String::new();
match test.name.as_str() {
"document-set-author-date" => {
let info = info(doc);
test_eq!(sink, info.author, ["A", "B"]);
test_eq!(sink, info.date, Smart::Custom(world.today(None)));
}
"issue-4065-document-context" => {
let info = info(doc);
test_eq!(sink, info.title.as_deref(), Some("Top level"));
}
"issue-4769-document-context-conditional" => {
let info = info(doc);
test_eq!(sink, info.author, ["Changed"]);
test_eq!(sink, info.title.as_deref(), Some("Alternative"));
}
"tags-grouping" | "tags-textual" => {
if let Some(doc) = doc {
if let Err(message) = check_balanced(doc) {
sink.push_str(message);
}
} else {
sink.push_str("missing document");
}
}
_ => {}
}
sink
}
/// Extract the document information.
fn info(doc: Option<&PagedDocument>) -> DocumentInfo {
doc.map(|doc| doc.info.clone()).unwrap_or_default()
}
/// Naive check for whether tags are balanced in the document.
///
/// This is kept minimal for now: It does not handle groups with parents and
/// does not print useful debugging information. This is currently only run for
/// specific tests that are known not to have those. We might want to extend
/// this to the whole test suite in the future. Then we'll need to handle
/// insertions and provide a better debugging experience. However, there are
/// scenarios that are inherently (and correctly) unbalanced and we'd need some
/// way to opt out for those (via something like `large`).
fn check_balanced(doc: &PagedDocument) -> Result<(), &'static str> {
fn visit(stack: &mut Vec<Location>, frame: &Frame) -> Result<(), &'static str> {
for (_, item) in frame.items() {
match item {
FrameItem::Tag(tag) => match tag {
Tag::Start(..) => stack.push(tag.location()),
Tag::End(..) => {
if stack.pop() != Some(tag.location()) {
return Err("tags are unbalanced");
}
}
},
FrameItem::Group(group) => {
if group.parent.is_some() {
return Err("groups with parents are not supported");
}
visit(stack, &group.frame)?
}
_ => {}
}
}
Ok(())
}
let mut stack = Vec::new();
doc.pages.iter().try_for_each(|page| visit(&mut stack, &page.frame))
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/tests/fuzz/src/lib.rs | tests/fuzz/src/lib.rs | use typst::diag::{FileError, FileResult};
use typst::foundations::{Bytes, Datetime};
use typst::syntax::{FileId, Source};
use typst::text::{Font, FontBook};
use typst::utils::LazyHash;
use typst::{Library, LibraryExt, World};
pub struct FuzzWorld {
library: LazyHash<Library>,
book: LazyHash<FontBook>,
font: Font,
source: Source,
}
impl FuzzWorld {
pub fn new(text: &str) -> Self {
let data = typst_assets::fonts().next().unwrap();
let font = Font::new(Bytes::new(data), 0).unwrap();
let book = FontBook::from_fonts([&font]);
Self {
library: LazyHash::new(Library::default()),
book: LazyHash::new(book),
font,
source: Source::detached(text),
}
}
}
impl World for FuzzWorld {
fn library(&self) -> &LazyHash<Library> {
&self.library
}
fn book(&self) -> &LazyHash<FontBook> {
&self.book
}
fn main(&self) -> FileId {
self.source.id()
}
fn source(&self, id: FileId) -> FileResult<Source> {
if id == self.source.id() {
Ok(self.source.clone())
} else {
Err(FileError::NotFound(id.vpath().as_rootless_path().into()))
}
}
fn file(&self, id: FileId) -> FileResult<Bytes> {
Err(FileError::NotFound(id.vpath().as_rootless_path().into()))
}
fn font(&self, _: usize) -> Option<Font> {
Some(self.font.clone())
}
fn today(&self, _: Option<i64>) -> Option<Datetime> {
None
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/tests/fuzz/src/bin/html.rs | tests/fuzz/src/bin/html.rs | #![no_main]
use libfuzzer_sys::fuzz_target;
use typst_fuzz::FuzzWorld;
use typst_html::HtmlDocument;
fuzz_target!(|text: &str| {
let world = FuzzWorld::new(text);
if let Ok(document) = typst::compile::<HtmlDocument>(&world).output {
_ = std::hint::black_box(typst_html::html(&document));
}
comemo::evict(10);
});
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/tests/fuzz/src/bin/parse.rs | tests/fuzz/src/bin/parse.rs | #![no_main]
use libfuzzer_sys::fuzz_target;
use typst_syntax::parse;
fuzz_target!(|text: &str| {
std::hint::black_box(parse(text));
});
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/tests/fuzz/src/bin/paged.rs | tests/fuzz/src/bin/paged.rs | #![no_main]
use libfuzzer_sys::fuzz_target;
use typst::layout::PagedDocument;
use typst_fuzz::FuzzWorld;
use typst_pdf::PdfOptions;
fuzz_target!(|text: &str| {
let world = FuzzWorld::new(text);
if let Ok(document) = typst::compile::<PagedDocument>(&world).output {
if let Some(page) = document.pages.first() {
std::hint::black_box(typst_render::render(page, 1.0));
std::hint::black_box(typst_svg::svg(page));
}
_ = std::hint::black_box(typst_pdf::pdf(&document, &PdfOptions::default()));
}
comemo::evict(10);
});
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-macros/src/func.rs | crates/typst-macros/src/func.rs | use heck::ToKebabCase;
use proc_macro2::TokenStream;
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::{Ident, Result, parse_quote};
use crate::util::{
determine_name_and_title, documentation, foundations, has_attr, kw, parse_attr,
parse_flag, parse_key_value, parse_string, parse_string_array, quote_option,
validate_attrs,
};
/// Expand the `#[func]` macro.
pub fn func(stream: TokenStream, item: &syn::ItemFn) -> Result<TokenStream> {
let func = parse(stream, item)?;
Ok(create(&func, item))
}
/// Details about a function.
struct Func {
/// The function's name as exposed to Typst.
name: String,
/// The function's title case name.
title: String,
/// Whether this function has an associated scope defined by the `#[scope]` macro.
scope: bool,
/// Whether this function is a constructor.
constructor: bool,
/// A list of alternate search terms for this element.
keywords: Vec<String>,
/// The parent type of this function.
///
/// Used for functions in a scope.
parent: Option<syn::Type>,
/// Whether this function is contextual.
contextual: bool,
/// The documentation for this element as a string.
docs: String,
/// The element's visibility.
vis: syn::Visibility,
/// The name for this function given in Rust.
ident: Ident,
/// Special parameters provided by the runtime.
special: SpecialParams,
/// The list of parameters for this function.
params: Vec<Param>,
/// The return type of this function.
returns: syn::Type,
}
/// Special parameters provided by the runtime.
#[derive(Default)]
struct SpecialParams {
/// The receiver (`self`) parameter.
self_: Option<Param>,
/// The parameter named `engine`, of type `&mut Engine`.
engine: bool,
/// The parameter named `context`, of type `Tracked<Context>`.
context: bool,
/// The parameter named `args`, of type `&mut Args`.
args: bool,
/// The parameter named `span`, of type `Span`.
span: bool,
}
/// Details about a function parameter.
struct Param {
/// The binding for this parameter.
binding: Binding,
/// The name of the parameter as defined in Rust.
ident: Ident,
/// The type of the parameter.
ty: syn::Type,
/// The name of the parameter as defined in Typst.
name: String,
/// The documentation for this parameter as a string.
docs: String,
/// Whether this parameter is named.
named: bool,
/// Whether this parameter is variadic; that is, has its values
/// taken from a variable number of arguments.
variadic: bool,
/// Whether this parameter exists only in documentation.
external: bool,
/// The default value for this parameter.
default: Option<syn::Expr>,
}
/// How a parameter is bound.
enum Binding {
/// Normal parameter.
Owned,
/// `&self`.
Ref,
/// `&mut self`.
RefMut,
}
/// The `..` in `#[func(..)]`.
pub struct Meta {
/// Whether this function has an associated scope defined by the `#[scope]` macro.
pub scope: bool,
/// Whether this function is contextual.
pub contextual: bool,
/// The function's name as exposed to Typst.
pub name: Option<String>,
/// The function's title case name.
pub title: Option<String>,
/// Whether this function is a constructor.
pub constructor: bool,
/// A list of alternate search terms for this element.
pub keywords: Vec<String>,
/// The parent type of this function.
///
/// Used for functions in a scope.
pub parent: Option<syn::Type>,
}
impl Parse for Meta {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Self {
scope: parse_flag::<kw::scope>(input)?,
contextual: parse_flag::<kw::contextual>(input)?,
name: parse_string::<kw::name>(input)?,
title: parse_string::<kw::title>(input)?,
constructor: parse_flag::<kw::constructor>(input)?,
keywords: parse_string_array::<kw::keywords>(input)?,
parent: parse_key_value::<kw::parent, _>(input)?,
})
}
}
/// Parse details about the function from the fn item.
fn parse(stream: TokenStream, item: &syn::ItemFn) -> Result<Func> {
let meta: Meta = syn::parse2(stream)?;
let (name, title) =
determine_name_and_title(meta.name, meta.title, &item.sig.ident, None)?;
let docs = documentation(&item.attrs);
let mut special = SpecialParams::default();
let mut params = vec![];
for input in &item.sig.inputs {
parse_param(&mut special, &mut params, meta.parent.as_ref(), input)?;
}
let returns = match &item.sig.output {
syn::ReturnType::Default => parse_quote! { () },
syn::ReturnType::Type(_, ty) => ty.as_ref().clone(),
};
if meta.parent.is_some() && meta.scope {
bail!(item, "scoped function cannot have a scope");
}
Ok(Func {
name,
title,
scope: meta.scope,
constructor: meta.constructor,
keywords: meta.keywords,
parent: meta.parent,
contextual: meta.contextual,
docs,
vis: item.vis.clone(),
ident: item.sig.ident.clone(),
special,
params,
returns,
})
}
/// Parse details about a function parameter.
fn parse_param(
special: &mut SpecialParams,
params: &mut Vec<Param>,
parent: Option<&syn::Type>,
input: &syn::FnArg,
) -> Result<()> {
let typed = match input {
syn::FnArg::Receiver(recv) => {
let mut binding = Binding::Owned;
if recv.reference.is_some() {
if recv.mutability.is_some() {
binding = Binding::RefMut
} else {
binding = Binding::Ref
}
};
special.self_ = Some(Param {
binding,
ident: syn::Ident::new("self_", recv.self_token.span),
ty: match parent {
Some(ty) => ty.clone(),
None => bail!(recv, "explicit parent type required"),
},
name: "self".into(),
docs: documentation(&recv.attrs),
named: false,
variadic: false,
external: false,
default: None,
});
return Ok(());
}
syn::FnArg::Typed(typed) => typed,
};
let syn::Pat::Ident(syn::PatIdent { by_ref: None, mutability: None, ident, .. }) =
&*typed.pat
else {
bail!(typed.pat, "expected identifier");
};
match ident.to_string().as_str() {
"engine" => special.engine = true,
"context" => special.context = true,
"args" => special.args = true,
"span" => special.span = true,
_ => {
let mut attrs = typed.attrs.clone();
params.push(Param {
binding: Binding::Owned,
ident: ident.clone(),
ty: (*typed.ty).clone(),
name: ident.to_string().to_kebab_case(),
docs: documentation(&attrs),
named: has_attr(&mut attrs, "named"),
variadic: has_attr(&mut attrs, "variadic"),
external: has_attr(&mut attrs, "external"),
default: parse_attr(&mut attrs, "default")?.map(|expr| {
expr.unwrap_or_else(
|| parse_quote! { ::std::default::Default::default() },
)
}),
});
validate_attrs(&attrs)?;
}
}
Ok(())
}
/// Produce the function's definition.
fn create(func: &Func, item: &syn::ItemFn) -> TokenStream {
let Func { docs, vis, ident, .. } = func;
let item = rewrite_fn_item(item);
let ty = create_func_ty(func);
let data = create_func_data(func);
let creator = if ty.is_some() {
quote! {
impl #foundations::NativeFunc for #ident {
fn data() -> &'static #foundations::NativeFuncData {
static DATA: #foundations::NativeFuncData = #data;
&DATA
}
}
}
} else {
let ident_data = quote::format_ident!("{ident}_data");
quote! {
#[doc(hidden)]
#[allow(non_snake_case)]
#vis fn #ident_data() -> &'static #foundations::NativeFuncData {
static DATA: #foundations::NativeFuncData = #data;
&DATA
}
}
};
quote! {
#[doc = #docs]
#[allow(dead_code)]
#[allow(rustdoc::broken_intra_doc_links)]
#item
#[doc(hidden)]
#ty
#creator
}
}
/// Create native function data for the function.
fn create_func_data(func: &Func) -> TokenStream {
let Func {
ident,
name,
title,
docs,
keywords,
returns,
scope,
parent,
constructor,
contextual,
..
} = func;
let scope = if *scope {
quote! { <#ident as #foundations::NativeScope>::scope() }
} else {
quote! { #foundations::Scope::new() }
};
let closure = create_wrapper_closure(func);
let params = func.special.self_.iter().chain(&func.params).map(create_param_info);
let name = if *constructor {
quote! { <#parent as #foundations::NativeType>::NAME }
} else {
quote! { #name }
};
quote! {
#foundations::NativeFuncData {
function: #foundations::NativeFuncPtr(&#closure),
name: #name,
title: #title,
docs: #docs,
keywords: &[#(#keywords),*],
contextual: #contextual,
scope: ::std::sync::LazyLock::new(&|| #scope),
params: ::std::sync::LazyLock::new(&|| ::std::vec![#(#params),*]),
returns: ::std::sync::LazyLock::new(&|| <#returns as #foundations::Reflect>::output()),
}
}
}
/// Create a type that shadows the function.
fn create_func_ty(func: &Func) -> Option<TokenStream> {
if func.parent.is_some() {
return None;
}
let Func { vis, ident, .. } = func;
Some(quote! {
#[doc(hidden)]
#[allow(non_camel_case_types)]
#vis enum #ident {}
})
}
/// Create the runtime-compatible wrapper closure that parses arguments.
fn create_wrapper_closure(func: &Func) -> TokenStream {
// These handlers parse the arguments.
let handlers = {
let func_handlers = func
.params
.iter()
.filter(|param| !param.external)
.map(create_param_parser);
let self_handler = func.special.self_.as_ref().map(create_param_parser);
quote! {
#self_handler
#(#func_handlers)*
}
};
// Throws errors about unexpected arguments.
let finish = (!func.special.args).then(|| quote! { args.take().finish()?; });
// This is the actual function call.
let call = {
let self_ = func
.special
.self_
.as_ref()
.map(bind)
.map(|tokens| quote! { #tokens, });
let engine_ = func.special.engine.then(|| quote! { engine, });
let context_ = func.special.context.then(|| quote! { context, });
let args_ = func.special.args.then(|| quote! { args, });
let span_ = func.special.span.then(|| quote! { args.span, });
let forwarded = func.params.iter().filter(|param| !param.external).map(bind);
quote! {
__typst_func(#self_ #engine_ #context_ #args_ #span_ #(#forwarded,)*)
}
};
// This is the whole wrapped closure.
let ident = &func.ident;
let parent = func.parent.as_ref().map(|ty| quote! { #ty:: });
quote! {
|engine, context, args| {
let __typst_func = #parent #ident;
#handlers
#finish
let output = #call;
#foundations::IntoResult::into_result(output, args.span)
}
}
}
/// Create a parameter info for a field.
fn create_param_info(param: &Param) -> TokenStream {
let Param { name, docs, named, variadic, ty, default, .. } = param;
let positional = !named;
let required = !named && default.is_none();
let ty = if *variadic || (*named && default.is_none()) {
quote! { <#ty as #foundations::Container>::Inner }
} else {
quote! { #ty }
};
let default = quote_option(&default.as_ref().map(|_default| {
quote! {
|| {
let typed: #ty = #default;
#foundations::IntoValue::into_value(typed)
}
}
}));
quote! {
#foundations::ParamInfo {
name: #name,
docs: #docs,
input: <#ty as #foundations::Reflect>::input(),
default: #default,
positional: #positional,
named: #named,
variadic: #variadic,
required: #required,
settable: false,
}
}
}
/// Create argument parsing code for a parameter.
fn create_param_parser(param: &Param) -> TokenStream {
let Param { name, ident, ty, .. } = param;
let mut value = if param.variadic {
quote! { args.all()? }
} else if param.named {
quote! { args.named(#name)? }
} else if param.default.is_some() {
quote! { args.eat()? }
} else {
quote! { args.expect(#name)? }
};
if let Some(default) = ¶m.default {
value = quote! { #value.unwrap_or_else(|| #default) }
}
quote! { let mut #ident: #ty = #value; }
}
/// Apply the binding to a parameter.
fn bind(param: &Param) -> TokenStream {
let ident = ¶m.ident;
match param.binding {
Binding::Owned => quote! { #ident },
Binding::Ref => quote! { &#ident },
Binding::RefMut => quote! { &mut #ident },
}
}
/// Removes attributes and so on from the native function.
fn rewrite_fn_item(item: &syn::ItemFn) -> syn::ItemFn {
let inputs = item.sig.inputs.iter().cloned().filter_map(|mut input| {
if let syn::FnArg::Typed(typed) = &mut input {
if typed.attrs.iter().any(|attr| attr.path().is_ident("external")) {
return None;
}
typed.attrs.clear();
}
Some(input)
});
let mut item = item.clone();
item.attrs.clear();
item.sig.inputs = parse_quote! { #(#inputs),* };
item
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-macros/src/lib.rs | crates/typst-macros/src/lib.rs | //! Procedural macros for Typst.
extern crate proc_macro;
#[macro_use]
mod util;
mod cast;
mod elem;
mod func;
mod scope;
mod time;
mod ty;
use proc_macro::TokenStream as BoundaryStream;
use syn::DeriveInput;
/// Makes a native Rust function usable as a Typst function.
///
/// This implements `NativeFunction` for a freshly generated type with the same
/// name as a function. (In Rust, functions and types live in separate
/// namespace, so both can coexist.)
///
/// If the function is in an impl block annotated with `#[scope]`, things work a
/// bit differently because the no type can be generated within the impl block.
/// In that case, a function named `{name}_data` that returns `&'static
/// NativeFuncData` is generated. You typically don't need to interact with this
/// function though because the `#[scope]` macro hooks everything up for you.
///
/// ```ignore
/// /// Doubles an integer.
/// #[func]
/// fn double(x: i64) -> i64 {
/// 2 * x
/// }
/// ```
///
/// # Properties
/// You can customize some properties of the resulting function:
/// - `scope`: Indicates that the function has an associated scope defined by
/// the `#[scope]` macro.
/// - `contextual`: Indicates that the function makes use of context. This has
/// no effect on the behaviour itself, but is used for the docs.
/// - `name`: The functions's normal name (e.g. `min`), as exposed to Typst.
/// Defaults to the Rust name in kebab-case.
/// - `title`: The functions's title case name (e.g. `Minimum`). Defaults to the
/// normal name in title case.
/// - `keywords = [..]`: A list of alternate search terms for this function.
/// - `constructor`: Indicates that the function is a constructor.
///
/// # Arguments
/// By default, function arguments are positional and required. You can use
/// various attributes to configure their parsing behaviour:
///
/// - `#[named]`: Makes the argument named and optional. The argument type must
/// either be `Option<_>` _or_ the `#[default]` attribute must be used. (If
/// it's both `Option<_>` and `#[default]`, then the argument can be specified
/// as `none` in Typst).
/// - `#[default]`: Specifies the default value of the argument as
/// `Default::default()`.
/// - `#[default(..)]`: Specifies the default value of the argument as `..`.
/// - `#[variadic]`: Parses a variable number of arguments. The argument type
/// must be `Vec<_>`.
/// - `#[external]`: The argument appears in documentation, but is otherwise
/// ignored. Can be useful if you want to do something manually for more
/// flexibility.
///
/// Defaults can be specified for positional and named arguments. This is in
/// contrast to user-defined functions which currently cannot have optional
/// positional arguments (except through argument sinks).
///
/// In the example below, we define a `min` function that could be called as
/// `min(1, 2, 3, default: 0)` in Typst.
///
/// ```ignore
/// /// Determines the minimum of a sequence of values.
/// #[func(title = "Minimum")]
/// fn min(
/// /// The values to extract the minimum from.
/// #[variadic]
/// values: Vec<i64>,
/// /// A default value to return if there are no values.
/// #[named]
/// #[default(0)]
/// default: i64,
/// ) -> i64 {
/// self.values.iter().min().unwrap_or(default)
/// }
/// ```
///
/// As you can see, arguments can also have doc-comments, which will be rendered
/// in the documentation. The first line of documentation should be concise and
/// self-contained as it is the designated short description, which is used in
/// overviews in the documentation (and for autocompletion).
///
/// Additionally, some arguments are treated specially by this macro:
///
/// - `engine`: The compilation context (`Engine`).
/// - `context`: The introspection context (`Tracked<Context>`).
/// - `args`: The rest of the arguments passed into this function (`&mut Args`).
/// - `span`: The span of the function call (`Span`).
///
/// These should always come after `self`, in the order specified.
#[proc_macro_attribute]
pub fn func(stream: BoundaryStream, item: BoundaryStream) -> BoundaryStream {
let item = syn::parse_macro_input!(item as syn::ItemFn);
func::func(stream.into(), &item)
.unwrap_or_else(|err| err.to_compile_error())
.into()
}
/// Makes a native Rust type usable as a Typst type.
///
/// This implements `NativeType` for the given type.
///
/// ```ignore
/// /// A sequence of codepoints.
/// #[ty(scope, title = "String")]
/// struct Str(EcoString);
///
/// #[scope]
/// impl Str {
/// ...
/// }
/// ```
///
/// # Properties
/// You can customize some properties of the resulting type:
/// - `scope`: Indicates that the type has an associated scope defined by the
/// `#[scope]` macro
/// - `cast`: Indicates that the type has a custom `cast!` implementation.
/// The macro will then not autogenerate one.
/// - `name`: The type's normal name (e.g. `str`), as exposed to Typst.
/// Defaults to the Rust name in kebab-case.
/// - `title`: The type's title case name (e.g. `String`). Defaults to the
/// normal name in title case.
#[proc_macro_attribute]
pub fn ty(stream: BoundaryStream, item: BoundaryStream) -> BoundaryStream {
let item = syn::parse_macro_input!(item as syn::Item);
ty::ty(stream.into(), item)
.unwrap_or_else(|err| err.to_compile_error())
.into()
}
/// Makes a native Rust type usable as a Typst element.
///
/// This implements `NativeElement` for the given type.
///
/// ```ignore
/// /// A section heading.
/// #[elem(Show, Count)]
/// struct HeadingElem {
/// /// The logical nesting depth of the heading, starting from one.
/// #[default(NonZeroUsize::ONE)]
/// level: NonZeroUsize,
///
/// /// The heading's title.
/// #[required]
/// body: Content,
/// }
/// ```
///
/// # Properties
/// You can customize some properties of the resulting type:
/// - `scope`: Indicates that the type has an associated scope defined by the
/// `#[scope]` macro.
/// - `name = "<name>"`: The element's normal name (e.g. `align`), as exposed to Typst.
/// Defaults to the Rust name in kebab-case.
/// - `title = "<title>"`: The type's title case name (e.g. `Align`). Defaults to the long
/// name in title case.
/// - `keywords = [..]`: A list of alternate search terms for this element.
/// Defaults to the empty list.
/// - The remaining entries in the `elem` macros list are traits the element
/// is capable of. These can be dynamically accessed.
///
/// # Fields
/// By default, element fields are named and optional (and thus settable). You
/// can use various attributes to configure their parsing behaviour:
///
/// - `#[positional]`: Makes the argument positional (but still optional).
/// - `#[required]`: Makes the argument positional and required.
/// - `#[default(..)]`: Specifies the default value of the argument as `..`.
/// - `#[variadic]`: Parses a variable number of arguments. The field type must
/// be `Vec<_>`. The field will be exposed as an array.
/// - `#[parse({ .. })]`: A block of code that parses the field manually.
///
/// In addition that there are a number of attributes that configure other
/// aspects of the field than the parsing behaviour.
/// - `#[resolve]`: When accessing the field, it will be automatically
/// resolved through the `Resolve` trait. This, for instance, turns `Length`
/// into `Abs`. It's just convenient.
/// - `#[fold]`: When there are multiple set rules for the field, all values
/// are folded together into one. E.g. `set rect(stroke: 2pt)` and
/// `set rect(stroke: red)` are combined into the equivalent of
/// `set rect(stroke: 2pt + red)` instead of having `red` override `2pt`.
/// - `#[borrowed]`: For fields that are accessed through the style chain,
/// indicates that accessor methods to this field should return references
/// to the value instead of cloning.
/// - `#[internal]`: The field does not appear in the documentation.
/// - `#[external]`: The field appears in the documentation, but is otherwise
/// ignored. Can be useful if you want to do something manually for more
/// flexibility.
/// - `#[synthesized]`: The field cannot be specified in a constructor or set
/// rule. Instead, it is added to an element before its show rule runs
/// through the `Synthesize` trait.
/// - `#[ghost]`: Allows creating fields that are only present in the style chain,
/// this means that they *cannot* be accessed by the user, they cannot be set
/// on an individual instantiated element, and must be set via the style chain.
/// This is useful for fields that are only used internally by the style chain,
/// such as the fields from `ParElem` and `TextElem`. If your element contains
/// any ghost fields, then you cannot auto-generate `Construct` for it, and
/// you must implement `Construct` manually.
#[proc_macro_attribute]
pub fn elem(stream: BoundaryStream, item: BoundaryStream) -> BoundaryStream {
let item = syn::parse_macro_input!(item as syn::ItemStruct);
elem::elem(stream.into(), item)
.unwrap_or_else(|err| err.to_compile_error())
.into()
}
/// Provides an associated scope to a native function, type, or element.
///
/// This implements `NativeScope` for the function's shadow type, the type, or
/// the element.
///
/// The implementation block can contain four kinds of items:
/// - constants, which will be defined through `scope.define`
/// - functions, which will be defined through `scope.define_func`
/// - types, which will be defined through `scope.define_type`
/// - elements, which will be defined through `scope.define_elem`
///
/// ```ignore
/// #[func(scope)]
/// fn name() { .. }
///
/// #[scope]
/// impl name {
/// /// A simple constant.
/// const VAL: u32 = 0;
///
/// /// A function.
/// #[func]
/// fn foo() -> EcoString {
/// "foo!".into()
/// }
///
/// /// A type.
/// type Brr;
///
/// /// An element.
/// #[elem]
/// type NiceElem;
/// }
///
/// #[ty]
/// struct Brr;
///
/// #[elem]
/// struct NiceElem {}
/// ```
#[proc_macro_attribute]
pub fn scope(stream: BoundaryStream, item: BoundaryStream) -> BoundaryStream {
let item = syn::parse_macro_input!(item as syn::Item);
scope::scope(stream.into(), item)
.unwrap_or_else(|err| err.to_compile_error())
.into()
}
/// Implements `Reflect`, `FromValue`, and `IntoValue` for a type.
///
/// - `Reflect` makes Typst's runtime aware of the type's characteristics.
/// It's important for autocompletion, error messages, etc.
/// - `FromValue` defines how to cast from a value into this type.
/// - `IntoValue` defines how to cast from this type into a value.
///
/// ```ignore
/// /// An integer between 0 and 13.
/// struct CoolInt(u8);
///
/// cast! {
/// CoolInt,
///
/// // Defines how to turn a `CoolInt` into a value.
/// self => self.0.into_value(),
///
/// // Defines "match arms" of types that can be cast into a `CoolInt`.
/// // These types needn't be value primitives, they can themselves use
/// // `cast!`.
/// v: bool => Self(v as u8),
/// v: i64 => if matches!(v, 0..=13) {
/// Self(v as u8)
/// } else {
/// bail!("integer is not nice :/")
/// },
/// }
/// ```
#[proc_macro]
pub fn cast(stream: BoundaryStream) -> BoundaryStream {
cast::cast(stream.into())
.unwrap_or_else(|err| err.to_compile_error())
.into()
}
/// Implements `Reflect`, `FromValue`, and `IntoValue` for an enum.
///
/// The enum will become castable from kebab-case strings. The doc-comments will
/// become user-facing documentation for each variant. The `#[string]` attribute
/// can be used to override the string corresponding to a variant.
///
/// ```ignore
/// /// A stringy enum of options.
/// #[derive(Cast)]
/// enum Niceness {
/// /// Clearly nice (parses from `"nice"`).
/// Nice,
/// /// Not so nice (parses from `"not-nice"`).
/// NotNice,
/// /// Very much not nice (parses from `"❌"`).
/// #[string("❌")]
/// Unnice,
/// }
/// ```
#[proc_macro_derive(Cast, attributes(string))]
pub fn derive_cast(item: BoundaryStream) -> BoundaryStream {
let item = syn::parse_macro_input!(item as DeriveInput);
cast::derive_cast(item)
.unwrap_or_else(|err| err.to_compile_error())
.into()
}
/// Times function invocations.
///
/// When tracing is enabled in the typst-cli, this macro will record the
/// invocations of the function and store them in a global map. The map can be
/// accessed through the `typst_trace::RECORDER` static.
///
/// You can also specify the span of the function invocation:
/// - `#[time(span = ..)]` to record the span, which will be used for the
/// `EventKey`.
///
/// By default, all tracing is omitted using the `wasm32` target flag.
/// This is done to avoid bloating the web app, which doesn't need tracing.
///
/// ```ignore
/// #[time]
/// fn fibonacci(n: u64) -> u64 {
/// if n <= 1 {
/// 1
/// } else {
/// fibonacci(n - 1) + fibonacci(n - 2)
/// }
/// }
///
/// #[time(span = span)]
/// fn fibonacci_spanned(n: u64, span: Span) -> u64 {
/// if n <= 1 {
/// 1
/// } else {
/// fibonacci(n - 1) + fibonacci(n - 2)
/// }
/// }
/// ```
#[proc_macro_attribute]
pub fn time(stream: BoundaryStream, item: BoundaryStream) -> BoundaryStream {
let item = syn::parse_macro_input!(item as syn::ItemFn);
time::time(stream.into(), item)
.unwrap_or_else(|err| err.to_compile_error())
.into()
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-macros/src/elem.rs | crates/typst-macros/src/elem.rs | use heck::ToKebabCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{Ident, Result, Token};
use crate::util::{
BlockWithReturn, determine_name_and_title, documentation, foundations, has_attr, kw,
parse_attr, parse_flag, parse_string, parse_string_array, validate_attrs,
};
/// Expand the `#[elem]` macro.
pub fn elem(stream: TokenStream, body: syn::ItemStruct) -> Result<TokenStream> {
let element = parse(stream, &body)?;
create(&element)
}
/// Details about an element.
struct Elem {
/// The element's name as exposed to Typst.
name: String,
/// The element's title case name.
title: String,
/// Whether this element has an associated scope defined by the `#[scope]` macro.
scope: bool,
/// A list of alternate search terms for this element.
keywords: Vec<String>,
/// The documentation for this element as a string.
docs: String,
/// The element's visibility.
vis: syn::Visibility,
/// The struct name for this element given in Rust.
ident: Ident,
/// The list of capabilities for this element.
capabilities: Vec<Ident>,
/// The fields of this element.
fields: Vec<Field>,
}
impl Elem {
/// Whether the element has the given trait listed as a capability.
fn can(&self, name: &str) -> bool {
self.capabilities.iter().any(|capability| capability == name)
}
/// Whether the element does not have the given trait listed as a
/// capability.
fn cannot(&self, name: &str) -> bool {
!self.can(name)
}
/// Whether the element has the given trait listed as a capability.
fn with(&self, name: &str) -> Option<&Ident> {
self.capabilities.iter().find(|capability| *capability == name)
}
}
impl Elem {
/// All fields that are not just external.
fn real_fields(&self) -> impl Iterator<Item = &Field> + Clone {
self.fields.iter().filter(|field| !field.external)
}
/// Fields that are present in the generated struct.
fn struct_fields(&self) -> impl Iterator<Item = &Field> + Clone {
self.real_fields().filter(|field| !field.ghost)
}
/// Fields that get accessor, with, and push methods.
fn accessor_fields(&self) -> impl Iterator<Item = &Field> + Clone {
self.struct_fields().filter(|field| !field.required)
}
/// Fields that are relevant for `Construct` impl.
///
/// The reason why fields that are `parse` and internal are allowed is
/// because it's a pattern used a lot for parsing data from the input and
/// then storing it in a field.
fn construct_fields(&self) -> impl Iterator<Item = &Field> + Clone {
self.real_fields().filter(|field| {
field.parse.is_some() || (!field.synthesized && !field.internal)
})
}
/// Fields that can be configured with set rules.
fn set_fields(&self) -> impl Iterator<Item = &Field> + Clone {
self.construct_fields().filter(|field| !field.required)
}
}
/// A field of an [element definition][`Elem`].
struct Field {
/// The index of the field among all.
i: u8,
/// The name of this field.
ident: Ident,
/// The identifier `with_{ident}`.
with_ident: Ident,
/// The visibility of this field.
vis: syn::Visibility,
/// The type of this field.
ty: syn::Type,
/// The field's identifier as exposed to Typst.
name: String,
/// The documentation for this field as a string.
docs: String,
/// Whether this field is positional (as opposed to named).
positional: bool,
/// Whether this field is required.
required: bool,
/// Whether this field is variadic; that is, has its values
/// taken from a variable number of arguments.
variadic: bool,
/// Whether this field has a `#[fold]` attribute.
fold: bool,
/// Whether this field is excluded from documentation.
internal: bool,
/// Whether this field exists only in documentation.
external: bool,
/// Whether this field has a `#[ghost]` attribute.
ghost: bool,
/// Whether this field has a `#[synthesized]` attribute.
synthesized: bool,
/// The contents of the `#[parse({..})]` attribute, if any.
parse: Option<BlockWithReturn>,
/// The contents of the `#[default(..)]` attribute, if any.
default: Option<syn::Expr>,
}
/// The `..` in `#[elem(..)]`.
struct Meta {
scope: bool,
name: Option<String>,
title: Option<String>,
keywords: Vec<String>,
capabilities: Vec<Ident>,
}
impl Parse for Meta {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Self {
scope: parse_flag::<kw::scope>(input)?,
name: parse_string::<kw::name>(input)?,
title: parse_string::<kw::title>(input)?,
keywords: parse_string_array::<kw::keywords>(input)?,
capabilities: Punctuated::<Ident, Token![,]>::parse_terminated(input)?
.into_iter()
.collect(),
})
}
}
/// Parse details about the element from its struct definition.
fn parse(stream: TokenStream, body: &syn::ItemStruct) -> Result<Elem> {
let meta: Meta = syn::parse2(stream)?;
let (name, title) = determine_name_and_title(
meta.name,
meta.title,
&body.ident,
Some(|base| base.trim_end_matches("Elem")),
)?;
let docs = documentation(&body.attrs);
let syn::Fields::Named(named) = &body.fields else {
bail!(body, "expected named fields");
};
let mut fields = named.named.iter().map(parse_field).collect::<Result<Vec<_>>>()?;
fields.sort_by_key(|field| field.internal);
for (i, field) in fields.iter_mut().enumerate() {
field.i = i as u8;
}
if fields.iter().any(|field| field.ghost && !field.internal)
&& meta.capabilities.iter().all(|capability| capability != "Construct")
{
bail!(
body.ident,
"cannot have public ghost fields and an auto-generated constructor",
);
}
Ok(Elem {
name,
title,
scope: meta.scope,
keywords: meta.keywords,
docs,
vis: body.vis.clone(),
ident: body.ident.clone(),
capabilities: meta.capabilities,
fields,
})
}
fn parse_field(field: &syn::Field) -> Result<Field> {
let Some(ident) = field.ident.clone() else {
bail!(field, "expected named field");
};
if ident == "label" {
bail!(ident, "invalid field name `label`");
}
let mut attrs = field.attrs.clone();
let variadic = has_attr(&mut attrs, "variadic");
let required = has_attr(&mut attrs, "required") || variadic;
let positional = has_attr(&mut attrs, "positional") || required;
let field = Field {
i: 0,
ident: ident.clone(),
with_ident: format_ident!("with_{ident}"),
vis: field.vis.clone(),
ty: field.ty.clone(),
name: ident.to_string().to_kebab_case(),
docs: documentation(&attrs),
positional,
required,
variadic,
fold: has_attr(&mut attrs, "fold"),
internal: has_attr(&mut attrs, "internal"),
external: has_attr(&mut attrs, "external"),
ghost: has_attr(&mut attrs, "ghost"),
synthesized: has_attr(&mut attrs, "synthesized"),
parse: parse_attr(&mut attrs, "parse")?.flatten(),
default: parse_attr::<syn::Expr>(&mut attrs, "default")?.flatten(),
};
if field.required && field.synthesized {
bail!(ident, "required fields cannot be synthesized");
}
if (field.required || field.synthesized)
&& (field.default.is_some() || field.fold || field.ghost)
{
bail!(ident, "required and synthesized fields cannot be default, fold, or ghost");
}
validate_attrs(&attrs)?;
Ok(field)
}
/// Produce the element's definition.
fn create(element: &Elem) -> Result<TokenStream> {
// The struct itself.
let struct_ = create_struct(element);
// Implementations.
let inherent_impl = create_inherent_impl(element);
let native_element_impl = create_native_elem_impl(element);
let field_impls =
element.fields.iter().map(|field| create_field_impl(element, field));
let construct_impl =
element.cannot("Construct").then(|| create_construct_impl(element));
let set_impl = element.cannot("Set").then(|| create_set_impl(element));
let unqueriable_impl = element
.with("Unqueriable")
.map(|cap| create_introspection_impl(element, cap));
let locatable_impl = element
.with("Locatable")
.map(|cap| create_introspection_impl(element, cap));
let tagged_impl = element
.with("Tagged")
.map(|cap| create_introspection_impl(element, cap));
let mathy_impl = element.can("Mathy").then(|| create_mathy_impl(element));
// We use a const block to create an anonymous scope, as to not leak any
// local definitions.
Ok(quote! {
#struct_
const _: () = {
#inherent_impl
#native_element_impl
#(#field_impls)*
#construct_impl
#set_impl
#unqueriable_impl
#locatable_impl
#tagged_impl
#mathy_impl
};
})
}
/// Create the struct definition itself.
fn create_struct(element: &Elem) -> TokenStream {
let Elem { vis, ident, docs, .. } = element;
let debug = element.cannot("Debug").then(|| quote! { Debug, });
let fields = element.struct_fields().map(create_field);
quote! {
#[doc = #docs]
#[derive(Hash, #debug Clone)]
#[allow(rustdoc::broken_intra_doc_links)]
#vis struct #ident {
#(#fields,)*
}
}
}
/// Create a field declaration for the struct.
fn create_field(field: &Field) -> TokenStream {
let Field { i, vis, ident, ty, .. } = field;
if field.required {
quote! { #vis #ident: #ty }
} else if field.synthesized {
quote! { #vis #ident: ::std::option::Option<#ty> }
} else {
quote! { #vis #ident: #foundations::Settable<Self, #i> }
}
}
/// Create the inherent implementation of the struct.
fn create_inherent_impl(element: &Elem) -> TokenStream {
let Elem { ident, .. } = element;
let new_func = create_new_func(element);
let with_field_methods = element.accessor_fields().map(create_with_field_method);
let style_consts = element.real_fields().map(|field| {
let Field { i, vis, ident, .. } = field;
quote! {
#vis const #ident: #foundations::Field<Self, #i>
= #foundations::Field::new();
}
});
quote! {
impl #ident {
#new_func
#(#with_field_methods)*
}
#[allow(non_upper_case_globals)]
impl #ident {
#(#style_consts)*
}
}
}
/// Create the `new` function for the element.
fn create_new_func(element: &Elem) -> TokenStream {
let params = element
.struct_fields()
.filter(|field| field.required)
.map(|Field { ident, ty, .. }| quote! { #ident: #ty });
let fields = element.struct_fields().map(|field| {
let ident = &field.ident;
if field.required {
quote! { #ident }
} else if field.synthesized {
quote! { #ident: None }
} else {
quote! { #ident: #foundations::Settable::new() }
}
});
quote! {
/// Create a new instance of the element.
pub fn new(#(#params),*) -> Self {
Self { #(#fields,)* }
}
}
}
/// Create a builder-style setter method for a field.
fn create_with_field_method(field: &Field) -> TokenStream {
let Field { vis, ident, with_ident, name, ty, .. } = field;
let doc = format!("Builder-style setter for the [`{name}`](Self::{ident}) field.");
let expr = if field.required {
quote! { self.#ident = #ident }
} else if field.synthesized {
quote! { self.#ident = Some(#ident) }
} else {
quote! { self.#ident.set(#ident) }
};
quote! {
#[doc = #doc]
#vis fn #with_ident(mut self, #ident: #ty) -> Self {
#expr;
self
}
}
}
/// Creates the element's `NativeElement` implementation.
fn create_native_elem_impl(element: &Elem) -> TokenStream {
let Elem { name, ident, title, scope, keywords, docs, .. } = element;
let fields = element.fields.iter().filter(|field| !field.internal).map(|field| {
let i = field.i;
if field.external {
quote! { #foundations::ExternalFieldData::<#ident, #i>::vtable() }
} else if field.variadic {
quote! { #foundations::RequiredFieldData::<#ident, #i>::vtable_variadic() }
} else if field.required {
quote! { #foundations::RequiredFieldData::<#ident, #i>::vtable() }
} else if field.synthesized {
quote! { #foundations::SynthesizedFieldData::<#ident, #i>::vtable() }
} else if field.ghost {
quote! { #foundations::SettablePropertyData::<#ident, #i>::vtable() }
} else {
quote! { #foundations::SettableFieldData::<#ident, #i>::vtable() }
}
});
let field_arms = element
.fields
.iter()
.filter(|field| !field.internal && !field.external)
.map(|field| {
let Field { name, i, .. } = field;
quote! { #name => Some(#i) }
});
let field_id = quote! {
|name| match name {
#(#field_arms,)*
_ => None,
}
};
let capable_func = create_capable_func(element);
let with_keywords =
(!keywords.is_empty()).then(|| quote! { .with_keywords(&[#(#keywords),*]) });
let with_repr = element.can("Repr").then(|| quote! { .with_repr() });
let with_partial_eq = element.can("PartialEq").then(|| quote! { .with_partial_eq() });
let with_local_name = element.can("LocalName").then(|| quote! { .with_local_name() });
let with_scope = scope.then(|| quote! { .with_scope() });
quote! {
unsafe impl #foundations::NativeElement for #ident {
const ELEM: #foundations::Element = #foundations::Element::from_vtable({
static STORE: #foundations::LazyElementStore
= #foundations::LazyElementStore::new();
static VTABLE: #foundations::ContentVtable =
#foundations::ContentVtable::new::<#ident>(
#name,
#title,
#docs,
&[#(#fields),*],
#field_id,
#capable_func,
|| &STORE,
) #with_keywords
#with_repr
#with_partial_eq
#with_local_name
#with_scope
.erase();
&VTABLE
});
}
}
}
/// Creates the appropriate trait implementation for a field.
fn create_field_impl(element: &Elem, field: &Field) -> TokenStream {
let elem_ident = &element.ident;
let Field { i, ty, ident, default, positional, name, docs, .. } = field;
let default = match default {
Some(default) => quote! { || #default },
None => quote! { std::default::Default::default },
};
if field.external {
quote! {
impl #foundations::ExternalField<#i> for #elem_ident {
type Type = #ty;
const FIELD: #foundations::ExternalFieldData<Self, #i> =
#foundations::ExternalFieldData::<Self, #i>::new(
#name,
#docs,
#default,
);
}
}
} else if field.required {
quote! {
impl #foundations::RequiredField<#i> for #elem_ident {
type Type = #ty;
const FIELD: #foundations::RequiredFieldData<Self, #i> =
#foundations::RequiredFieldData::<Self, #i>::new(
#name,
#docs,
|elem| &elem.#ident,
);
}
}
} else if field.synthesized {
quote! {
impl #foundations::SynthesizedField<#i> for #elem_ident {
type Type = #ty;
const FIELD: #foundations::SynthesizedFieldData<Self, #i> =
#foundations::SynthesizedFieldData::<Self, #i>::new(
#name,
#docs,
|elem| &elem.#ident,
);
}
}
} else {
let slot = quote! {
|| {
static LOCK: ::std::sync::OnceLock<#ty> = ::std::sync::OnceLock::new();
&LOCK
}
};
let with_fold = field.fold.then(|| quote! { .with_fold() });
let refable = (!field.fold).then(|| {
quote! {
impl #foundations::RefableProperty<#i> for #elem_ident {}
}
});
if field.ghost {
quote! {
impl #foundations::SettableProperty<#i> for #elem_ident {
type Type = #ty;
const FIELD: #foundations::SettablePropertyData<Self, #i> =
#foundations::SettablePropertyData::<Self, #i>::new(
#name,
#docs,
#positional,
#default,
#slot,
) #with_fold;
}
#refable
}
} else {
quote! {
impl #foundations::SettableField<#i> for #elem_ident {
type Type = #ty;
const FIELD: #foundations::SettableFieldData<Self, #i> =
#foundations::SettableFieldData::<Self, #i>::new(
#name,
#docs,
#positional,
|elem| &elem.#ident,
|elem| &mut elem.#ident,
#default,
#slot,
) #with_fold;
}
#refable
}
}
}
}
/// Creates the element's `Construct` implementation.
fn create_construct_impl(element: &Elem) -> TokenStream {
let ident = &element.ident;
let setup = element.construct_fields().map(|field| {
let (prefix, value) = create_field_parser(field);
let ident = &field.ident;
quote! {
#prefix
let #ident = #value;
}
});
let fields = element.struct_fields().map(|field| {
let ident = &field.ident;
if field.required {
quote! { #ident }
} else if field.synthesized {
quote! { #ident: None }
} else {
quote! { #ident: #foundations::Settable::from(#ident) }
}
});
quote! {
impl #foundations::Construct for #ident {
fn construct(
engine: &mut ::typst_library::engine::Engine,
args: &mut #foundations::Args,
) -> ::typst_library::diag::SourceResult<#foundations::Content> {
#(#setup)*
Ok(#foundations::Content::new(Self { #(#fields),* }))
}
}
}
}
/// Creates the element's `Set` implementation.
fn create_set_impl(element: &Elem) -> TokenStream {
let ident = &element.ident;
let handlers = element.set_fields().map(|field| {
let field_ident = &field.ident;
let (prefix, value) = create_field_parser(field);
quote! {
#prefix
if let Some(value) = #value {
styles.set(Self::#field_ident, value);
}
}
});
quote! {
impl #foundations::Set for #ident {
fn set(
engine: &mut ::typst_library::engine::Engine,
args: &mut #foundations::Args,
) -> ::typst_library::diag::SourceResult<#foundations::Styles> {
let mut styles = #foundations::Styles::new();
#(#handlers)*
Ok(styles)
}
}
}
}
/// Create argument parsing code for a field.
fn create_field_parser(field: &Field) -> (TokenStream, TokenStream) {
if let Some(BlockWithReturn { prefix, expr }) = &field.parse {
return (quote! { #(#prefix);* }, quote! { #expr });
}
let name = &field.name;
let value = if field.variadic {
quote! { args.all()? }
} else if field.required {
quote! { args.expect(#name)? }
} else if field.positional {
quote! { args.find()? }
} else {
quote! { args.named(#name)? }
};
(quote! {}, value)
}
/// Creates the element's casting vtable.
fn create_capable_func(element: &Elem) -> TokenStream {
// Forbidden capabilities (i.e capabilities that are not object safe).
const FORBIDDEN: &[&str] =
&["Debug", "PartialEq", "Hash", "Construct", "Set", "Repr", "LocalName"];
let ident = &element.ident;
let relevant = element
.capabilities
.iter()
.filter(|&ident| !FORBIDDEN.contains(&(&ident.to_string() as &str)));
let checks = relevant.map(|capability| {
quote! {
if capability == ::std::any::TypeId::of::<dyn #capability>() {
// Safety: The vtable function doesn't require initialized
// data, so it's fine to use a dangling pointer.
return Some(unsafe {
::typst_utils::fat::vtable(dangling as *const dyn #capability)
});
}
}
});
quote! {
|capability| {
let dangling = ::std::ptr::NonNull::<#foundations::Packed<#ident>>::dangling().as_ptr();
#(#checks)*
None
}
}
}
/// Creates the element's introspection capability implementation.
fn create_introspection_impl(element: &Elem, capability: &Ident) -> TokenStream {
let ident = &element.ident;
quote! { impl ::typst_library::introspection::#capability for #foundations::Packed<#ident> {} }
}
/// Creates the element's `Mathy` implementation.
fn create_mathy_impl(element: &Elem) -> TokenStream {
let ident = &element.ident;
quote! { impl ::typst_library::math::Mathy for #foundations::Packed<#ident> {} }
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-macros/src/time.rs | crates/typst-macros/src/time.rs | use proc_macro2::TokenStream;
use quote::{ToTokens, quote};
use syn::parse::{Parse, ParseStream};
use syn::{Result, parse_quote};
use crate::util::{kw, parse_key_value, parse_string};
/// Expand the `#[time(..)]` macro.
pub fn time(stream: TokenStream, item: syn::ItemFn) -> Result<TokenStream> {
let meta: Meta = syn::parse2(stream)?;
Ok(create(meta, item))
}
/// The `..` in `#[time(..)]`.
pub struct Meta {
pub span: Option<syn::Expr>,
pub name: Option<String>,
}
impl Parse for Meta {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Self {
name: parse_string::<kw::name>(input)?,
span: parse_key_value::<kw::span, syn::Expr>(input)?,
})
}
}
fn create(meta: Meta, mut item: syn::ItemFn) -> TokenStream {
let name = meta.name.unwrap_or_else(|| item.sig.ident.to_string());
let construct = match meta.span.as_ref() {
Some(span) => quote! { with_span(#name, Some(#span.into_raw())) },
None => quote! { new(#name) },
};
item.block.stmts.insert(
0,
parse_quote! {
let __scope = ::typst_timing::TimingScope::#construct;
},
);
item.into_token_stream()
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-macros/src/util.rs | crates/typst-macros/src/util.rs | use heck::{ToKebabCase, ToTitleCase};
use proc_macro2::TokenStream;
use quote::{ToTokens, quote};
use syn::parse::{Parse, ParseStream};
use syn::token::Token;
use syn::{Attribute, Ident, Result, Token};
/// Return an error at the given item.
macro_rules! bail {
(callsite, $($tts:tt)*) => {
return Err(syn::Error::new(
proc_macro2::Span::call_site(),
format!("typst: {}", format!($($tts)*))
))
};
($item:expr, $($tts:tt)*) => {
return Err(syn::Error::new_spanned(
&$item,
format!("typst: {}", format!($($tts)*))
))
};
}
/// Extract documentation comments from an attribute list.
pub fn documentation(attrs: &[syn::Attribute]) -> String {
let mut doc = String::new();
// Parse doc comments.
for attr in attrs {
if let syn::Meta::NameValue(meta) = &attr.meta
&& meta.path.is_ident("doc")
&& let syn::Expr::Lit(lit) = &meta.value
&& let syn::Lit::Str(string) = &lit.lit
{
let full = string.value();
let line = full.strip_prefix(' ').unwrap_or(&full);
doc.push_str(line);
doc.push('\n');
}
}
doc.trim().into()
}
/// Whether an attribute list has a specified attribute.
pub fn has_attr(attrs: &mut Vec<syn::Attribute>, target: &str) -> bool {
take_attr(attrs, target).is_some()
}
/// Whether an attribute list has a specified attribute.
pub fn parse_attr<T: Parse>(
attrs: &mut Vec<syn::Attribute>,
target: &str,
) -> Result<Option<Option<T>>> {
take_attr(attrs, target)
.map(|attr| {
Ok(match attr.meta {
syn::Meta::Path(_) => None,
syn::Meta::List(list) => Some(list.parse_args()?),
syn::Meta::NameValue(meta) => bail!(meta, "not valid here"),
})
})
.transpose()
}
/// Whether an attribute list has a specified attribute.
pub fn take_attr(
attrs: &mut Vec<syn::Attribute>,
target: &str,
) -> Option<syn::Attribute> {
attrs
.iter()
.position(|attr| attr.path().is_ident(target))
.map(|i| attrs.remove(i))
}
/// Ensure that no unrecognized attributes remain.
pub fn validate_attrs(attrs: &[syn::Attribute]) -> Result<()> {
for attr in attrs {
if !attr.path().is_ident("doc") && !attr.path().is_ident("derive") {
let ident = attr.path().get_ident().unwrap();
bail!(ident, "unrecognized attribute: {ident}");
}
}
Ok(())
}
/// Quotes an option literally.
pub fn quote_option<T: ToTokens>(option: &Option<T>) -> TokenStream {
if let Some(value) = option {
quote! { Some(#value) }
} else {
quote! { None }
}
}
/// Parse a metadata key-value pair, separated by `=`.
pub fn parse_key_value<K: Token + Default + Parse, V: Parse>(
input: ParseStream,
) -> Result<Option<V>> {
if !input.peek(|_| K::default()) {
return Ok(None);
}
let _: K = input.parse()?;
let _: Token![=] = input.parse()?;
let value: V = input.parse::<V>()?;
eat_comma(input);
Ok(Some(value))
}
/// Parse a metadata key-array pair, separated by `=`.
pub fn parse_key_value_array<K: Token + Default + Parse, V: Parse>(
input: ParseStream,
) -> Result<Vec<V>> {
Ok(parse_key_value::<K, Array<V>>(input)?.map_or(vec![], |array| array.0))
}
/// Parse a metadata key-string pair, separated by `=`.
pub fn parse_string<K: Token + Default + Parse>(
input: ParseStream,
) -> Result<Option<String>> {
Ok(parse_key_value::<K, syn::LitStr>(input)?.map(|s| s.value()))
}
/// Parse a metadata key-string pair, separated by `=`.
pub fn parse_string_array<K: Token + Default + Parse>(
input: ParseStream,
) -> Result<Vec<String>> {
Ok(parse_key_value_array::<K, syn::LitStr>(input)?
.into_iter()
.map(|lit| lit.value())
.collect())
}
/// Parse a metadata flag that can be present or not.
pub fn parse_flag<K: Token + Default + Parse>(input: ParseStream) -> Result<bool> {
if input.peek(|_| K::default()) {
let _: K = input.parse()?;
eat_comma(input);
return Ok(true);
}
Ok(false)
}
/// Parse a comma if there is one.
pub fn eat_comma(input: ParseStream) {
if input.peek(Token![,]) {
let _: Token![,] = input.parse().unwrap();
}
}
/// Determine the normal and title case name of a function, type, or element.
pub fn determine_name_and_title(
specified_name: Option<String>,
specified_title: Option<String>,
ident: &syn::Ident,
trim: Option<fn(&str) -> &str>,
) -> Result<(String, String)> {
let name = {
let trim = trim.unwrap_or(|s| s);
let default = trim(&ident.to_string()).to_kebab_case();
if specified_name.as_ref() == Some(&default) {
bail!(ident, "name was specified unnecessarily");
}
specified_name.unwrap_or(default)
};
let title = {
let default = name.to_title_case();
if specified_title.as_ref() == Some(&default) {
bail!(ident, "title was specified unnecessarily");
}
specified_title.unwrap_or(default)
};
Ok((name, title))
}
/// A generic parseable array.
struct Array<T>(Vec<T>);
impl<T: Parse> Parse for Array<T> {
fn parse(input: ParseStream) -> Result<Self> {
let content;
syn::bracketed!(content in input);
let mut elems = Vec::new();
while !content.is_empty() {
let first: T = content.parse()?;
elems.push(first);
if !content.is_empty() {
let _: Token![,] = content.parse()?;
}
}
Ok(Self(elems))
}
}
/// Shorthand for `::typst_library::foundations`.
#[allow(non_camel_case_types)]
pub struct foundations;
impl quote::ToTokens for foundations {
fn to_tokens(&self, tokens: &mut TokenStream) {
quote! { ::typst_library::foundations }.to_tokens(tokens);
}
}
/// For parsing attributes of the form:
/// #[attr(
/// statement;
/// statement;
/// returned_expression
/// )]
pub struct BlockWithReturn {
pub prefix: Vec<syn::Stmt>,
pub expr: syn::Stmt,
}
impl Parse for BlockWithReturn {
fn parse(input: ParseStream) -> Result<Self> {
let mut stmts = syn::Block::parse_within(input)?;
let Some(expr) = stmts.pop() else {
return Err(input.error("expected at least one expression"));
};
Ok(Self { prefix: stmts, expr })
}
}
/// Parse a bare `type Name;` item.
#[allow(dead_code)]
pub struct BareType {
pub attrs: Vec<Attribute>,
pub type_token: Token![type],
pub ident: Ident,
pub semi_token: Token![;],
}
impl Parse for BareType {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Self {
attrs: input.call(Attribute::parse_outer)?,
type_token: input.parse()?,
ident: input.parse()?,
semi_token: input.parse()?,
})
}
}
pub mod kw {
syn::custom_keyword!(name);
syn::custom_keyword!(span);
syn::custom_keyword!(title);
syn::custom_keyword!(scope);
syn::custom_keyword!(contextual);
syn::custom_keyword!(cast);
syn::custom_keyword!(constructor);
syn::custom_keyword!(keywords);
syn::custom_keyword!(parent);
syn::custom_keyword!(ext);
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.