pub struct App {
pub world: World,
pub runner: Box<dyn FnOnce(App) + Send>,
pub main_schedule_label: Interned<dyn ScheduleLabel>,
/* private fields */
}
Expand description
A container of app logic and data.
Bundles together the necessary elements like World
and Schedule
to create
an ECS-based application. It also stores a pointer to a runner function.
The runner is responsible for managing the application’s event loop and applying the
Schedule
to the World
to drive application logic.
§Examples
Here is a simple “Hello World” Bevy app:
fn main() {
App::new()
.add_systems(Update, hello_world_system)
.run();
}
fn hello_world_system() {
println!("hello world");
}
Fields§
§world: World
The main ECS World
of the App
.
This stores and provides access to all the main data of the application.
The systems of the App
will run using this World
.
If additional separate World
-Schedule
pairs are needed, you can use sub_app
s.
runner: Box<dyn FnOnce(App) + Send>
The runner function is primarily responsible for managing
the application’s event loop and advancing the Schedule
.
Typically, it is not configured manually, but set by one of Bevy’s built-in plugins.
See bevy::winit::WinitPlugin
and ScheduleRunnerPlugin
.
main_schedule_label: Interned<dyn ScheduleLabel>
The schedule that systems are added to by default.
The schedule that runs the main loop of schedule execution.
This is initially set to Main
.
Implementations§
source§impl App
impl App
sourcepub fn new() -> App
pub fn new() -> App
Creates a new App
with some default structure to enable core engine features.
This is the preferred constructor for most use cases.
Examples found in repository?
More examples
- examples/2d/sprite.rs
- examples/2d/sprite_flipping.rs
- examples/2d/transparency_2d.rs
- examples/3d/3d_scene.rs
- examples/3d/orthographic.rs
- examples/3d/texture.rs
- examples/3d/two_passes.rs
- examples/3d/vertex_colors.rs
- examples/asset/asset_loading.rs
- examples/audio/audio.rs
- examples/reflection/reflection_types.rs
- examples/ui/borders.rs
- examples/input/mouse_grab.rs
- examples/input/touch_input.rs
- examples/input/gamepad_input.rs
- examples/input/gamepad_rumble.rs
- examples/input/mouse_input.rs
- examples/input/touch_input_events.rs
- examples/input/keyboard_input.rs
- examples/input/keyboard_modifiers.rs
- examples/ecs/startup_system.rs
- examples/input/char_input_events.rs
- examples/app/drag_and_drop.rs
- examples/input/mouse_input_events.rs
- examples/input/keyboard_input_events.rs
- examples/2d/mesh2d_manual.rs
- examples/asset/embedded_asset.rs
- examples/shader/shader_instancing.rs
- examples/asset/custom_asset_reader.rs
- examples/input/gamepad_input_events.rs
- examples/reflection/trait_reflection.rs
- examples/ecs/hierarchy.rs
- examples/2d/sprite_tile.rs
- examples/app/without_winit.rs
- examples/transforms/translation.rs
- examples/2d/2d_viewport_to_world.rs
- examples/3d/3d_viewport_to_world.rs
- examples/transforms/3d_rotation.rs
- examples/animation/cubic_curve.rs
- examples/3d/generate_custom_mesh.rs
- examples/3d/lines.rs
- examples/3d/parenting.rs
- examples/ui/render_ui_to_texture.rs
- examples/2d/move_sprite.rs
- examples/app/custom_loop.rs
- examples/shader/animate_shader.rs
- examples/shader/custom_vertex_attribute.rs
- examples/shader/shader_defs.rs
- examples/shader/shader_material.rs
- examples/3d/animated_material.rs
- examples/ecs/system_param.rs
- tests/3d/no_prepass.rs
- examples/ui/transparency_ui.rs
- examples/ui/z_index.rs
- examples/2d/bloom_2d.rs
- examples/window/screenshot.rs
- examples/3d/deterministic.rs
- examples/3d/pbr.rs
- examples/audio/audio_control.rs
- examples/app/thread_pool_resources.rs
- examples/reflection/reflection.rs
- examples/ecs/parallel_query.rs
- examples/transforms/scale.rs
- examples/3d/render_to_texture.rs
- examples/3d/split_screen.rs
- examples/3d/3d_shapes.rs
- examples/async_tasks/async_compute.rs
- examples/3d/bloom_3d.rs
- examples/shader/post_processing.rs
- examples/ecs/one_shot_systems.rs
- examples/shader/shader_material_2d.rs
- examples/shader/fallback_image.rs
- examples/3d/transparency_3d.rs
- examples/shader/shader_material_screenspace_texture.rs
- examples/audio/spatial_audio_3d.rs
- examples/3d/lightmaps.rs
- examples/audio/pitch.rs
- examples/ui/text.rs
- examples/time/timers.rs
- examples/async_tasks/external_source_external_thread.rs
- examples/3d/spherical_area_lights.rs
- examples/ui/ui_material.rs
- examples/2d/sprite_sheet.rs
- examples/reflection/generic_reflection.rs
- examples/window/clear_color.rs
- examples/animation/animated_transform.rs
- examples/2d/2d_gizmos.rs
- examples/3d/update_gltf_scene.rs
- examples/2d/text2d.rs
- examples/3d/load_gltf.rs
- examples/ui/size_constraints.rs
- examples/app/log_layers.rs
- examples/ecs/component_change_detection.rs
- examples/asset/asset_decompression.rs
- examples/3d/atmospheric_fog.rs
- examples/3d/anti_aliasing.rs
- examples/shader/array_texture.rs
- examples/shader/texture_binding_array.rs
- examples/ecs/event.rs
- examples/animation/gltf_skinned_mesh.rs
- examples/animation/custom_skinned_mesh.rs
- examples/ui/font_atlas_debug.rs
- examples/2d/pixel_grid_snap.rs
- examples/3d/3d_gizmos.rs
- examples/window/multiple_windows.rs
- examples/shader/extended_material.rs
- examples/3d/spotlight.rs
- examples/ecs/iter_combinations.rs
- examples/3d/ssao.rs
- examples/3d/fog.rs
- examples/audio/decodable.rs
- examples/2d/sprite_slice.rs
- examples/ui/ui.rs
- examples/ui/button.rs
- examples/ui/ui_texture_slice.rs
- examples/ui/overflow.rs
- examples/app/no_renderer.rs
- examples/audio/spatial_audio_2d.rs
- examples/ui/relative_cursor_position.rs
- examples/app/plugin.rs
- examples/animation/animated_fox.rs
- examples/transforms/transform.rs
- examples/ecs/custom_query_param.rs
- examples/scene/scene.rs
- examples/asset/custom_asset.rs
- examples/3d/skybox.rs
- examples/2d/texture_atlas.rs
- examples/ui/grid.rs
- examples/3d/lighting.rs
- examples/input/text_input.rs
- examples/ui/flex_layout.rs
- examples/window/window_resizing.rs
- examples/games/contributors.rs
- examples/time/time.rs
- examples/2d/rotation.rs
- examples/3d/shadow_biases.rs
- examples/app/return_after_run.rs
- examples/ecs/fixed_timestep.rs
- examples/ui/text_debug.rs
- examples/3d/parallax_mapping.rs
- examples/app/headless.rs
- examples/3d/shadow_caster_receiver.rs
- examples/ui/display_and_visibility.rs
- tests/window/minimising.rs
- examples/window/scale_factor_override.rs
- examples/animation/morph_targets.rs
- examples/app/logs.rs
- examples/diagnostics/custom_diagnostic.rs
- examples/3d/blend_modes.rs
- examples/3d/deferred_rendering.rs
- examples/shader/compute_shader_game_of_life.rs
- examples/games/game_menu.rs
- examples/2d/custom_gltf_vertex_attribute.rs
- examples/ui/ui_scaling.rs
- examples/ui/ui_texture_atlas.rs
- examples/ui/overflow_debug.rs
- examples/3d/reflection_probes.rs
- examples/ui/viewport_debug.rs
- examples/ecs/generic_system.rs
- examples/ecs/system_piping.rs
- examples/app/plugin_group.rs
- examples/ui/window_fallthrough.rs
- examples/3d/transmission.rs
- examples/window/transparent_window.rs
- examples/diagnostics/log_diagnostics.rs
- examples/stress_tests/text_pipeline.rs
- examples/ecs/removal_detection.rs
- examples/stress_tests/many_glyphs.rs
- examples/ecs/send_and_receive_events.rs
- examples/ui/text_wrap_debug.rs
- tests/window/resizing.rs
- examples/2d/bounding_2d.rs
- examples/stress_tests/many_lights.rs
- examples/stress_tests/many_gizmos.rs
- examples/3d/tonemapping.rs
- examples/shader/shader_prepass.rs
- examples/games/breakout.rs
- examples/time/virtual_time.rs
- examples/stress_tests/many_animated_sprites.rs
- examples/stress_tests/many_cubes.rs
- examples/stress_tests/transform_hierarchy.rs
- examples/games/alien_cake_addict.rs
- examples/stress_tests/many_sprites.rs
- examples/ecs/state.rs
- examples/window/low_power.rs
- examples/3d/wireframe.rs
- examples/stress_tests/many_foxes.rs
- examples/stress_tests/many_buttons.rs
- examples/math/render_primitives.rs
- examples/stress_tests/bevymark.rs
- examples/ecs/system_closure.rs
- examples/window/window_settings.rs
- examples/3d/irradiance_volumes.rs
- examples/ecs/nondeterministic_system_order.rs
- examples/ecs/custom_schedule.rs
- examples/ecs/run_conditions.rs
- examples/ecs/ecs_guide.rs
- examples/ecs/system_stepping.rs
sourcepub fn empty() -> App
pub fn empty() -> App
Creates a new empty App
with minimal default configuration.
This constructor should be used if you wish to provide custom scheduling, exit handling, cleanup, etc.
sourcepub fn update(&mut self)
pub fn update(&mut self)
Advances the execution of the Schedule
by one cycle.
This method also updates sub apps.
See insert_sub_app
for more details.
The schedule run by this method is determined by the main_schedule_label
field.
By default this is Main
.
§Panics
The active schedule of the app must be set before this method is called.
Examples found in repository?
More examples
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
fn main() {
let mut app = App::new();
app.add_plugins(MinimalPlugins)
.add_event::<DebugEvent>()
.add_event::<A>()
.add_event::<B>()
.add_systems(Update, read_and_write_different_event_types)
.add_systems(
Update,
(
send_events,
debug_events,
send_and_receive_param_set,
debug_events,
send_and_receive_manual_event_reader,
debug_events,
)
.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 event queue properly.
app.update();
}
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
fn runner(mut app: App) {
banner();
help();
let stdin = io::stdin();
for line in stdin.lock().lines() {
if let Err(err) = line {
println!("read err: {:#}", err);
break;
}
match line.unwrap().as_str() {
"" => {
app.update();
}
"f" => {
println!("FAST: setting relative speed to 2x");
app.world
.resource_mut::<Time<Virtual>>()
.set_relative_speed(2.0);
}
"n" => {
println!("NORMAL: setting relative speed to 1x");
app.world
.resource_mut::<Time<Virtual>>()
.set_relative_speed(1.0);
}
"s" => {
println!("SLOW: setting relative speed to 0.5x");
app.world
.resource_mut::<Time<Virtual>>()
.set_relative_speed(0.5);
}
"p" => {
println!("PAUSE: pausing virtual clock");
app.world.resource_mut::<Time<Virtual>>().pause();
}
"u" => {
println!("UNPAUSE: resuming virtual clock");
app.world.resource_mut::<Time<Virtual>>().unpause();
}
"q" => {
println!("QUITTING!");
break;
}
_ => {
help();
}
}
}
}
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
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.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.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.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.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.resource_mut::<Stepping>();
stepping.always_run(Update, update_system_two);
for _ in 0..3 {
let mut stepping = app.world.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.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_three().
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.resource_mut::<Stepping>();
stepping.set_breakpoint(Update, update_system_two);
stepping.continue_frame();
app.update();
let mut stepping = app.world.resource_mut::<Stepping>();
stepping.step_frame();
app.update();
let mut stepping = app.world.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.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.resource_mut::<Stepping>();
stepping.disable();
app.update();
}
sourcepub fn run(&mut self)
pub fn run(&mut self)
Starts the application by calling the app’s runner function.
Finalizes the App
configuration. For general usage, see the example on the item
level documentation.
§run()
might not return
Calls to App::run()
will never return on iOS and Web.
In simple and headless applications, one can expect that execution will
proceed, normally, after calling run()
but this is not the case for
windowed applications.
Windowed apps are typically driven by an event loop or message loop and some window-manager APIs expect programs to terminate when their primary window is closed and that event loop terminates – behavior of processes that do not is often platform dependent or undocumented.
By default, Bevy uses the winit
crate for window creation.
§Panics
Panics if called from Plugin::build()
, because it would prevent other plugins to properly build.
Examples found in repository?
More examples
- examples/2d/sprite.rs
- examples/2d/sprite_flipping.rs
- examples/2d/transparency_2d.rs
- examples/3d/3d_scene.rs
- examples/3d/orthographic.rs
- examples/3d/texture.rs
- examples/3d/two_passes.rs
- examples/3d/vertex_colors.rs
- examples/asset/asset_loading.rs
- examples/audio/audio.rs
- examples/reflection/reflection_types.rs
- examples/ui/borders.rs
- examples/input/mouse_grab.rs
- examples/input/touch_input.rs
- examples/input/gamepad_input.rs
- examples/input/gamepad_rumble.rs
- examples/input/mouse_input.rs
- examples/input/touch_input_events.rs
- examples/input/keyboard_input.rs
- examples/input/keyboard_modifiers.rs
- examples/ecs/startup_system.rs
- examples/input/char_input_events.rs
- examples/app/drag_and_drop.rs
- examples/input/mouse_input_events.rs
- examples/input/keyboard_input_events.rs
- examples/2d/mesh2d_manual.rs
- examples/asset/embedded_asset.rs
- examples/shader/shader_instancing.rs
- examples/asset/custom_asset_reader.rs
- examples/input/gamepad_input_events.rs
- examples/reflection/trait_reflection.rs
- examples/ecs/hierarchy.rs
- examples/2d/sprite_tile.rs
- examples/app/without_winit.rs
- examples/transforms/translation.rs
- examples/2d/2d_viewport_to_world.rs
- examples/3d/3d_viewport_to_world.rs
- examples/transforms/3d_rotation.rs
- examples/animation/cubic_curve.rs
- examples/3d/generate_custom_mesh.rs
- examples/3d/lines.rs
- examples/3d/parenting.rs
- examples/ui/render_ui_to_texture.rs
- examples/2d/move_sprite.rs
- examples/app/custom_loop.rs
- examples/shader/animate_shader.rs
- examples/shader/custom_vertex_attribute.rs
- examples/shader/shader_defs.rs
- examples/shader/shader_material.rs
- examples/3d/animated_material.rs
- examples/ecs/system_param.rs
- tests/3d/no_prepass.rs
- examples/ui/transparency_ui.rs
- examples/ui/z_index.rs
- examples/2d/bloom_2d.rs
- examples/window/screenshot.rs
- examples/3d/deterministic.rs
- examples/3d/pbr.rs
- examples/audio/audio_control.rs
- examples/app/thread_pool_resources.rs
- examples/reflection/reflection.rs
- examples/ecs/parallel_query.rs
- examples/transforms/scale.rs
- examples/3d/render_to_texture.rs
- examples/3d/split_screen.rs
- examples/3d/3d_shapes.rs
- examples/async_tasks/async_compute.rs
- examples/3d/bloom_3d.rs
- examples/shader/post_processing.rs
- examples/ecs/one_shot_systems.rs
- examples/shader/shader_material_2d.rs
- examples/shader/fallback_image.rs
- examples/3d/transparency_3d.rs
- examples/shader/shader_material_screenspace_texture.rs
- examples/audio/spatial_audio_3d.rs
- examples/3d/lightmaps.rs
- examples/audio/pitch.rs
- examples/ui/text.rs
- examples/time/timers.rs
- examples/async_tasks/external_source_external_thread.rs
- examples/3d/spherical_area_lights.rs
- examples/ui/ui_material.rs
- examples/2d/sprite_sheet.rs
- examples/reflection/generic_reflection.rs
- examples/window/clear_color.rs
- examples/animation/animated_transform.rs
- examples/2d/2d_gizmos.rs
- examples/3d/update_gltf_scene.rs
- examples/2d/text2d.rs
- examples/3d/load_gltf.rs
- examples/ui/size_constraints.rs
- examples/app/log_layers.rs
- examples/ecs/component_change_detection.rs
- examples/asset/asset_decompression.rs
- examples/3d/atmospheric_fog.rs
- examples/3d/anti_aliasing.rs
- examples/shader/array_texture.rs
- examples/shader/texture_binding_array.rs
- examples/ecs/event.rs
- examples/animation/gltf_skinned_mesh.rs
- examples/animation/custom_skinned_mesh.rs
- examples/ui/font_atlas_debug.rs
- examples/2d/pixel_grid_snap.rs
- examples/3d/3d_gizmos.rs
- examples/window/multiple_windows.rs
- examples/shader/extended_material.rs
- examples/3d/spotlight.rs
- examples/ecs/iter_combinations.rs
- examples/3d/ssao.rs
- examples/3d/fog.rs
- examples/audio/decodable.rs
- examples/2d/sprite_slice.rs
- examples/ui/ui.rs
- examples/ui/button.rs
- examples/ui/ui_texture_slice.rs
- examples/ui/overflow.rs
- examples/app/no_renderer.rs
- examples/audio/spatial_audio_2d.rs
- examples/ui/relative_cursor_position.rs
- examples/app/plugin.rs
- examples/animation/animated_fox.rs
- examples/transforms/transform.rs
- examples/ecs/custom_query_param.rs
- examples/scene/scene.rs
- examples/asset/custom_asset.rs
- examples/3d/skybox.rs
- examples/2d/texture_atlas.rs
- examples/ui/grid.rs
- examples/3d/lighting.rs
- examples/input/text_input.rs
- examples/ui/flex_layout.rs
- examples/window/window_resizing.rs
- examples/games/contributors.rs
- examples/time/time.rs
- examples/2d/rotation.rs
- examples/3d/shadow_biases.rs
- examples/app/return_after_run.rs
- examples/ecs/fixed_timestep.rs
- examples/ui/text_debug.rs
- examples/3d/parallax_mapping.rs
- examples/app/headless.rs
- examples/3d/shadow_caster_receiver.rs
- examples/ui/display_and_visibility.rs
- tests/window/minimising.rs
- examples/window/scale_factor_override.rs
- examples/animation/morph_targets.rs
- examples/app/logs.rs
- examples/diagnostics/custom_diagnostic.rs
- examples/3d/blend_modes.rs
- examples/3d/deferred_rendering.rs
- examples/shader/compute_shader_game_of_life.rs
- examples/games/game_menu.rs
- examples/2d/custom_gltf_vertex_attribute.rs
- examples/ui/ui_scaling.rs
- examples/ui/ui_texture_atlas.rs
- examples/ui/overflow_debug.rs
- examples/3d/reflection_probes.rs
- examples/ui/viewport_debug.rs
- examples/ecs/generic_system.rs
- examples/ecs/system_piping.rs
- examples/app/plugin_group.rs
- examples/ui/window_fallthrough.rs
- examples/3d/transmission.rs
- examples/window/transparent_window.rs
- examples/diagnostics/log_diagnostics.rs
- examples/stress_tests/text_pipeline.rs
- examples/ecs/removal_detection.rs
- examples/stress_tests/many_glyphs.rs
- examples/ui/text_wrap_debug.rs
- tests/window/resizing.rs
- examples/2d/bounding_2d.rs
- examples/stress_tests/many_lights.rs
- examples/stress_tests/many_gizmos.rs
- examples/3d/tonemapping.rs
- examples/shader/shader_prepass.rs
- examples/games/breakout.rs
- examples/time/virtual_time.rs
- examples/stress_tests/many_animated_sprites.rs
- examples/stress_tests/many_cubes.rs
- examples/stress_tests/transform_hierarchy.rs
- examples/games/alien_cake_addict.rs
- examples/stress_tests/many_sprites.rs
- examples/ecs/state.rs
- examples/window/low_power.rs
- examples/3d/wireframe.rs
- examples/stress_tests/many_foxes.rs
- examples/stress_tests/many_buttons.rs
- examples/math/render_primitives.rs
- examples/stress_tests/bevymark.rs
- examples/ecs/system_closure.rs
- examples/window/window_settings.rs
- examples/3d/irradiance_volumes.rs
- examples/ecs/nondeterministic_system_order.rs
- examples/ecs/custom_schedule.rs
- examples/ecs/run_conditions.rs
- examples/ecs/ecs_guide.rs
sourcepub fn plugins_state(&self) -> PluginsState
pub fn plugins_state(&self) -> PluginsState
Check the state of all plugins already added to this app. This is usually called by the
event loop, but can be useful for situations where you want to use App::update
sourcepub fn finish(&mut self)
pub fn finish(&mut self)
Run Plugin::finish
for each plugin. This is usually called by the event loop once all
plugins are ready, but can be useful for situations where you want to use App::update
.
sourcepub fn cleanup(&mut self)
pub fn cleanup(&mut self)
Run Plugin::cleanup
for each plugin. This is usually called by the event loop after
App::finish
, but can be useful for situations where you want to use App::update
.
sourcepub fn init_state<S>(&mut self) -> &mut App
pub fn init_state<S>(&mut self) -> &mut App
Initializes a State
with standard starting values.
If the State
already exists, nothing happens.
Adds State<S>
and NextState<S>
resources, OnEnter
and OnExit
schedules
for each state variant (if they don’t already exist), an instance of apply_state_transition::<S>
in
StateTransition
so that transitions happen before Update
and
a instance of run_enter_schedule::<S>
in StateTransition
with a
run_once
condition to run the on enter schedule of the
initial state.
If you would like to control how other systems run based on the current state,
you can emulate this behavior using the in_state
Condition
.
Note that you can also apply state transitions at other points in the schedule
by adding the apply_state_transition
system manually.
Examples found in repository?
More examples
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// Insert as resource the initial value for the settings resources
.insert_resource(DisplayQuality::Medium)
.insert_resource(Volume(7))
// Declare the game state, whose starting value is determined by the `Default` trait
.init_state::<GameState>()
.add_systems(Startup, setup)
// Adds the plugins for each state
.add_plugins((splash::splash_plugin, menu::menu_plugin, game::game_plugin))
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2dBundle::default());
}
mod splash {
use bevy::prelude::*;
use super::{despawn_screen, GameState};
// This plugin will display a splash screen with Bevy logo for 1 second before switching to the menu
pub fn splash_plugin(app: &mut App) {
// As this plugin is managing the splash screen, it will focus on the state `GameState::Splash`
app
// When entering the state, spawn everything needed for this screen
.add_systems(OnEnter(GameState::Splash), splash_setup)
// While in this state, run the `countdown` system
.add_systems(Update, countdown.run_if(in_state(GameState::Splash)))
// When exiting the state, despawn everything that was spawned for this screen
.add_systems(OnExit(GameState::Splash), despawn_screen::<OnSplashScreen>);
}
// Tag component used to tag entities added on the splash screen
#[derive(Component)]
struct OnSplashScreen;
// Newtype to use a `Timer` for this screen as a resource
#[derive(Resource, Deref, DerefMut)]
struct SplashTimer(Timer);
fn splash_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let icon = asset_server.load("branding/icon.png");
// Display the logo
commands
.spawn((
NodeBundle {
style: Style {
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
width: Val::Percent(100.0),
height: Val::Percent(100.0),
..default()
},
..default()
},
OnSplashScreen,
))
.with_children(|parent| {
parent.spawn(ImageBundle {
style: Style {
// This will set the logo to be 200px wide, and auto adjust its height
width: Val::Px(200.0),
..default()
},
image: UiImage::new(icon),
..default()
});
});
// Insert the timer as a resource
commands.insert_resource(SplashTimer(Timer::from_seconds(1.0, TimerMode::Once)));
}
// Tick the timer, and change state when finished
fn countdown(
mut game_state: ResMut<NextState<GameState>>,
time: Res<Time>,
mut timer: ResMut<SplashTimer>,
) {
if timer.tick(time.delta()).finished() {
game_state.set(GameState::Menu);
}
}
}
mod game {
use bevy::prelude::*;
use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};
// This plugin will contain the game. In this case, it's just be a screen that will
// display the current settings for 5 seconds before returning to the menu
pub fn game_plugin(app: &mut App) {
app.add_systems(OnEnter(GameState::Game), game_setup)
.add_systems(Update, game.run_if(in_state(GameState::Game)))
.add_systems(OnExit(GameState::Game), despawn_screen::<OnGameScreen>);
}
// Tag component used to tag entities added on the game screen
#[derive(Component)]
struct OnGameScreen;
#[derive(Resource, Deref, DerefMut)]
struct GameTimer(Timer);
fn game_setup(
mut commands: Commands,
display_quality: Res<DisplayQuality>,
volume: Res<Volume>,
) {
commands
.spawn((
NodeBundle {
style: Style {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
// center children
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
..default()
},
OnGameScreen,
))
.with_children(|parent| {
// First create a `NodeBundle` for centering what we want to display
parent
.spawn(NodeBundle {
style: Style {
// This will display its children in a column, from top to bottom
flex_direction: FlexDirection::Column,
// `align_items` will align children on the cross axis. Here the main axis is
// vertical (column), so the cross axis is horizontal. This will center the
// children
align_items: AlignItems::Center,
..default()
},
background_color: Color::BLACK.into(),
..default()
})
.with_children(|parent| {
// Display two lines of text, the second one with the current settings
parent.spawn(
TextBundle::from_section(
"Will be back to the menu shortly...",
TextStyle {
font_size: 80.0,
color: TEXT_COLOR,
..default()
},
)
.with_style(Style {
margin: UiRect::all(Val::Px(50.0)),
..default()
}),
);
parent.spawn(
TextBundle::from_sections([
TextSection::new(
format!("quality: {:?}", *display_quality),
TextStyle {
font_size: 60.0,
color: Color::BLUE,
..default()
},
),
TextSection::new(
" - ",
TextStyle {
font_size: 60.0,
color: TEXT_COLOR,
..default()
},
),
TextSection::new(
format!("volume: {:?}", *volume),
TextStyle {
font_size: 60.0,
color: Color::GREEN,
..default()
},
),
])
.with_style(Style {
margin: UiRect::all(Val::Px(50.0)),
..default()
}),
);
});
});
// Spawn a 5 seconds timer to trigger going back to the menu
commands.insert_resource(GameTimer(Timer::from_seconds(5.0, TimerMode::Once)));
}
// Tick the timer, and change state when finished
fn game(
time: Res<Time>,
mut game_state: ResMut<NextState<GameState>>,
mut timer: ResMut<GameTimer>,
) {
if timer.tick(time.delta()).finished() {
game_state.set(GameState::Menu);
}
}
}
mod menu {
use bevy::{app::AppExit, prelude::*};
use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};
// This plugin manages the menu, with 5 different screens:
// - a main menu with "New Game", "Settings", "Quit"
// - a settings menu with two submenus and a back button
// - two settings screen with a setting that can be set and a back button
pub fn menu_plugin(app: &mut App) {
app
// At start, the menu is not enabled. This will be changed in `menu_setup` when
// entering the `GameState::Menu` state.
// Current screen in the menu is handled by an independent state from `GameState`
.init_state::<MenuState>()
.add_systems(OnEnter(GameState::Menu), menu_setup)
// Systems to handle the main menu screen
.add_systems(OnEnter(MenuState::Main), main_menu_setup)
.add_systems(OnExit(MenuState::Main), despawn_screen::<OnMainMenuScreen>)
// Systems to handle the settings menu screen
.add_systems(OnEnter(MenuState::Settings), settings_menu_setup)
.add_systems(
OnExit(MenuState::Settings),
despawn_screen::<OnSettingsMenuScreen>,
)
// Systems to handle the display settings screen
.add_systems(
OnEnter(MenuState::SettingsDisplay),
display_settings_menu_setup,
)
.add_systems(
Update,
(setting_button::<DisplayQuality>.run_if(in_state(MenuState::SettingsDisplay)),),
)
.add_systems(
OnExit(MenuState::SettingsDisplay),
despawn_screen::<OnDisplaySettingsMenuScreen>,
)
// Systems to handle the sound settings screen
.add_systems(OnEnter(MenuState::SettingsSound), sound_settings_menu_setup)
.add_systems(
Update,
setting_button::<Volume>.run_if(in_state(MenuState::SettingsSound)),
)
.add_systems(
OnExit(MenuState::SettingsSound),
despawn_screen::<OnSoundSettingsMenuScreen>,
)
// Common systems to all screens that handles buttons behavior
.add_systems(
Update,
(menu_action, button_system).run_if(in_state(GameState::Menu)),
);
}
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
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();
}
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_state::<Test>()
.add_systems(Startup, setup)
.add_systems(
Update,
(update_text, spin, update_volumes, update_test_state),
)
.add_systems(
PostUpdate,
(
render_shapes,
(
aabb_intersection_system.run_if(in_state(Test::AabbSweep)),
circle_intersection_system.run_if(in_state(Test::CircleSweep)),
ray_cast_system.run_if(in_state(Test::RayCast)),
aabb_cast_system.run_if(in_state(Test::AabbCast)),
bounding_circle_cast_system.run_if(in_state(Test::CircleCast)),
),
render_volumes,
)
.chain(),
)
.run();
}
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_resource::<Game>()
.insert_resource(BonusSpawnTimer(Timer::from_seconds(
5.0,
TimerMode::Repeating,
)))
.init_state::<GameState>()
.add_systems(Startup, setup_cameras)
.add_systems(OnEnter(GameState::Playing), setup)
.add_systems(
Update,
(
move_player,
focus_camera,
rotate_bonus,
scoreboard_system,
spawn_bonus,
)
.run_if(in_state(GameState::Playing)),
)
.add_systems(OnExit(GameState::Playing), teardown)
.add_systems(OnEnter(GameState::GameOver), display_score)
.add_systems(
Update,
(
gameover_keyboard.run_if(in_state(GameState::GameOver)),
bevy::window::close_on_esc,
),
)
.add_systems(OnExit(GameState::GameOver), teardown)
.run();
}
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_state::<AppState>() // Alternatively we could use .insert_state(AppState::Menu)
.add_systems(Startup, setup)
// This system runs when we enter `AppState::Menu`, during the `StateTransition` schedule.
// All systems from the exit schedule of the state we're leaving are run first,
// and then all systems from the enter schedule of the state we're entering are run second.
.add_systems(OnEnter(AppState::Menu), setup_menu)
// By contrast, update systems are stored in the `Update` schedule. They simply
// check the value of the `State<T>` resource to see if they should run each frame.
.add_systems(Update, menu.run_if(in_state(AppState::Menu)))
.add_systems(OnExit(AppState::Menu), cleanup_menu)
.add_systems(OnEnter(AppState::InGame), setup_game)
.add_systems(
Update,
(movement, change_color).run_if(in_state(AppState::InGame)),
)
.add_systems(Update, log_transitions)
.run();
}
sourcepub fn insert_state<S>(&mut self, state: S) -> &mut Appwhere
S: States,
pub fn insert_state<S>(&mut self, state: S) -> &mut Appwhere
S: States,
Inserts a specific State
to the current App
and
overrides any State
previously added of the same type.
Adds State<S>
and NextState<S>
resources, OnEnter
and OnExit
schedules
for each state variant (if they don’t already exist), an instance of apply_state_transition::<S>
in
StateTransition
so that transitions happen before Update
and
a instance of run_enter_schedule::<S>
in StateTransition
with a
run_once
condition to run the on enter schedule of the
initial state.
If you would like to control how other systems run based on the current state,
you can emulate this behavior using the in_state
Condition
.
Note that you can also apply state transitions at other points in the schedule
by adding the apply_state_transition
system manually.
sourcepub fn add_systems<M>(
&mut self,
schedule: impl ScheduleLabel,
systems: impl IntoSystemConfigs<M>
) -> &mut App
pub fn add_systems<M>( &mut self, schedule: impl ScheduleLabel, systems: impl IntoSystemConfigs<M> ) -> &mut App
Adds a system to the given schedule in this app’s Schedules
.
§Examples
app.add_systems(Update, (system_a, system_b, system_c));
app.add_systems(Update, (system_a, system_b).run_if(should_run));
Examples found in repository?
More examples
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
fn build(&self, app: &mut App) {
app.add_systems(Update, print_hello_system);
}
}
fn print_hello_system() {
info!("hello");
}
struct PrintWorldPlugin;
impl Plugin for PrintWorldPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, print_world_system);
}
- examples/2d/sprite.rs
- examples/2d/sprite_flipping.rs
- examples/2d/transparency_2d.rs
- examples/3d/3d_scene.rs
- examples/3d/orthographic.rs
- examples/3d/texture.rs
- examples/3d/two_passes.rs
- examples/3d/vertex_colors.rs
- examples/asset/asset_loading.rs
- examples/audio/audio.rs
- examples/reflection/reflection_types.rs
- examples/ui/borders.rs
- examples/input/mouse_grab.rs
- examples/input/touch_input.rs
- examples/input/gamepad_input.rs
- examples/input/gamepad_rumble.rs
- examples/input/mouse_input.rs
- examples/input/touch_input_events.rs
- examples/input/keyboard_input.rs
- examples/input/keyboard_modifiers.rs
- examples/ecs/startup_system.rs
- examples/input/char_input_events.rs
- examples/app/drag_and_drop.rs
- examples/input/mouse_input_events.rs
- examples/input/keyboard_input_events.rs
- examples/2d/mesh2d_manual.rs
- examples/asset/embedded_asset.rs
- examples/shader/shader_instancing.rs
- examples/asset/custom_asset_reader.rs
- examples/input/gamepad_input_events.rs
- examples/reflection/trait_reflection.rs
- examples/ecs/hierarchy.rs
- examples/2d/sprite_tile.rs
- examples/app/without_winit.rs
- examples/transforms/translation.rs
- examples/2d/2d_viewport_to_world.rs
- examples/3d/3d_viewport_to_world.rs
- examples/transforms/3d_rotation.rs
- examples/animation/cubic_curve.rs
- examples/3d/generate_custom_mesh.rs
- examples/3d/lines.rs
- examples/3d/parenting.rs
- examples/ui/render_ui_to_texture.rs
- examples/2d/move_sprite.rs
- examples/app/custom_loop.rs
- examples/shader/animate_shader.rs
- examples/shader/custom_vertex_attribute.rs
- examples/shader/shader_defs.rs
- examples/shader/shader_material.rs
- examples/3d/animated_material.rs
- examples/ecs/system_param.rs
- examples/ui/transparency_ui.rs
- examples/ui/z_index.rs
- examples/2d/bloom_2d.rs
- examples/window/screenshot.rs
- examples/3d/deterministic.rs
- examples/3d/pbr.rs
- examples/audio/audio_control.rs
- examples/reflection/reflection.rs
- examples/ecs/parallel_query.rs
- examples/transforms/scale.rs
- examples/3d/render_to_texture.rs
- examples/3d/split_screen.rs
- examples/3d/3d_shapes.rs
- examples/async_tasks/async_compute.rs
- examples/3d/bloom_3d.rs
- examples/shader/post_processing.rs
- examples/ecs/one_shot_systems.rs
- examples/shader/shader_material_2d.rs
- examples/shader/fallback_image.rs
- examples/3d/transparency_3d.rs
- examples/shader/shader_material_screenspace_texture.rs
- examples/audio/spatial_audio_3d.rs
- examples/3d/lightmaps.rs
- examples/audio/pitch.rs
- examples/ui/text.rs
- examples/time/timers.rs
- examples/async_tasks/external_source_external_thread.rs
- examples/3d/spherical_area_lights.rs
- examples/ui/ui_material.rs
- examples/2d/sprite_sheet.rs
- examples/reflection/generic_reflection.rs
- examples/window/clear_color.rs
- examples/animation/animated_transform.rs
- examples/2d/2d_gizmos.rs
- examples/3d/update_gltf_scene.rs
- examples/2d/text2d.rs
- examples/3d/load_gltf.rs
- examples/ui/size_constraints.rs
- examples/app/log_layers.rs
- examples/ecs/component_change_detection.rs
- examples/asset/asset_decompression.rs
- examples/3d/atmospheric_fog.rs
- examples/3d/anti_aliasing.rs
- examples/shader/array_texture.rs
- examples/shader/texture_binding_array.rs
- examples/ecs/event.rs
- examples/animation/gltf_skinned_mesh.rs
- examples/animation/custom_skinned_mesh.rs
- examples/ui/font_atlas_debug.rs
- examples/2d/pixel_grid_snap.rs
- examples/3d/3d_gizmos.rs
- examples/window/multiple_windows.rs
- examples/shader/extended_material.rs
- examples/3d/spotlight.rs
- examples/ecs/iter_combinations.rs
- examples/3d/ssao.rs
- examples/3d/fog.rs
- examples/app/plugin.rs
- examples/audio/decodable.rs
- examples/2d/sprite_slice.rs
- examples/ui/ui.rs
- examples/ui/button.rs
- examples/ui/ui_texture_slice.rs
- examples/ui/overflow.rs
- examples/audio/spatial_audio_2d.rs
- examples/ui/relative_cursor_position.rs
- examples/animation/animated_fox.rs
- examples/transforms/transform.rs
- examples/ecs/custom_query_param.rs
- examples/scene/scene.rs
- examples/asset/custom_asset.rs
- examples/3d/skybox.rs
- examples/2d/texture_atlas.rs
- examples/ui/grid.rs
- examples/3d/lighting.rs
- examples/input/text_input.rs
- examples/ui/flex_layout.rs
- examples/window/window_resizing.rs
- examples/games/contributors.rs
- examples/time/time.rs
- examples/2d/rotation.rs
- examples/3d/shadow_biases.rs
- examples/app/return_after_run.rs
- examples/ecs/fixed_timestep.rs
- examples/ui/text_debug.rs
- examples/3d/parallax_mapping.rs
- examples/app/headless.rs
- examples/3d/shadow_caster_receiver.rs
- examples/ui/display_and_visibility.rs
- tests/window/minimising.rs
- examples/window/scale_factor_override.rs
- examples/animation/morph_targets.rs
- examples/app/logs.rs
- examples/diagnostics/custom_diagnostic.rs
- examples/3d/blend_modes.rs
- examples/3d/deferred_rendering.rs
- examples/shader/compute_shader_game_of_life.rs
- examples/games/game_menu.rs
- examples/2d/custom_gltf_vertex_attribute.rs
- examples/ui/ui_scaling.rs
- examples/ui/ui_texture_atlas.rs
- examples/ui/overflow_debug.rs
- examples/3d/reflection_probes.rs
- examples/ui/viewport_debug.rs
- examples/ecs/generic_system.rs
- examples/ecs/system_piping.rs
- examples/ui/window_fallthrough.rs
- examples/3d/transmission.rs
- examples/window/transparent_window.rs
- examples/stress_tests/text_pipeline.rs
- examples/ecs/removal_detection.rs
- examples/stress_tests/many_glyphs.rs
- examples/ecs/send_and_receive_events.rs
- examples/ui/text_wrap_debug.rs
- tests/window/resizing.rs
- examples/2d/bounding_2d.rs
- examples/stress_tests/many_lights.rs
- examples/stress_tests/many_gizmos.rs
- examples/3d/tonemapping.rs
- examples/shader/shader_prepass.rs
- examples/games/breakout.rs
- examples/time/virtual_time.rs
- examples/stress_tests/many_animated_sprites.rs
- examples/stress_tests/many_cubes.rs
- examples/stress_tests/transform_hierarchy.rs
- examples/games/alien_cake_addict.rs
- examples/stress_tests/many_sprites.rs
- examples/ecs/state.rs
- examples/games/stepping.rs
- examples/window/low_power.rs
- examples/3d/wireframe.rs
- examples/stress_tests/many_foxes.rs
- examples/stress_tests/many_buttons.rs
- examples/math/render_primitives.rs
- examples/stress_tests/bevymark.rs
- examples/ecs/system_closure.rs
- examples/window/window_settings.rs
- examples/3d/irradiance_volumes.rs
- examples/ecs/nondeterministic_system_order.rs
- examples/ecs/custom_schedule.rs
- examples/ecs/run_conditions.rs
- examples/ecs/ecs_guide.rs
- examples/ecs/system_stepping.rs
sourcepub fn configure_sets(
&mut self,
schedule: impl ScheduleLabel,
sets: impl IntoSystemSetConfigs
) -> &mut App
pub fn configure_sets( &mut self, schedule: impl ScheduleLabel, sets: impl IntoSystemSetConfigs ) -> &mut App
Configures a collection of system sets in the provided schedule, adding any sets that do not exist.
Examples found in repository?
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
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
(MySet::BeforeRound, MySet::Round, MySet::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(MySet::BeforeRound),
// This `Round` system will run after the `BeforeRound` systems thanks to the chained set configuration
score_system.in_set(MySet::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(MySet::AfterRound),
),
)
// This call to run() starts the app we just built!
.run();
}
sourcepub fn add_event<T>(&mut self) -> &mut Appwhere
T: Event,
pub fn add_event<T>(&mut self) -> &mut Appwhere
T: Event,
Setup the application to manage events of type T
.
This is done by adding a Resource
of type Events::<T>
,
and inserting an event_update_system
into First
.
See Events
for defining events.
§Examples
app.add_event::<MyEvent>();
Examples found in repository?
More examples
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
fn main() {
let mut app = App::new();
app.add_plugins(MinimalPlugins)
.add_event::<DebugEvent>()
.add_event::<A>()
.add_event::<B>()
.add_systems(Update, read_and_write_different_event_types)
.add_systems(
Update,
(
send_events,
debug_events,
send_and_receive_param_set,
debug_events,
send_and_receive_manual_event_reader,
debug_events,
)
.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 event queue properly.
app.update();
}
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(
stepping::SteppingPlugin::default()
.add_schedule(Update)
.add_schedule(FixedUpdate)
.at(Val::Percent(35.0), Val::Percent(50.0)),
)
.insert_resource(Scoreboard { score: 0 })
.insert_resource(ClearColor(BACKGROUND_COLOR))
.add_event::<CollisionEvent>()
.add_systems(Startup, setup)
// Add our gameplay simulation systems to the fixed timestep schedule
// which runs at 64 Hz by default
.add_systems(
FixedUpdate,
(
apply_velocity,
move_paddle,
check_for_collisions,
play_collision_sound,
)
// `chain`ing systems together runs them in order
.chain(),
)
.add_systems(Update, (update_scoreboard, bevy::window::close_on_esc))
.run();
}
sourcepub fn insert_resource<R>(&mut self, resource: R) -> &mut Appwhere
R: Resource,
pub fn insert_resource<R>(&mut self, resource: R) -> &mut Appwhere
R: Resource,
Inserts a Resource
to the current App
and overwrites any Resource
previously added of the same type.
A Resource
in Bevy represents globally unique data. Resource
s must be added to Bevy apps
before using them. This happens with insert_resource
.
See init_resource
for Resource
s that implement Default
or FromWorld
.
§Examples
#[derive(Resource)]
struct MyCounter {
counter: usize,
}
App::new()
.insert_resource(MyCounter { counter: 0 });
Examples found in repository?
More examples
- examples/3d/spherical_area_lights.rs
- examples/window/clear_color.rs
- examples/animation/animated_transform.rs
- examples/3d/update_gltf_scene.rs
- examples/3d/load_gltf.rs
- examples/3d/anti_aliasing.rs
- examples/animation/gltf_skinned_mesh.rs
- examples/animation/custom_skinned_mesh.rs
- examples/ui/font_atlas_debug.rs
- examples/2d/pixel_grid_snap.rs
- examples/3d/spotlight.rs
- examples/ecs/iter_combinations.rs
- examples/3d/ssao.rs
- examples/3d/fog.rs
- examples/app/plugin.rs
- examples/ui/ui.rs
- examples/ui/button.rs
- examples/ui/ui_texture_slice.rs
- examples/ui/overflow.rs
- examples/ui/relative_cursor_position.rs
- examples/animation/animated_fox.rs
- examples/3d/lighting.rs
- examples/window/window_resizing.rs
- examples/time/time.rs
- examples/2d/rotation.rs
- examples/ecs/fixed_timestep.rs
- examples/3d/parallax_mapping.rs
- examples/ui/display_and_visibility.rs
- examples/animation/morph_targets.rs
- examples/3d/deferred_rendering.rs
- examples/shader/compute_shader_game_of_life.rs
- examples/games/game_menu.rs
- examples/2d/custom_gltf_vertex_attribute.rs
- examples/ui/ui_scaling.rs
- examples/ui/ui_texture_atlas.rs
- examples/ui/overflow_debug.rs
- examples/ui/viewport_debug.rs
- examples/ecs/system_piping.rs
- examples/ui/window_fallthrough.rs
- examples/3d/transmission.rs
- examples/window/transparent_window.rs
- examples/stress_tests/text_pipeline.rs
- examples/stress_tests/many_glyphs.rs
- examples/ui/text_wrap_debug.rs
- tests/window/resizing.rs
- examples/stress_tests/many_lights.rs
- examples/stress_tests/many_gizmos.rs
- examples/3d/tonemapping.rs
- examples/shader/shader_prepass.rs
- examples/games/breakout.rs
- examples/stress_tests/many_animated_sprites.rs
- examples/stress_tests/many_cubes.rs
- examples/stress_tests/transform_hierarchy.rs
- examples/games/alien_cake_addict.rs
- examples/stress_tests/many_sprites.rs
- examples/games/stepping.rs
- examples/window/low_power.rs
- examples/3d/wireframe.rs
- examples/stress_tests/many_foxes.rs
- examples/stress_tests/many_buttons.rs
- examples/stress_tests/bevymark.rs
- examples/3d/irradiance_volumes.rs
- examples/ecs/system_stepping.rs
sourcepub fn insert_non_send_resource<R>(&mut self, resource: R) -> &mut Appwhere
R: 'static,
pub fn insert_non_send_resource<R>(&mut self, resource: R) -> &mut Appwhere
R: 'static,
Inserts a non-send resource to the app.
You usually want to use insert_resource
,
but there are some special cases when a resource cannot be sent across threads.
§Examples
struct MyCounter {
counter: usize,
}
App::new()
.insert_non_send_resource(MyCounter { counter: 0 });
sourcepub fn init_resource<R>(&mut self) -> &mut App
pub fn init_resource<R>(&mut self) -> &mut App
Initialize a Resource
with standard starting values by adding it to the World
.
If the Resource
already exists, nothing happens.
The Resource
must implement the FromWorld
trait.
If the Default
trait is implemented, the FromWorld
trait will use
the Default::default
method to initialize the Resource
.
§Examples
#[derive(Resource)]
struct MyCounter {
counter: usize,
}
impl Default for MyCounter {
fn default() -> MyCounter {
MyCounter {
counter: 100
}
}
}
App::new()
.init_resource::<MyCounter>();
Examples found in repository?
More examples
95 96 97 98 99 100 101 102 103 104 105 106
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();
}
- examples/games/contributors.rs
- examples/shader/shader_instancing.rs
- examples/3d/reflection_probes.rs
- examples/2d/mesh2d_manual.rs
- examples/3d/tonemapping.rs
- examples/games/alien_cake_addict.rs
- examples/3d/irradiance_volumes.rs
- examples/ecs/nondeterministic_system_order.rs
- examples/ecs/run_conditions.rs
- examples/ecs/ecs_guide.rs
sourcepub fn init_non_send_resource<R>(&mut self) -> &mut Appwhere
R: 'static + FromWorld,
pub fn init_non_send_resource<R>(&mut self) -> &mut Appwhere
R: 'static + FromWorld,
sourcepub fn set_runner(
&mut self,
run_fn: impl FnOnce(App) + Send + 'static
) -> &mut App
pub fn set_runner( &mut self, run_fn: impl FnOnce(App) + Send + 'static ) -> &mut App
Sets the function that will be called when the app is run.
The runner function run_fn
is called only once by App::run
. If the
presence of a main loop in the app is desired, it is the responsibility of the runner
function to provide it.
The runner function is usually not set manually, but by Bevy integrated plugins
(e.g. WinitPlugin
).
§Examples
fn my_runner(mut app: App) {
loop {
println!("In main loop");
app.update();
}
}
App::new()
.set_runner(my_runner);
Examples found in repository?
More examples
sourcepub fn is_plugin_added<T>(&self) -> boolwhere
T: Plugin,
pub fn is_plugin_added<T>(&self) -> boolwhere
T: Plugin,
Checks if a Plugin
has already been added.
This can be used by plugins to check if a plugin they depend upon has already been added.
sourcepub fn get_added_plugins<T>(&self) -> Vec<&T>where
T: Plugin,
pub fn get_added_plugins<T>(&self) -> Vec<&T>where
T: Plugin,
Returns a vector of references to any plugins of type T
that have been added.
This can be used to read the settings of any already added plugins.
This vector will be length zero if no plugins of that type have been added.
If multiple copies of the same plugin are added to the App
, they will be listed in insertion order in this vector.
let default_sampler = app.get_added_plugins::<ImagePlugin>()[0].default_sampler;
sourcepub fn add_plugins<M>(&mut self, plugins: impl Plugins<M>) -> &mut App
pub fn add_plugins<M>(&mut self, plugins: impl Plugins<M>) -> &mut App
Adds one or more Plugin
s.
One of Bevy’s core principles is modularity. All Bevy engine features are implemented
as Plugin
s. This includes internal features like the renderer.
Plugin
s can be grouped into a set by using a PluginGroup
.
There are built-in PluginGroup
s that provide core engine functionality.
The PluginGroup
s available by default are DefaultPlugins
and MinimalPlugins
.
To customize the plugins in the group (reorder, disable a plugin, add a new plugin
before / after another plugin), call build()
on the group,
which will convert it to a PluginGroupBuilder
.
You can also specify a group of Plugin
s by using a tuple over Plugin
s and
PluginGroup
s. See Plugins
for more details.
§Examples
App::new()
.add_plugins(MinimalPlugins);
App::new()
.add_plugins((MinimalPlugins, LogPlugin));
§Panics
Panics if one of the plugins was already added to the application.
Examples found in repository?
More examples
- examples/2d/transparency_2d.rs
- examples/3d/3d_scene.rs
- examples/3d/orthographic.rs
- examples/3d/texture.rs
- examples/3d/two_passes.rs
- examples/3d/vertex_colors.rs
- examples/asset/asset_loading.rs
- examples/audio/audio.rs
- examples/reflection/reflection_types.rs
- examples/ui/borders.rs
- examples/input/mouse_grab.rs
- examples/input/touch_input.rs
- examples/input/gamepad_input.rs
- examples/input/gamepad_rumble.rs
- examples/input/mouse_input.rs
- examples/input/touch_input_events.rs
- examples/input/keyboard_input.rs
- examples/input/keyboard_modifiers.rs
- examples/input/char_input_events.rs
- examples/app/drag_and_drop.rs
- examples/input/mouse_input_events.rs
- examples/input/keyboard_input_events.rs
- examples/2d/mesh2d_manual.rs
- examples/asset/embedded_asset.rs
- examples/shader/shader_instancing.rs
- examples/asset/custom_asset_reader.rs
- examples/input/gamepad_input_events.rs
- examples/reflection/trait_reflection.rs
- examples/ecs/hierarchy.rs
- examples/2d/sprite_tile.rs
- examples/app/without_winit.rs
- examples/transforms/translation.rs
- examples/2d/2d_viewport_to_world.rs
- examples/3d/3d_viewport_to_world.rs
- examples/transforms/3d_rotation.rs
- examples/animation/cubic_curve.rs
- examples/3d/generate_custom_mesh.rs
- examples/3d/lines.rs
- examples/3d/parenting.rs
- examples/ui/render_ui_to_texture.rs
- examples/2d/move_sprite.rs
- examples/shader/animate_shader.rs
- examples/shader/custom_vertex_attribute.rs
- examples/shader/shader_defs.rs
- examples/shader/shader_material.rs
- examples/3d/animated_material.rs
- tests/3d/no_prepass.rs
- examples/ui/transparency_ui.rs
- examples/ui/z_index.rs
- examples/2d/bloom_2d.rs
- examples/window/screenshot.rs
- examples/3d/deterministic.rs
- examples/3d/pbr.rs
- examples/audio/audio_control.rs
- examples/app/thread_pool_resources.rs
- examples/reflection/reflection.rs
- examples/ecs/parallel_query.rs
- examples/transforms/scale.rs
- examples/3d/render_to_texture.rs
- examples/3d/split_screen.rs
- examples/3d/3d_shapes.rs
- examples/async_tasks/async_compute.rs
- examples/3d/bloom_3d.rs
- examples/shader/post_processing.rs
- examples/shader/shader_material_2d.rs
- examples/shader/fallback_image.rs
- examples/3d/transparency_3d.rs
- examples/shader/shader_material_screenspace_texture.rs
- examples/audio/spatial_audio_3d.rs
- examples/3d/lightmaps.rs
- examples/audio/pitch.rs
- examples/ui/text.rs
- examples/time/timers.rs
- examples/async_tasks/external_source_external_thread.rs
- examples/3d/spherical_area_lights.rs
- examples/ui/ui_material.rs
- examples/2d/sprite_sheet.rs
- examples/reflection/generic_reflection.rs
- examples/window/clear_color.rs
- examples/animation/animated_transform.rs
- examples/2d/2d_gizmos.rs
- examples/3d/update_gltf_scene.rs
- examples/2d/text2d.rs
- examples/3d/load_gltf.rs
- examples/ui/size_constraints.rs
- examples/app/log_layers.rs
- examples/ecs/component_change_detection.rs
- examples/asset/asset_decompression.rs
- examples/3d/atmospheric_fog.rs
- examples/3d/anti_aliasing.rs
- examples/shader/array_texture.rs
- examples/shader/texture_binding_array.rs
- examples/ecs/event.rs
- examples/animation/gltf_skinned_mesh.rs
- examples/animation/custom_skinned_mesh.rs
- examples/ui/font_atlas_debug.rs
- examples/2d/pixel_grid_snap.rs
- examples/3d/3d_gizmos.rs
- examples/window/multiple_windows.rs
- examples/shader/extended_material.rs
- examples/3d/spotlight.rs
- examples/ecs/iter_combinations.rs
- examples/3d/ssao.rs
- examples/3d/fog.rs
- examples/audio/decodable.rs
- examples/2d/sprite_slice.rs
- examples/ui/ui.rs
- examples/ui/button.rs
- examples/ui/ui_texture_slice.rs
- examples/ui/overflow.rs
- examples/app/no_renderer.rs
- examples/audio/spatial_audio_2d.rs
- examples/ui/relative_cursor_position.rs
- examples/app/plugin.rs
- examples/animation/animated_fox.rs
- examples/transforms/transform.rs
- examples/scene/scene.rs
- examples/asset/custom_asset.rs
- examples/3d/skybox.rs
- examples/2d/texture_atlas.rs
- examples/ui/grid.rs
- examples/3d/lighting.rs
- examples/input/text_input.rs
- examples/ui/flex_layout.rs
- examples/window/window_resizing.rs
- examples/games/contributors.rs
- examples/time/time.rs
- examples/2d/rotation.rs
- examples/3d/shadow_biases.rs
- examples/app/return_after_run.rs
- examples/ecs/fixed_timestep.rs
- examples/ui/text_debug.rs
- examples/3d/parallax_mapping.rs
- examples/app/headless.rs
- examples/3d/shadow_caster_receiver.rs
- examples/ui/display_and_visibility.rs
- tests/window/minimising.rs
- examples/window/scale_factor_override.rs
- examples/animation/morph_targets.rs
- examples/app/logs.rs
- examples/diagnostics/custom_diagnostic.rs
- examples/3d/blend_modes.rs
- examples/3d/deferred_rendering.rs
- examples/shader/compute_shader_game_of_life.rs
- examples/games/game_menu.rs
- examples/2d/custom_gltf_vertex_attribute.rs
- examples/ui/ui_scaling.rs
- examples/ui/ui_texture_atlas.rs
- examples/ui/overflow_debug.rs
- examples/3d/reflection_probes.rs
- examples/ui/viewport_debug.rs
- examples/ecs/generic_system.rs
- examples/ecs/system_piping.rs
- examples/app/plugin_group.rs
- examples/ui/window_fallthrough.rs
- examples/3d/transmission.rs
- examples/window/transparent_window.rs
- examples/diagnostics/log_diagnostics.rs
- examples/stress_tests/text_pipeline.rs
- examples/ecs/removal_detection.rs
- examples/stress_tests/many_glyphs.rs
- examples/ecs/send_and_receive_events.rs
- examples/ui/text_wrap_debug.rs
- tests/window/resizing.rs
- examples/2d/bounding_2d.rs
- examples/stress_tests/many_lights.rs
- examples/stress_tests/many_gizmos.rs
- examples/3d/tonemapping.rs
- examples/shader/shader_prepass.rs
- examples/games/breakout.rs
- examples/time/virtual_time.rs
- examples/stress_tests/many_animated_sprites.rs
- examples/stress_tests/many_cubes.rs
- examples/stress_tests/transform_hierarchy.rs
- examples/games/alien_cake_addict.rs
- examples/stress_tests/many_sprites.rs
- examples/ecs/state.rs
- examples/window/low_power.rs
- examples/3d/wireframe.rs
- examples/stress_tests/many_foxes.rs
- examples/stress_tests/many_buttons.rs
- examples/math/render_primitives.rs
- examples/stress_tests/bevymark.rs
- examples/ecs/system_closure.rs
- examples/window/window_settings.rs
- examples/3d/irradiance_volumes.rs
- examples/ecs/nondeterministic_system_order.rs
- examples/ecs/run_conditions.rs
- examples/ecs/ecs_guide.rs
- examples/ecs/system_stepping.rs
sourcepub fn register_type<T>(&mut self) -> &mut Appwhere
T: GetTypeRegistration,
pub fn register_type<T>(&mut self) -> &mut Appwhere
T: GetTypeRegistration,
Registers the type T
in the TypeRegistry
resource,
adding reflect data as specified in the Reflect
derive:
#[derive(Component, Serialize, Deserialize, Reflect)]
#[reflect(Component, Serialize, Deserialize)] // will register ReflectComponent, ReflectSerialize, ReflectDeserialize
Examples found in repository?
More examples
5 6 7 8 9 10 11 12 13 14 15 16 17
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.register_type::<ComponentA>()
.register_type::<ComponentB>()
.register_type::<ResourceA>()
.add_systems(
Startup,
(save_scene_system, load_scene_system, infotext_system),
)
.add_systems(Update, log_system)
.run();
}
sourcepub fn register_type_data<T, D>(&mut self) -> &mut App
pub fn register_type_data<T, D>(&mut self) -> &mut App
Adds the type data D
to type T
in the TypeRegistry
resource.
Most of the time App::register_type
can be used instead to register a type you derived Reflect
for.
However, in cases where you want to add a piece of type data that was not included in the list of #[reflect(...)]
type data in the derive,
or where the type is generic and cannot register e.g. ReflectSerialize
unconditionally without knowing the specific type parameters,
this method can be used to insert additional type data.
§Example
use bevy_app::App;
use bevy_reflect::{ReflectSerialize, ReflectDeserialize};
App::new()
.register_type::<Option<String>>()
.register_type_data::<Option<String>, ReflectSerialize>()
.register_type_data::<Option<String>, ReflectDeserialize>();
sourcepub fn sub_app_mut(&mut self, label: impl AppLabel) -> &mut App
pub fn sub_app_mut(&mut self, label: impl AppLabel) -> &mut App
Examples found in repository?
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
fn build(&self, app: &mut App) {
app.add_plugins(ExtractComponentPlugin::<InstanceMaterialData>::default());
app.sub_app_mut(RenderApp)
.add_render_command::<Transparent3d, DrawCustom>()
.init_resource::<SpecializedMeshPipelines<CustomPipeline>>()
.add_systems(
Render,
(
queue_custom.in_set(RenderSet::QueueMeshes),
prepare_instance_buffers.in_set(RenderSet::PrepareResources),
),
);
}
fn finish(&self, app: &mut App) {
app.sub_app_mut(RenderApp).init_resource::<CustomPipeline>();
}
More examples
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
fn build(&self, app: &mut App) {
// Extract the game of life image resource from the main world into the render world
// for operation on by the compute shader and display on the sprite.
app.add_plugins(ExtractResourcePlugin::<GameOfLifeImage>::default());
let render_app = app.sub_app_mut(RenderApp);
render_app.add_systems(
Render,
prepare_bind_group.in_set(RenderSet::PrepareBindGroups),
);
let mut render_graph = render_app.world.resource_mut::<RenderGraph>();
render_graph.add_node(GameOfLifeLabel, GameOfLifeNode::default());
render_graph.add_node_edge(GameOfLifeLabel, bevy::render::graph::CameraDriverLabel);
}
fn finish(&self, app: &mut App) {
let render_app = app.sub_app_mut(RenderApp);
render_app.init_resource::<GameOfLifePipeline>();
}
sourcepub fn get_sub_app_mut(
&mut self,
label: impl AppLabel
) -> Result<&mut App, impl AppLabel>
pub fn get_sub_app_mut( &mut self, label: impl AppLabel ) -> Result<&mut App, impl AppLabel>
Retrieves a SubApp
inside this App
with the given label, if it exists. Otherwise returns
an Err
containing the given label.
Examples found in repository?
More examples
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
fn finish(&self, app: &mut App) {
let Ok(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
let render_device = render_app.world.resource::<RenderDevice>();
// Check if the device support the required feature. If not, exit the example.
// In a real application, you should setup a fallback for the missing feature
if !render_device
.features()
.contains(WgpuFeatures::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING)
{
error!(
"Render device doesn't support feature \
SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING, \
which is required for texture binding arrays"
);
exit(1);
}
}
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
fn build(&self, app: &mut App) {
// Load our custom shader
let mut shaders = app.world.resource_mut::<Assets<Shader>>();
shaders.insert(
COLORED_MESH2D_SHADER_HANDLE,
Shader::from_wgsl(COLORED_MESH2D_SHADER, file!()),
);
// Register our custom draw function, and add our render systems
app.get_sub_app_mut(RenderApp)
.unwrap()
.add_render_command::<Transparent2d, DrawColoredMesh2d>()
.init_resource::<SpecializedRenderPipelines<ColoredMesh2dPipeline>>()
.add_systems(
ExtractSchedule,
extract_colored_mesh2d.after(extract_mesh2d),
)
.add_systems(Render, queue_colored_mesh2d.in_set(RenderSet::QueueMeshes));
}
fn finish(&self, app: &mut App) {
// Register our custom pipeline
app.get_sub_app_mut(RenderApp)
.unwrap()
.init_resource::<ColoredMesh2dPipeline>();
}
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
fn build(&self, app: &mut App) {
app.add_plugins((
// The settings will be a component that lives in the main world but will
// be extracted to the render world every frame.
// This makes it possible to control the effect from the main world.
// This plugin will take care of extracting it automatically.
// It's important to derive [`ExtractComponent`] on [`PostProcessingSettings`]
// for this plugin to work correctly.
ExtractComponentPlugin::<PostProcessSettings>::default(),
// The settings will also be the data used in the shader.
// This plugin will prepare the component for the GPU by creating a uniform buffer
// and writing the data to that buffer every frame.
UniformComponentPlugin::<PostProcessSettings>::default(),
));
// We need to get the render app from the main app
let Ok(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app
// Bevy's renderer uses a render graph which is a collection of nodes in a directed acyclic graph.
// It currently runs on each view/camera and executes each node in the specified order.
// It will make sure that any node that needs a dependency from another node
// only runs when that dependency is done.
//
// Each node can execute arbitrary work, but it generally runs at least one render pass.
// A node only has access to the render world, so if you need data from the main world
// you need to extract it manually or with the plugin like above.
// Add a [`Node`] to the [`RenderGraph`]
// The Node needs to impl FromWorld
//
// The [`ViewNodeRunner`] is a special [`Node`] that will automatically run the node for each view
// matching the [`ViewQuery`]
.add_render_graph_node::<ViewNodeRunner<PostProcessNode>>(
// Specify the label of the graph, in this case we want the graph for 3d
Core3d,
// It also needs the label of the node
PostProcessLabel,
)
.add_render_graph_edges(
Core3d,
// Specify the node ordering.
// This will automatically create all required node edges to enforce the given ordering.
(
Node3d::Tonemapping,
PostProcessLabel,
Node3d::EndMainPassPostProcessing,
),
);
}
fn finish(&self, app: &mut App) {
// We need to get the render app from the main app
let Ok(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app
// Initialize the pipeline
.init_resource::<PostProcessPipeline>();
}
sourcepub fn insert_sub_app(&mut self, label: impl AppLabel, sub_app: SubApp)
pub fn insert_sub_app(&mut self, label: impl AppLabel, sub_app: SubApp)
Inserts an existing sub app into the app
sourcepub fn remove_sub_app(&mut self, label: impl AppLabel) -> Option<SubApp>
pub fn remove_sub_app(&mut self, label: impl AppLabel) -> Option<SubApp>
Removes a sub app from the app. Returns None
if the label doesn’t exist.
sourcepub fn add_schedule(&mut self, schedule: Schedule) -> &mut App
pub fn add_schedule(&mut self, schedule: Schedule) -> &mut App
Adds a new schedule
to the App
.
§Warning
This method will overwrite any existing schedule with the same label.
To avoid this behavior, use the init_schedule
method instead.
Examples found in repository?
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
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.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.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();
}
sourcepub fn init_schedule(&mut self, label: impl ScheduleLabel) -> &mut App
pub fn init_schedule(&mut self, label: impl ScheduleLabel) -> &mut App
Initializes a new empty schedule
to the App
under the provided label
if it does not exists.
See App::add_schedule
to pass in a pre-constructed schedule.
Examples found in repository?
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
fn build(&self, app: &mut App) {
// create and insert our debug schedule into the main schedule order.
// We need an independent schedule so we have access to all other
// schedules through the `Stepping` resource
app.init_schedule(DebugSchedule);
let mut order = app.world.resource_mut::<MainScheduleOrder>();
order.insert_after(Update, DebugSchedule);
// create our stepping resource
let mut stepping = Stepping::new();
for label in &self.schedule_labels {
stepping.add_schedule(*label);
}
app.insert_resource(stepping);
// add our startup & stepping systems
app.insert_resource(State {
ui_top: self.top,
ui_left: self.left,
systems: Vec::new(),
})
.add_systems(Startup, build_help)
.add_systems(
DebugSchedule,
(
build_ui.run_if(not(initialized)),
handle_input,
update_ui.run_if(initialized),
)
.chain(),
);
}
sourcepub fn get_schedule(&self, label: impl ScheduleLabel) -> Option<&Schedule>
pub fn get_schedule(&self, label: impl ScheduleLabel) -> Option<&Schedule>
Gets read-only access to the Schedule
with the provided label
if it exists.
sourcepub fn get_schedule_mut(
&mut self,
label: impl ScheduleLabel
) -> Option<&mut Schedule>
pub fn get_schedule_mut( &mut self, label: impl ScheduleLabel ) -> Option<&mut Schedule>
Gets read-write access to a Schedule
with the provided label
if it exists.
sourcepub fn edit_schedule(
&mut self,
label: impl ScheduleLabel,
f: impl FnOnce(&mut Schedule)
) -> &mut App
pub fn edit_schedule( &mut self, label: impl ScheduleLabel, f: impl FnOnce(&mut Schedule) ) -> &mut App
Applies the function to the Schedule
associated with label
.
Note: This will create the schedule if it does not already exist.
Examples found in repository?
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
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();
}
sourcepub fn configure_schedules(
&mut self,
schedule_build_settings: ScheduleBuildSettings
) -> &mut App
pub fn configure_schedules( &mut self, schedule_build_settings: ScheduleBuildSettings ) -> &mut App
Applies the provided ScheduleBuildSettings
to all schedules.
sourcepub fn allow_ambiguous_component<T>(&mut self) -> &mut Appwhere
T: Component,
pub fn allow_ambiguous_component<T>(&mut self) -> &mut Appwhere
T: Component,
When doing ambiguity checking this
ignores systems that are ambiguous on Component
T.
This settings only applies to the main world. To apply this to other worlds call the corresponding method on World
§Example
#[derive(Component)]
struct A;
// these systems are ambiguous on A
fn system_1(_: Query<&mut A>) {}
fn system_2(_: Query<&A>) {}
let mut app = App::new();
app.configure_schedules(ScheduleBuildSettings {
ambiguity_detection: LogLevel::Error,
..default()
});
app.add_systems(Update, ( system_1, system_2 ));
app.allow_ambiguous_component::<A>();
// running the app does not error.
app.update();
sourcepub fn allow_ambiguous_resource<T>(&mut self) -> &mut Appwhere
T: Resource,
pub fn allow_ambiguous_resource<T>(&mut self) -> &mut Appwhere
T: Resource,
When doing ambiguity checking this
ignores systems that are ambiguous on Resource
T.
This settings only applies to the main world. To apply this to other worlds call the corresponding method on World
§Example
#[derive(Resource)]
struct R;
// these systems are ambiguous on R
fn system_1(_: ResMut<R>) {}
fn system_2(_: Res<R>) {}
let mut app = App::new();
app.configure_schedules(ScheduleBuildSettings {
ambiguity_detection: LogLevel::Error,
..default()
});
app.insert_resource(R);
app.add_systems(Update, ( system_1, system_2 ));
app.allow_ambiguous_resource::<R>();
// running the app does not error.
app.update();
sourcepub fn ignore_ambiguity<M1, M2, S1, S2>(
&mut self,
schedule: impl ScheduleLabel,
a: S1,
b: S2
) -> &mut Appwhere
S1: IntoSystemSet<M1>,
S2: IntoSystemSet<M2>,
pub fn ignore_ambiguity<M1, M2, S1, S2>(
&mut self,
schedule: impl ScheduleLabel,
a: S1,
b: S2
) -> &mut Appwhere
S1: IntoSystemSet<M1>,
S2: IntoSystemSet<M2>,
Suppress warnings and errors that would result from systems in these sets having ambiguities
(conflicting access but indeterminate order) with systems in set
.
When possible, do this directly in the .add_systems(Update, a.ambiguous_with(b))
call.
However, sometimes two independant plugins A
and B
are reported as ambiguous, which you
can only supress as the consumer of both.
Trait Implementations§
source§impl AddAudioSource for App
impl AddAudioSource for App
source§fn add_audio_source<T>(&mut self) -> &mut App
fn add_audio_source<T>(&mut self) -> &mut App
source§impl AddRenderCommand for App
impl AddRenderCommand for App
source§fn add_render_command<P, C>(&mut self) -> &mut Appwhere
P: PhaseItem,
C: RenderCommand<P> + Send + Sync + 'static,
<C as RenderCommand<P>>::Param: ReadOnlySystemParam,
fn add_render_command<P, C>(&mut self) -> &mut Appwhere
P: PhaseItem,
C: RenderCommand<P> + Send + Sync + 'static,
<C as RenderCommand<P>>::Param: ReadOnlySystemParam,
RenderCommand
for the specified RenderPhase
to the app.source§impl AppGizmoBuilder for App
impl AppGizmoBuilder for App
source§fn init_gizmo_group<T>(&mut self) -> &mut Appwhere
T: GizmoConfigGroup + Default,
fn init_gizmo_group<T>(&mut self) -> &mut Appwhere
T: GizmoConfigGroup + Default,
source§fn insert_gizmo_group<T>(&mut self, group: T, config: GizmoConfig) -> &mut Appwhere
T: GizmoConfigGroup,
fn insert_gizmo_group<T>(&mut self, group: T, config: GizmoConfig) -> &mut Appwhere
T: GizmoConfigGroup,
source§impl AssetApp for App
impl AssetApp for App
source§fn register_asset_loader<L>(&mut self, loader: L) -> &mut Appwhere
L: AssetLoader,
fn register_asset_loader<L>(&mut self, loader: L) -> &mut Appwhere
L: AssetLoader,
source§fn register_asset_processor<P>(&mut self, processor: P) -> &mut Appwhere
P: Process,
fn register_asset_processor<P>(&mut self, processor: P) -> &mut Appwhere
P: Process,
source§fn register_asset_source(
&mut self,
id: impl Into<AssetSourceId<'static>>,
source: AssetSourceBuilder
) -> &mut App
fn register_asset_source( &mut self, id: impl Into<AssetSourceId<'static>>, source: AssetSourceBuilder ) -> &mut App
source§fn set_default_asset_processor<P>(&mut self, extension: &str) -> &mut Appwhere
P: Process,
fn set_default_asset_processor<P>(&mut self, extension: &str) -> &mut Appwhere
P: Process,
extension
.source§fn init_asset_loader<L>(&mut self) -> &mut Appwhere
L: AssetLoader + FromWorld,
fn init_asset_loader<L>(&mut self) -> &mut Appwhere
L: AssetLoader + FromWorld,
App
’s AssetServer
.source§fn init_asset<A>(&mut self) -> &mut Appwhere
A: Asset,
fn init_asset<A>(&mut self) -> &mut Appwhere
A: Asset,
source§fn register_asset_reflect<A>(&mut self) -> &mut App
fn register_asset_reflect<A>(&mut self) -> &mut App
T
using [App::register]
,
and adds ReflectAsset
type data to T
and ReflectHandle
type data to Handle<T>
in the type registry. Read moresource§fn preregister_asset_loader<L>(&mut self, extensions: &[&str]) -> &mut Appwhere
L: AssetLoader,
fn preregister_asset_loader<L>(&mut self, extensions: &[&str]) -> &mut Appwhere
L: AssetLoader,
source§impl RegisterDiagnostic for App
impl RegisterDiagnostic for App
source§fn register_diagnostic(&mut self, diagnostic: Diagnostic) -> &mut App
fn register_diagnostic(&mut self, diagnostic: Diagnostic) -> &mut App
Register a new Diagnostic
with an App
.
Will initialize a DiagnosticsStore
if it doesn’t exist.
use bevy_app::App;
use bevy_diagnostic::{Diagnostic, DiagnosticsPlugin, DiagnosticPath, RegisterDiagnostic};
const UNIQUE_DIAG_PATH: DiagnosticPath = DiagnosticPath::const_new("foo/bar");
App::new()
.register_diagnostic(Diagnostic::new(UNIQUE_DIAG_PATH))
.add_plugins(DiagnosticsPlugin)
.run();
source§impl RenderGraphApp for App
impl RenderGraphApp for App
fn add_render_sub_graph(&mut self, sub_graph: impl RenderSubGraph) -> &mut App
source§fn add_render_graph_node<T>(
&mut self,
sub_graph: impl RenderSubGraph,
node_label: impl RenderLabel
) -> &mut App
fn add_render_graph_node<T>( &mut self, sub_graph: impl RenderSubGraph, node_label: impl RenderLabel ) -> &mut App
source§fn add_render_graph_edges<const N: usize>(
&mut self,
sub_graph: impl RenderSubGraph,
edges: impl IntoRenderNodeArray<N>
) -> &mut App
fn add_render_graph_edges<const N: usize>( &mut self, sub_graph: impl RenderSubGraph, edges: impl IntoRenderNodeArray<N> ) -> &mut App
source§fn add_render_graph_edge(
&mut self,
sub_graph: impl RenderSubGraph,
output_node: impl RenderLabel,
input_node: impl RenderLabel
) -> &mut App
fn add_render_graph_edge( &mut self, sub_graph: impl RenderSubGraph, output_node: impl RenderLabel, input_node: impl RenderLabel ) -> &mut App
Auto Trait Implementations§
impl !Freeze for App
impl !RefUnwindSafe for App
impl Send for App
impl !Sync for App
impl Unpin for App
impl !UnwindSafe for App
Blanket Implementations§
source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U
T
ShaderType
for self
. When used in AsBindGroup
derives, it is safe to assume that all images in self
exist.source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.source§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
source§impl<T> FromWorld for Twhere
T: Default,
impl<T> FromWorld for Twhere
T: Default,
source§fn from_world(_world: &mut World) -> T
fn from_world(_world: &mut World) -> T
Self
using data from the given World
.