Struct bevy_internal::app::App

source ·
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_apps.

§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

source

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.

source

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.

source

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.

source

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.

source

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

source

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.

source

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.

source

pub fn init_state<S>(&mut self) -> &mut App
where S: States + FromWorld,

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.

source

pub fn insert_state<S>(&mut self, state: S) -> &mut App
where 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.

source

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));
source

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.

source

pub fn add_event<T>(&mut self) -> &mut App
where 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>();
source

pub fn insert_resource<R>(&mut self, resource: R) -> &mut App
where 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. Resources must be added to Bevy apps before using them. This happens with insert_resource.

See init_resource for Resources that implement Default or FromWorld.

Examples
#[derive(Resource)]
struct MyCounter {
    counter: usize,
}

App::new()
   .insert_resource(MyCounter { counter: 0 });
source

pub fn insert_non_send_resource<R>(&mut self, resource: R) -> &mut App
where 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 });
source

pub fn init_resource<R>(&mut self) -> &mut App
where R: Resource + FromWorld,

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>();
source

pub fn init_non_send_resource<R>(&mut self) -> &mut App
where R: 'static + FromWorld,

Initialize a non-send Resource with standard starting values by adding it to the World.

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.

source

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);
source

pub fn is_plugin_added<T>(&self) -> bool
where 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.

source

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;
source

pub fn add_plugins<M>(&mut self, plugins: impl Plugins<M>) -> &mut App

Adds one or more Plugins.

One of Bevy’s core principles is modularity. All Bevy engine features are implemented as Plugins. This includes internal features like the renderer.

Plugins can be grouped into a set by using a PluginGroup.

There are built-in PluginGroups that provide core engine functionality. The PluginGroups 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 Plugins by using a tuple over Plugins and PluginGroups. 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.

source

pub fn register_type<T>(&mut self) -> &mut App

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

See bevy_reflect::TypeRegistry::register.

source

pub fn register_type_data<T, D>(&mut self) -> &mut App
where T: Reflect + TypePath, D: TypeData + FromType<T>,

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>();

See bevy_reflect::TypeRegistry::register_type_data.

source

pub fn sub_app_mut(&mut self, label: impl AppLabel) -> &mut App

Retrieves a SubApp stored inside this App.

Panics

Panics if the SubApp doesn’t exist.

source

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.

source

pub fn sub_app(&self, label: impl AppLabel) -> &App

Retrieves a SubApp stored inside this App.

Panics

Panics if the SubApp doesn’t exist.

source

pub fn insert_sub_app(&mut self, label: impl AppLabel, sub_app: SubApp)

Inserts an existing sub app into the app

source

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.

source

pub fn get_sub_app(&self, label: impl AppLabel) -> Result<&App, impl AppLabel>

Retrieves a SubApp inside this App with the given label, if it exists. Otherwise returns an Err containing the given label.

source

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.

source

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.

source

pub fn get_schedule(&self, label: impl ScheduleLabel) -> Option<&Schedule>

Gets read-only access to the Schedule with the provided label if it exists.

source

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.

source

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.

source

pub fn configure_schedules( &mut self, schedule_build_settings: ScheduleBuildSettings ) -> &mut App

Applies the provided ScheduleBuildSettings to all schedules.

source

pub fn allow_ambiguous_component<T>(&mut self) -> &mut App
where 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();
source

pub fn allow_ambiguous_resource<T>(&mut self) -> &mut App
where 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();
source

pub fn ignore_ambiguity<M1, M2, S1, S2>( &mut self, schedule: impl ScheduleLabel, a: S1, b: S2 ) -> &mut App
where 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

source§

fn add_audio_source<T>(&mut self) -> &mut App

Registers an audio source. The type must implement Decodable, so that it can be converted to a rodio::Source type, and Asset, so that it can be registered as an asset. To use this method on App, the audio and asset plugins must be added first.
source§

impl AddRenderCommand for App

source§

fn add_render_command<P, C>(&mut self) -> &mut App
where P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static, <C as RenderCommand<P>>::Param: ReadOnlySystemParam,

Adds the RenderCommand for the specified RenderPhase to the app.
source§

impl AppGizmoBuilder for App

source§

fn init_gizmo_group<T>(&mut self) -> &mut App

Registers GizmoConfigGroup T in the app enabling the use of Gizmos<T>. Read more
source§

fn insert_gizmo_group<T>(&mut self, group: T, config: GizmoConfig) -> &mut App

Insert the GizmoConfigGroup in the app with the given value and GizmoConfig. Read more
source§

impl AssetApp for App

source§

fn register_asset_loader<L>(&mut self, loader: L) -> &mut App
where L: AssetLoader,

Registers the given loader in the App’s AssetServer.
source§

fn register_asset_processor<P>(&mut self, processor: P) -> &mut App
where P: Process,

Registers the given processor in the App’s AssetProcessor.
source§

fn register_asset_source( &mut self, id: impl Into<AssetSourceId<'static>>, source: AssetSourceBuilder ) -> &mut App

Registers the given AssetSourceBuilder with the given id. Read more
source§

fn set_default_asset_processor<P>(&mut self, extension: &str) -> &mut App
where P: Process,

Sets the default asset processor for the given extension.
source§

fn init_asset_loader<L>(&mut self) -> &mut App

Initializes the given loader in the App’s AssetServer.
source§

fn init_asset<A>(&mut self) -> &mut App
where A: Asset,

Initializes the given Asset in the App by: Read more
source§

fn register_asset_reflect<A>(&mut self) -> &mut App

Registers the asset type T using [App::register], and adds ReflectAsset type data to T and ReflectHandle type data to Handle<T> in the type registry. Read more
source§

fn preregister_asset_loader<L>(&mut self, extensions: &[&str]) -> &mut App
where L: AssetLoader,

Preregisters a loader for the given extensions, that will block asset loads until a real loader is registered.
source§

impl Debug for App

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl Default for App

source§

fn default() -> App

Returns the “default value” for a type. Read more
source§

impl RegisterDiagnostic for App

source§

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

source§

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
where T: Node + FromWorld,

Add a Node to the RenderGraph: Read more
source§

fn add_render_graph_edges<const N: usize>( &mut self, sub_graph: impl RenderSubGraph, edges: impl IntoRenderNodeArray<N> ) -> &mut App

Automatically add the required node edges based on the given ordering
source§

fn add_render_graph_edge( &mut self, sub_graph: impl RenderSubGraph, output_node: impl RenderLabel, input_node: impl RenderLabel ) -> &mut App

Add node edge to the specified graph

Auto Trait Implementations§

§

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> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> Downcast<T> for T

source§

fn downcast(&self) -> &T

source§

impl<T> Downcast for T
where T: Any,

source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert 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>

Convert 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)

Convert &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)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<S> FromSample<S> for S

source§

fn from_sample_(s: S) -> S

source§

impl<T> FromWorld for T
where T: Default,

source§

fn from_world(_world: &mut World) -> T

Creates Self using data from the given World.
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

source§

fn to_sample_(self) -> U

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> Upcast<T> for T

source§

fn upcast(&self) -> Option<&T>

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

source§

impl<T> WasmNotSend for T
where T: Send,