2024-06-25 14:04:31 +00:00
|
|
|
use crate::{App, AppLabel, InternedAppLabel, Plugin, Plugins, PluginsState};
|
2024-03-31 03:16:10 +00:00
|
|
|
use bevy_ecs::{
|
Optimize Event Updates (#12936)
# Objective
Improve performance scalability when adding new event types to a Bevy
app. Currently, just using Bevy in the default configuration, all apps
spend upwards of 100+us in the `First` schedule, every app tick,
evaluating if it should update events or not, even if events are not
being used for that particular frame, and this scales with the number of
Events registered in the app.
## Solution
As `Events::update` is guaranteed `O(1)` by just checking if a
resource's value, swapping two Vecs, and then clearing one of them, the
actual cost of running `event_update_system` is *very* cheap. The
overhead of doing system dependency injection, task scheduling ,and the
multithreaded executor outweighs the cost of running the system by a
large margin.
Create an `EventRegistry` resource that keeps a number of function
pointers that update each event. Replace the per-event type
`event_update_system` with a singular exclusive system uses the
`EventRegistry` to update all events instead. Update `SubApp::add_event`
to use `EventRegistry` instead.
## Performance
This speeds reduces the cost of the `First` schedule in both many_foxes
and many_cubes by over 80%. Note this is with system spans on. The
majority of this is now context-switching costs from launching
`time_system`, which should be mostly eliminated with #12869.
![image](https://github.com/bevyengine/bevy/assets/3137680/037624be-21a2-4dc2-a42f-9d0bfa3e9b4a)
The actual `event_update_system` is usually *very* short, using only a
few microseconds on average.
![image](https://github.com/bevyengine/bevy/assets/3137680/01ff1689-3595-49b6-8f09-5c44bcf903e8)
---
## Changelog
TODO
## Migration Guide
TODO
---------
Co-authored-by: Josh Matthews <josh@joshmatthews.net>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-04-13 14:11:28 +00:00
|
|
|
event::EventRegistry,
|
2024-03-31 03:16:10 +00:00
|
|
|
prelude::*,
|
Separate state crate (#13216)
# Objective
Extracts the state mechanisms into a new crate called "bevy_state".
This comes with a few goals:
- state wasn't really an inherent machinery of the ecs system, and so
keeping it within bevy_ecs felt forced
- by mixing it in with bevy_ecs, the maintainability of our more robust
state system was significantly compromised
moving state into a new crate makes it easier to encapsulate as it's own
feature, and easier to read and understand since it's no longer a
single, massive file.
## Solution
move the state-related elements from bevy_ecs to a new crate
## Testing
- Did you test these changes? If so, how? all the automated tests
migrated and passed, ran the pre-existing examples without changes to
validate.
---
## Migration Guide
Since bevy_state is now gated behind the `bevy_state` feature, projects
that use state but don't use the `default-features` will need to add
that feature flag.
Since it is no longer part of bevy_ecs, projects that use bevy_ecs
directly will need to manually pull in `bevy_state`, trigger the
StateTransition schedule, and handle any of the elements that bevy_app
currently sets up.
---------
Co-authored-by: Kristoffer Søholm <k.soeholm@gmail.com>
2024-05-09 18:06:05 +00:00
|
|
|
schedule::{InternedScheduleLabel, ScheduleBuildSettings, ScheduleLabel},
|
2024-03-31 03:16:10 +00:00
|
|
|
system::SystemId,
|
|
|
|
};
|
Separate state crate (#13216)
# Objective
Extracts the state mechanisms into a new crate called "bevy_state".
This comes with a few goals:
- state wasn't really an inherent machinery of the ecs system, and so
keeping it within bevy_ecs felt forced
- by mixing it in with bevy_ecs, the maintainability of our more robust
state system was significantly compromised
moving state into a new crate makes it easier to encapsulate as it's own
feature, and easier to read and understand since it's no longer a
single, massive file.
## Solution
move the state-related elements from bevy_ecs to a new crate
## Testing
- Did you test these changes? If so, how? all the automated tests
migrated and passed, ran the pre-existing examples without changes to
validate.
---
## Migration Guide
Since bevy_state is now gated behind the `bevy_state` feature, projects
that use state but don't use the `default-features` will need to add
that feature flag.
Since it is no longer part of bevy_ecs, projects that use bevy_ecs
directly will need to manually pull in `bevy_state`, trigger the
StateTransition schedule, and handle any of the elements that bevy_app
currently sets up.
---------
Co-authored-by: Kristoffer Søholm <k.soeholm@gmail.com>
2024-05-09 18:06:05 +00:00
|
|
|
|
2024-03-31 03:16:10 +00:00
|
|
|
#[cfg(feature = "trace")]
|
|
|
|
use bevy_utils::tracing::info_span;
|
2024-04-28 21:32:16 +00:00
|
|
|
use bevy_utils::{HashMap, HashSet};
|
2024-03-31 03:16:10 +00:00
|
|
|
use std::fmt::Debug;
|
|
|
|
|
|
|
|
type ExtractFn = Box<dyn Fn(&mut World, &mut World) + Send>;
|
|
|
|
|
|
|
|
/// A secondary application with its own [`World`]. These can run independently of each other.
|
|
|
|
///
|
|
|
|
/// These are useful for situations where certain processes (e.g. a render thread) need to be kept
|
|
|
|
/// separate from the main application.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # use bevy_app::{App, AppLabel, SubApp, Main};
|
|
|
|
/// # use bevy_ecs::prelude::*;
|
|
|
|
/// # use bevy_ecs::schedule::ScheduleLabel;
|
|
|
|
///
|
|
|
|
/// #[derive(Resource, Default)]
|
|
|
|
/// struct Val(pub i32);
|
|
|
|
///
|
|
|
|
/// #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, AppLabel)]
|
|
|
|
/// struct ExampleApp;
|
|
|
|
///
|
|
|
|
/// // Create an app with a certain resource.
|
|
|
|
/// let mut app = App::new();
|
|
|
|
/// app.insert_resource(Val(10));
|
|
|
|
///
|
|
|
|
/// // Create a sub-app with the same resource and a single schedule.
|
|
|
|
/// let mut sub_app = SubApp::new();
|
|
|
|
/// sub_app.insert_resource(Val(100));
|
|
|
|
///
|
|
|
|
/// // Setup an extract function to copy the resource's value in the main world.
|
|
|
|
/// sub_app.set_extract(|main_world, sub_world| {
|
|
|
|
/// sub_world.resource_mut::<Val>().0 = main_world.resource::<Val>().0;
|
|
|
|
/// });
|
|
|
|
///
|
|
|
|
/// // Schedule a system that will verify extraction is working.
|
|
|
|
/// sub_app.add_systems(Main, |counter: Res<Val>| {
|
|
|
|
/// // The value will be copied during extraction, so we should see 10 instead of 100.
|
|
|
|
/// assert_eq!(counter.0, 10);
|
|
|
|
/// });
|
|
|
|
///
|
|
|
|
/// // Add the sub-app to the main app.
|
|
|
|
/// app.insert_sub_app(ExampleApp, sub_app);
|
|
|
|
///
|
|
|
|
/// // Update the application once (using the default runner).
|
|
|
|
/// app.run();
|
|
|
|
/// ```
|
|
|
|
pub struct SubApp {
|
|
|
|
/// The data of this application.
|
|
|
|
world: World,
|
2024-04-28 21:32:16 +00:00
|
|
|
/// List of plugins that have been added.
|
|
|
|
pub(crate) plugin_registry: Vec<Box<dyn Plugin>>,
|
|
|
|
/// The names of plugins that have been added to this app. (used to track duplicates and
|
|
|
|
/// already-registered plugins)
|
|
|
|
pub(crate) plugin_names: HashSet<String>,
|
2024-03-31 03:16:10 +00:00
|
|
|
/// Panics if an update is attempted while plugins are building.
|
|
|
|
pub(crate) plugin_build_depth: usize,
|
|
|
|
pub(crate) plugins_state: PluginsState,
|
|
|
|
/// The schedule that will be run by [`update`](Self::update).
|
|
|
|
pub update_schedule: Option<InternedScheduleLabel>,
|
|
|
|
/// A function that gives mutable access to two app worlds. This is primarily
|
|
|
|
/// intended for copying data from the main world to secondary worlds.
|
|
|
|
extract: Option<ExtractFn>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Debug for SubApp {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
write!(f, "SubApp")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for SubApp {
|
|
|
|
fn default() -> Self {
|
|
|
|
let mut world = World::new();
|
|
|
|
world.init_resource::<Schedules>();
|
|
|
|
Self {
|
|
|
|
world,
|
2024-04-28 21:32:16 +00:00
|
|
|
plugin_registry: Vec::default(),
|
|
|
|
plugin_names: HashSet::default(),
|
2024-03-31 03:16:10 +00:00
|
|
|
plugin_build_depth: 0,
|
|
|
|
plugins_state: PluginsState::Adding,
|
|
|
|
update_schedule: None,
|
|
|
|
extract: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl SubApp {
|
|
|
|
/// Returns a default, empty [`SubApp`].
|
|
|
|
pub fn new() -> Self {
|
|
|
|
Self::default()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// This method is a workaround. Each [`SubApp`] can have its own plugins, but [`Plugin`]
|
|
|
|
/// works on an [`App`] as a whole.
|
|
|
|
fn run_as_app<F>(&mut self, f: F)
|
|
|
|
where
|
|
|
|
F: FnOnce(&mut App),
|
|
|
|
{
|
|
|
|
let mut app = App::empty();
|
|
|
|
std::mem::swap(self, &mut app.sub_apps.main);
|
|
|
|
f(&mut app);
|
|
|
|
std::mem::swap(self, &mut app.sub_apps.main);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a reference to the [`World`].
|
|
|
|
pub fn world(&self) -> &World {
|
|
|
|
&self.world
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a mutable reference to the [`World`].
|
|
|
|
pub fn world_mut(&mut self) -> &mut World {
|
|
|
|
&mut self.world
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Runs the default schedule.
|
Remove extra call to clear_trackers (#13762)
Fixes #13758.
# Objective
Calling `update` on the main app already calls `clear_trackers`. Calling
it again in `SubApps::update` caused RemovedCompenet Events to be
cleared earlier than they should be.
## Solution
- Don't call clear_trackers an extra time.
## Testing
I manually tested the fix with this unit test:
```
#[cfg(test)]
mod test {
use crate::core::{FrameCount, FrameCountPlugin};
use crate::prelude::*;
#[test]
fn test_next_frame_removal() {
#[derive(Component)]
struct Foo;
#[derive(Resource)]
struct RemovedCount(usize);
let mut app = App::new();
app.add_plugins(FrameCountPlugin);
app.add_systems(Startup, |mut commands: Commands| {
for _ in 0..100 {
commands.spawn(Foo);
}
commands.insert_resource(RemovedCount(0));
});
app.add_systems(First, |counter: Res<FrameCount>| {
println!("Frame {}:", counter.0)
});
fn detector_system(
mut removals: RemovedComponents<Foo>,
foos: Query<Entity, With<Foo>>,
mut removed_c: ResMut<RemovedCount>,
) {
for e in removals.read() {
println!(" Detected removed Foo component for {e:?}");
removed_c.0 += 1;
}
let c = foos.iter().count();
println!(" Total Foos: {}", c);
assert_eq!(c + removed_c.0, 100);
}
fn deleter_system(foos: Query<Entity, With<Foo>>, mut commands: Commands) {
foos.iter().next().map(|e| {
commands.entity(e).remove::<Foo>();
});
}
app.add_systems(Update, (detector_system, deleter_system).chain());
app.update();
app.update();
app.update();
app.update();
}
}
```
2024-06-10 18:06:05 +00:00
|
|
|
///
|
|
|
|
/// Does not clear internal trackers used for change detection.
|
|
|
|
pub fn run_default_schedule(&mut self) {
|
2024-03-31 03:16:10 +00:00
|
|
|
if self.is_building_plugins() {
|
|
|
|
panic!("SubApp::update() was called while a plugin was building.");
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(label) = self.update_schedule {
|
|
|
|
self.world.run_schedule(label);
|
|
|
|
}
|
Remove extra call to clear_trackers (#13762)
Fixes #13758.
# Objective
Calling `update` on the main app already calls `clear_trackers`. Calling
it again in `SubApps::update` caused RemovedCompenet Events to be
cleared earlier than they should be.
## Solution
- Don't call clear_trackers an extra time.
## Testing
I manually tested the fix with this unit test:
```
#[cfg(test)]
mod test {
use crate::core::{FrameCount, FrameCountPlugin};
use crate::prelude::*;
#[test]
fn test_next_frame_removal() {
#[derive(Component)]
struct Foo;
#[derive(Resource)]
struct RemovedCount(usize);
let mut app = App::new();
app.add_plugins(FrameCountPlugin);
app.add_systems(Startup, |mut commands: Commands| {
for _ in 0..100 {
commands.spawn(Foo);
}
commands.insert_resource(RemovedCount(0));
});
app.add_systems(First, |counter: Res<FrameCount>| {
println!("Frame {}:", counter.0)
});
fn detector_system(
mut removals: RemovedComponents<Foo>,
foos: Query<Entity, With<Foo>>,
mut removed_c: ResMut<RemovedCount>,
) {
for e in removals.read() {
println!(" Detected removed Foo component for {e:?}");
removed_c.0 += 1;
}
let c = foos.iter().count();
println!(" Total Foos: {}", c);
assert_eq!(c + removed_c.0, 100);
}
fn deleter_system(foos: Query<Entity, With<Foo>>, mut commands: Commands) {
foos.iter().next().map(|e| {
commands.entity(e).remove::<Foo>();
});
}
app.add_systems(Update, (detector_system, deleter_system).chain());
app.update();
app.update();
app.update();
app.update();
}
}
```
2024-06-10 18:06:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Runs the default schedule and updates internal component trackers.
|
|
|
|
pub fn update(&mut self) {
|
|
|
|
self.run_default_schedule();
|
2024-03-31 03:16:10 +00:00
|
|
|
self.world.clear_trackers();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Extracts data from `world` into the app's world using the registered extract method.
|
|
|
|
///
|
|
|
|
/// **Note:** There is no default extract method. Calling `extract` does nothing if
|
|
|
|
/// [`set_extract`](Self::set_extract) has not been called.
|
|
|
|
pub fn extract(&mut self, world: &mut World) {
|
|
|
|
if let Some(f) = self.extract.as_mut() {
|
|
|
|
f(world, &mut self.world);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Sets the method that will be called by [`extract`](Self::extract).
|
|
|
|
///
|
|
|
|
/// The first argument is the `World` to extract data from, the second argument is the app `World`.
|
|
|
|
pub fn set_extract<F>(&mut self, extract: F) -> &mut Self
|
|
|
|
where
|
|
|
|
F: Fn(&mut World, &mut World) + Send + 'static,
|
|
|
|
{
|
|
|
|
self.extract = Some(Box::new(extract));
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::insert_resource`].
|
|
|
|
pub fn insert_resource<R: Resource>(&mut self, resource: R) -> &mut Self {
|
|
|
|
self.world.insert_resource(resource);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::init_resource`].
|
|
|
|
pub fn init_resource<R: Resource + FromWorld>(&mut self) -> &mut Self {
|
|
|
|
self.world.init_resource::<R>();
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::add_systems`].
|
|
|
|
pub fn add_systems<M>(
|
|
|
|
&mut self,
|
|
|
|
schedule: impl ScheduleLabel,
|
|
|
|
systems: impl IntoSystemConfigs<M>,
|
|
|
|
) -> &mut Self {
|
|
|
|
let mut schedules = self.world.resource_mut::<Schedules>();
|
Schedule resource mutation (#13193)
# Objective
Resolves #13185
## Solution
Move the following methods from `sub_app` to the `Schedules` resource,
and use them in the sub app:
- `add_systems`
- `configure_sets`
- `ignore_ambiguity`
Add an `entry(&mut self, label: impl ScheduleLabel) -> &mut Schedule`
method to the `Schedules` resource, which returns a mutable reference to
the schedule associated with the label, and creates one if it doesn't
already exist. (build on top of the `entry(..).or_insert_with(...)`
pattern in `HashMap`.
## Testing
- Did you test these changes? If so, how? Added 4 unit tests to the
`schedule.rs` - one that validates adding a system to an existing
schedule, one that validates adding a system to a new one, one that
validates configuring sets on an existing schedule, and one that
validates configuring sets on a new schedule.
- I didn't add tests for `entry` since the previous 4 tests use
functions that rely on it.
- I didn't test `ignore_ambiguity` since I didn't see examples of it's
use, and am not familiar enough with it to know how to set up a good
test for it. However, it relies on the `entry` method as well, so it
should work just like the other 2 methods.
2024-05-03 12:40:32 +00:00
|
|
|
schedules.add_systems(schedule, systems);
|
2024-03-31 03:16:10 +00:00
|
|
|
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::register_system`].
|
|
|
|
pub fn register_system<I: 'static, O: 'static, M, S: IntoSystem<I, O, M> + 'static>(
|
|
|
|
&mut self,
|
|
|
|
system: S,
|
|
|
|
) -> SystemId<I, O> {
|
|
|
|
self.world.register_system(system)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::configure_sets`].
|
|
|
|
#[track_caller]
|
|
|
|
pub fn configure_sets(
|
|
|
|
&mut self,
|
|
|
|
schedule: impl ScheduleLabel,
|
|
|
|
sets: impl IntoSystemSetConfigs,
|
|
|
|
) -> &mut Self {
|
|
|
|
let mut schedules = self.world.resource_mut::<Schedules>();
|
Schedule resource mutation (#13193)
# Objective
Resolves #13185
## Solution
Move the following methods from `sub_app` to the `Schedules` resource,
and use them in the sub app:
- `add_systems`
- `configure_sets`
- `ignore_ambiguity`
Add an `entry(&mut self, label: impl ScheduleLabel) -> &mut Schedule`
method to the `Schedules` resource, which returns a mutable reference to
the schedule associated with the label, and creates one if it doesn't
already exist. (build on top of the `entry(..).or_insert_with(...)`
pattern in `HashMap`.
## Testing
- Did you test these changes? If so, how? Added 4 unit tests to the
`schedule.rs` - one that validates adding a system to an existing
schedule, one that validates adding a system to a new one, one that
validates configuring sets on an existing schedule, and one that
validates configuring sets on a new schedule.
- I didn't add tests for `entry` since the previous 4 tests use
functions that rely on it.
- I didn't test `ignore_ambiguity` since I didn't see examples of it's
use, and am not familiar enough with it to know how to set up a good
test for it. However, it relies on the `entry` method as well, so it
should work just like the other 2 methods.
2024-05-03 12:40:32 +00:00
|
|
|
schedules.configure_sets(schedule, sets);
|
2024-03-31 03:16:10 +00:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::add_schedule`].
|
|
|
|
pub fn add_schedule(&mut self, schedule: Schedule) -> &mut Self {
|
|
|
|
let mut schedules = self.world.resource_mut::<Schedules>();
|
|
|
|
schedules.insert(schedule);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::init_schedule`].
|
|
|
|
pub fn init_schedule(&mut self, label: impl ScheduleLabel) -> &mut Self {
|
|
|
|
let label = label.intern();
|
|
|
|
let mut schedules = self.world.resource_mut::<Schedules>();
|
|
|
|
if !schedules.contains(label) {
|
|
|
|
schedules.insert(Schedule::new(label));
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::get_schedule`].
|
|
|
|
pub fn get_schedule(&self, label: impl ScheduleLabel) -> Option<&Schedule> {
|
|
|
|
let schedules = self.world.get_resource::<Schedules>()?;
|
|
|
|
schedules.get(label)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::get_schedule_mut`].
|
|
|
|
pub fn get_schedule_mut(&mut self, label: impl ScheduleLabel) -> Option<&mut Schedule> {
|
|
|
|
let schedules = self.world.get_resource_mut::<Schedules>()?;
|
|
|
|
// We must call `.into_inner` here because the borrow checker only understands reborrows
|
|
|
|
// using ordinary references, not our `Mut` smart pointers.
|
|
|
|
schedules.into_inner().get_mut(label)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::edit_schedule`].
|
|
|
|
pub fn edit_schedule(
|
|
|
|
&mut self,
|
|
|
|
label: impl ScheduleLabel,
|
|
|
|
mut f: impl FnMut(&mut Schedule),
|
|
|
|
) -> &mut Self {
|
|
|
|
let label = label.intern();
|
|
|
|
let mut schedules = self.world.resource_mut::<Schedules>();
|
|
|
|
if !schedules.contains(label) {
|
|
|
|
schedules.insert(Schedule::new(label));
|
|
|
|
}
|
|
|
|
|
|
|
|
let schedule = schedules.get_mut(label).unwrap();
|
|
|
|
f(schedule);
|
|
|
|
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::configure_schedules`].
|
|
|
|
pub fn configure_schedules(
|
|
|
|
&mut self,
|
|
|
|
schedule_build_settings: ScheduleBuildSettings,
|
|
|
|
) -> &mut Self {
|
|
|
|
self.world_mut()
|
|
|
|
.resource_mut::<Schedules>()
|
|
|
|
.configure_schedules(schedule_build_settings);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::allow_ambiguous_component`].
|
|
|
|
pub fn allow_ambiguous_component<T: Component>(&mut self) -> &mut Self {
|
|
|
|
self.world_mut().allow_ambiguous_component::<T>();
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::allow_ambiguous_resource`].
|
|
|
|
pub fn allow_ambiguous_resource<T: Resource>(&mut self) -> &mut Self {
|
|
|
|
self.world_mut().allow_ambiguous_resource::<T>();
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::ignore_ambiguity`].
|
|
|
|
#[track_caller]
|
|
|
|
pub fn ignore_ambiguity<M1, M2, S1, S2>(
|
|
|
|
&mut self,
|
|
|
|
schedule: impl ScheduleLabel,
|
|
|
|
a: S1,
|
|
|
|
b: S2,
|
|
|
|
) -> &mut Self
|
|
|
|
where
|
|
|
|
S1: IntoSystemSet<M1>,
|
|
|
|
S2: IntoSystemSet<M2>,
|
|
|
|
{
|
|
|
|
let schedule = schedule.intern();
|
|
|
|
let mut schedules = self.world.resource_mut::<Schedules>();
|
|
|
|
|
Schedule resource mutation (#13193)
# Objective
Resolves #13185
## Solution
Move the following methods from `sub_app` to the `Schedules` resource,
and use them in the sub app:
- `add_systems`
- `configure_sets`
- `ignore_ambiguity`
Add an `entry(&mut self, label: impl ScheduleLabel) -> &mut Schedule`
method to the `Schedules` resource, which returns a mutable reference to
the schedule associated with the label, and creates one if it doesn't
already exist. (build on top of the `entry(..).or_insert_with(...)`
pattern in `HashMap`.
## Testing
- Did you test these changes? If so, how? Added 4 unit tests to the
`schedule.rs` - one that validates adding a system to an existing
schedule, one that validates adding a system to a new one, one that
validates configuring sets on an existing schedule, and one that
validates configuring sets on a new schedule.
- I didn't add tests for `entry` since the previous 4 tests use
functions that rely on it.
- I didn't test `ignore_ambiguity` since I didn't see examples of it's
use, and am not familiar enough with it to know how to set up a good
test for it. However, it relies on the `entry` method as well, so it
should work just like the other 2 methods.
2024-05-03 12:40:32 +00:00
|
|
|
schedules.ignore_ambiguity(schedule, a, b);
|
2024-03-31 03:16:10 +00:00
|
|
|
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::add_event`].
|
|
|
|
pub fn add_event<T>(&mut self) -> &mut Self
|
|
|
|
where
|
|
|
|
T: Event,
|
|
|
|
{
|
|
|
|
if !self.world.contains_resource::<Events<T>>() {
|
Optimize Event Updates (#12936)
# Objective
Improve performance scalability when adding new event types to a Bevy
app. Currently, just using Bevy in the default configuration, all apps
spend upwards of 100+us in the `First` schedule, every app tick,
evaluating if it should update events or not, even if events are not
being used for that particular frame, and this scales with the number of
Events registered in the app.
## Solution
As `Events::update` is guaranteed `O(1)` by just checking if a
resource's value, swapping two Vecs, and then clearing one of them, the
actual cost of running `event_update_system` is *very* cheap. The
overhead of doing system dependency injection, task scheduling ,and the
multithreaded executor outweighs the cost of running the system by a
large margin.
Create an `EventRegistry` resource that keeps a number of function
pointers that update each event. Replace the per-event type
`event_update_system` with a singular exclusive system uses the
`EventRegistry` to update all events instead. Update `SubApp::add_event`
to use `EventRegistry` instead.
## Performance
This speeds reduces the cost of the `First` schedule in both many_foxes
and many_cubes by over 80%. Note this is with system spans on. The
majority of this is now context-switching costs from launching
`time_system`, which should be mostly eliminated with #12869.
![image](https://github.com/bevyengine/bevy/assets/3137680/037624be-21a2-4dc2-a42f-9d0bfa3e9b4a)
The actual `event_update_system` is usually *very* short, using only a
few microseconds on average.
![image](https://github.com/bevyengine/bevy/assets/3137680/01ff1689-3595-49b6-8f09-5c44bcf903e8)
---
## Changelog
TODO
## Migration Guide
TODO
---------
Co-authored-by: Josh Matthews <josh@joshmatthews.net>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-04-13 14:11:28 +00:00
|
|
|
EventRegistry::register_event::<T>(self.world_mut());
|
2024-03-31 03:16:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::add_plugins`].
|
|
|
|
pub fn add_plugins<M>(&mut self, plugins: impl Plugins<M>) -> &mut Self {
|
|
|
|
self.run_as_app(|app| plugins.add_to_app(app));
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::is_plugin_added`].
|
|
|
|
pub fn is_plugin_added<T>(&self) -> bool
|
|
|
|
where
|
|
|
|
T: Plugin,
|
|
|
|
{
|
2024-04-28 21:32:16 +00:00
|
|
|
self.plugin_names.contains(std::any::type_name::<T>())
|
2024-03-31 03:16:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::get_added_plugins`].
|
|
|
|
pub fn get_added_plugins<T>(&self) -> Vec<&T>
|
|
|
|
where
|
|
|
|
T: Plugin,
|
|
|
|
{
|
2024-04-28 21:32:16 +00:00
|
|
|
self.plugin_registry
|
2024-03-31 03:16:10 +00:00
|
|
|
.iter()
|
|
|
|
.filter_map(|p| p.downcast_ref())
|
|
|
|
.collect()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns `true` if there is no plugin in the middle of being built.
|
|
|
|
pub(crate) fn is_building_plugins(&self) -> bool {
|
|
|
|
self.plugin_build_depth > 0
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the state of plugins.
|
|
|
|
#[inline]
|
|
|
|
pub fn plugins_state(&mut self) -> PluginsState {
|
|
|
|
match self.plugins_state {
|
|
|
|
PluginsState::Adding => {
|
|
|
|
let mut state = PluginsState::Ready;
|
2024-04-28 21:32:16 +00:00
|
|
|
let plugins = std::mem::take(&mut self.plugin_registry);
|
2024-03-31 03:16:10 +00:00
|
|
|
self.run_as_app(|app| {
|
2024-04-28 21:32:16 +00:00
|
|
|
for plugin in &plugins {
|
2024-03-31 03:16:10 +00:00
|
|
|
if !plugin.ready(app) {
|
|
|
|
state = PluginsState::Adding;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
2024-04-28 21:32:16 +00:00
|
|
|
self.plugin_registry = plugins;
|
2024-03-31 03:16:10 +00:00
|
|
|
state
|
|
|
|
}
|
|
|
|
state => state,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Runs [`Plugin::finish`] for each plugin.
|
|
|
|
pub fn finish(&mut self) {
|
2024-04-28 21:32:16 +00:00
|
|
|
let plugins = std::mem::take(&mut self.plugin_registry);
|
2024-03-31 03:16:10 +00:00
|
|
|
self.run_as_app(|app| {
|
2024-04-28 21:32:16 +00:00
|
|
|
for plugin in &plugins {
|
2024-03-31 03:16:10 +00:00
|
|
|
plugin.finish(app);
|
|
|
|
}
|
|
|
|
});
|
2024-04-28 21:32:16 +00:00
|
|
|
self.plugin_registry = plugins;
|
2024-03-31 03:16:10 +00:00
|
|
|
self.plugins_state = PluginsState::Finished;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Runs [`Plugin::cleanup`] for each plugin.
|
|
|
|
pub fn cleanup(&mut self) {
|
2024-04-28 21:32:16 +00:00
|
|
|
let plugins = std::mem::take(&mut self.plugin_registry);
|
2024-03-31 03:16:10 +00:00
|
|
|
self.run_as_app(|app| {
|
2024-04-28 21:32:16 +00:00
|
|
|
for plugin in &plugins {
|
2024-03-31 03:16:10 +00:00
|
|
|
plugin.cleanup(app);
|
|
|
|
}
|
|
|
|
});
|
2024-04-28 21:32:16 +00:00
|
|
|
self.plugin_registry = plugins;
|
2024-03-31 03:16:10 +00:00
|
|
|
self.plugins_state = PluginsState::Cleaned;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::register_type`].
|
|
|
|
#[cfg(feature = "bevy_reflect")]
|
|
|
|
pub fn register_type<T: bevy_reflect::GetTypeRegistration>(&mut self) -> &mut Self {
|
|
|
|
let registry = self.world.resource_mut::<AppTypeRegistry>();
|
|
|
|
registry.write().register::<T>();
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::register_type_data`].
|
|
|
|
#[cfg(feature = "bevy_reflect")]
|
|
|
|
pub fn register_type_data<
|
|
|
|
T: bevy_reflect::Reflect + bevy_reflect::TypePath,
|
|
|
|
D: bevy_reflect::TypeData + bevy_reflect::FromType<T>,
|
|
|
|
>(
|
|
|
|
&mut self,
|
|
|
|
) -> &mut Self {
|
|
|
|
let registry = self.world.resource_mut::<AppTypeRegistry>();
|
|
|
|
registry.write().register_type_data::<T, D>();
|
|
|
|
self
|
|
|
|
}
|
bevy_reflect: Function registry (#14098)
# Objective
#13152 added support for reflecting functions. Now, we need a way to
register those functions such that they may be accessed anywhere within
the ECS.
## Solution
Added a `FunctionRegistry` type similar to `TypeRegistry`.
This allows a function to be registered and retrieved by name.
```rust
fn foo() -> i32 {
123
}
let mut registry = FunctionRegistry::default();
registry.register("my_function", foo);
let function = registry.get_mut("my_function").unwrap();
let value = function.call(ArgList::new()).unwrap().unwrap_owned();
assert_eq!(value.downcast_ref::<i32>(), Some(&123));
```
Additionally, I added an `AppFunctionRegistry` resource which wraps a
`FunctionRegistryArc`. Functions can be registered into this resource
using `App::register_function` or by getting a mutable reference to the
resource itself.
### Limitations
#### `Send + Sync`
In order to get this registry to work across threads, it needs to be
`Send + Sync`. This means that `DynamicFunction` needs to be `Send +
Sync`, which means that its internal function also needs to be `Send +
Sync`.
In most cases, this won't be an issue because standard Rust functions
(the type most likely to be registered) are always `Send + Sync`.
Additionally, closures tend to be `Send + Sync` as well, granted they
don't capture any `!Send` or `!Sync` variables.
This PR adds this `Send + Sync` requirement, but as mentioned above, it
hopefully shouldn't be too big of an issue.
#### Closures
Unfortunately, closures can't be registered yet. This will likely be
explored and added in a followup PR.
### Future Work
Besides addressing the limitations listed above, another thing we could
look into is improving the lookup of registered functions. One aspect is
in the performance of hashing strings. The other is in the developer
experience of having to call `std::any::type_name_of_val` to get the
name of their function (assuming they didn't give it a custom name).
## Testing
You can run the tests locally with:
```
cargo test --package bevy_reflect
```
---
## Changelog
- Added `FunctionRegistry`
- Added `AppFunctionRegistry` (a `Resource` available from `bevy_ecs`)
- Added `FunctionRegistryArc`
- Added `FunctionRegistrationError`
- Added `reflect_functions` feature to `bevy_ecs` and `bevy_app`
- `FunctionInfo` is no longer `Default`
- `DynamicFunction` now requires its wrapped function be `Send + Sync`
## Internal Migration Guide
> [!important]
> Function reflection was introduced as part of the 0.15 dev cycle. This
migration guide was written for developers relying on `main` during this
cycle, and is not a breaking change coming from 0.14.
`DynamicFunction` (both those created manually and those created with
`IntoFunction`), now require `Send + Sync`. All standard Rust functions
should meet that requirement. Closures, on the other hand, may not if
they capture any `!Send` or `!Sync` variables from its environment.
2024-08-06 01:09:48 +00:00
|
|
|
|
|
|
|
/// See [`App::register_function`].
|
|
|
|
#[cfg(feature = "reflect_functions")]
|
bevy_reflect: Anonymous function parsing (#14641)
# Objective
### TL;DR
#14098 added the `FunctionRegistry` but had some last minute
complications due to anonymous functions. It ended up going with a
"required name" approach to ensure anonymous functions would always have
a name.
However, this approach isn't ideal for named functions since, by
definition, they will always have a name.
Therefore, this PR aims to modify function reflection such that we can
make function registration easier for named functions, while still
allowing anonymous functions to be registered as well.
### Context
Function registration (#14098) ran into a little problem: anonymous
functions.
Anonymous functions, including function pointers, have very non-unique
type names. For example, the anonymous function `|a: i32, b: i32| a + b`
has the type name of `fn(i32, i32) -> i32`. This obviously means we'd
conflict with another function like `|a: i32, b: i32| a - b`.
The solution that #14098 landed on was to always require a name during
function registration.
The downside with this is that named functions (e.g. `fn add(a: i32, b:
i32) -> i32 { a + b }`) had to redundantly provide a name. Additionally,
manually constructed `DynamicFunction`s also ran into this ergonomics
issue.
I don't entirely know how the function registry will be used, but I have
a strong suspicion that most of its registrations will either be named
functions or manually constructed `DynamicFunction`s, with anonymous
functions only being used here and there for quick prototyping or adding
small functionality.
Why then should the API prioritize the anonymous function use case by
always requiring a name during registration?
#### Telling Functions Apart
Rust doesn't provide a lot of out-of-the-box tools for reflecting
functions. One of the biggest hurdles in attempting to solve the problem
outlined above would be to somehow tell the different kinds of functions
apart.
Let's briefly recap on the categories of functions in Rust:
| Category | Example |
| ------------------ | ----------------------------------------- |
| Named function | `fn add(a: i32, b: i32) -> i32 { a + b }` |
| Closure | `\|a: i32\| a + captured_variable` |
| Anonymous function | `\|a: i32, b: i32\| a + b` |
| Function pointer | `fn(i32, i32) -> i32` |
My first thought was to try and differentiate these categories based on
their size. However, we can see that this doesn't quite work:
| Category | `size_of` |
| ------------------ | --------- |
| Named function | 0 |
| Closure | 0+ |
| Anonymous function | 0 |
| Function pointer | 8 |
Not only does this not tell anonymous functions from named ones, but it
struggles with pretty much all of them.
My second then was to differentiate based on type name:
| Category | `type_name` |
| ------------------ | ----------------------- |
| Named function | `foo::bar::baz` |
| Closure | `foo::bar::{{closure}}` |
| Anonymous function | `fn() -> String` |
| Function pointer | `fn() -> String` |
This is much better. While it can't distinguish between function
pointers and anonymous functions, this doesn't matter too much since we
only care about whether we can _name_ the function.
So why didn't we implement this in #14098?
#### Relying on `type_name`
While this solution was known about while working on #14098, it was left
out from that PR due to it being potentially controversial.
The [docs](https://doc.rust-lang.org/stable/std/any/fn.type_name.html)
for `std::any::type_name` state:
> The returned string must not be considered to be a unique identifier
of a type as multiple types may map to the same type name. Similarly,
there is no guarantee that all parts of a type will appear in the
returned string: for example, lifetime specifiers are currently not
included. In addition, the output may change between versions of the
compiler.
So that's it then? We can't use `type_name`?
Well, this statement isn't so much a rule as it is a guideline. And Bevy
is no stranger to bending the rules to make things work or to improve
ergonomics. Remember that before `TypePath`, Bevy's scene system was
entirely dependent on `type_name`. Not to mention that `type_name` is
being used as a key into both the `TypeRegistry` and the
`FunctionRegistry`.
Bevy's practices aside, can we reliably use `type_name` for this?
My answer would be "yes".
Anonymous functions are anonymous. They have no name. There's nothing
Rust could do to give them a name apart from generating a random string
of characters. But remember that this is a diagnostic tool, it doesn't
make sense to obfuscate the type by randomizing the output. So changing
it to be anything other than what it is now is very unlikely.
The only changes that I could potentially see happening are:
1. Closures replace `{{closure}}` with the name of their variable
2. Lifetimes are included in the output
I don't think the first is likely to happen, but if it does then it
actually works out in our favor: closures are now named!
The second point is probably the likeliest. However, adding lifetimes
doesn't mean we can't still rely on `type_name` to determine whether or
not a function is named. So we should be okay in this case as well.
## Solution
Parse the `type_name` of the function in the `TypedFunction` impl to
determine if the function is named or anonymous.
This once again makes `FunctionInfo::name` optional. For manual
constructions of `DynamicFunction`, `FunctionInfo::named` or
``FunctionInfo::anonymous` can be used.
The `FunctionRegistry` API has also been reworked to account for this
change.
`FunctionRegistry::register` no longer takes a name and instead takes it
from the supplied function, returning a
`FunctionRegistrationError::MissingName` error if the name is `None`.
This also doubles as a replacement for the old
`FunctionRegistry::register_dynamic` method, which has been removed.
To handle anonymous functions, a `FunctionRegistry::register_with_name`
method has been added. This works in the same way
`FunctionRegistry::register` used to work before this PR.
The overwriting methods have been updated in a similar manner, with
modifications to `FunctionRegistry::overwrite_registration`, the removal
of `FunctionRegistry::overwrite_registration_dynamic`, and the addition
of `FunctionRegistry::overwrite_registration_with_name`.
This PR also updates the methods on `App` in a similar way:
`App::register_function` no longer requires a name argument and
`App::register_function_with_name` has been added to handle anonymous
functions (and eventually closures).
## Testing
You can run the tests locally by running:
```
cargo test --package bevy_reflect --features functions
```
---
## Internal Migration Guide
> [!important]
> Function reflection was introduced as part of the 0.15 dev cycle. This
migration guide was written for developers relying on `main` during this
cycle, and is not a breaking change coming from 0.14.
> [!note]
> This list is not exhaustive. It only contains some of the most
important changes.
`FunctionRegistry::register` no longer requires a name string for named
functions. Anonymous functions, however, need to be registered using
`FunctionRegistry::register_with_name`.
```rust
// BEFORE
registry
.register(std::any::type_name_of_val(&foo), foo)?
.register("bar", || println!("Hello world!"));
// AFTER
registry
.register(foo)?
.register_with_name("bar", || println!("Hello world!"));
```
`FunctionInfo::name` is now optional. Anonymous functions and closures
will now have their name set to `None` by default. Additionally,
`FunctionInfo::new` has been renamed to `FunctionInfo::named`.
2024-08-07 03:11:08 +00:00
|
|
|
pub fn register_function<F, Marker>(&mut self, function: F) -> &mut Self
|
|
|
|
where
|
bevy_reflect: Function reflection terminology refactor (#14813)
# Objective
One of the changes in #14704 made `DynamicFunction` effectively the same
as `DynamicClosure<'static>`. This change meant that the de facto
function type would likely be `DynamicClosure<'static>` instead of the
intended `DynamicFunction`, since the former is much more flexible.
We _could_ explore ways of making `DynamicFunction` implement `Copy`
using some unsafe code, but it likely wouldn't be worth it. And users
would likely still reach for the convenience of
`DynamicClosure<'static>` over the copy-ability of `DynamicFunction`.
The goal of this PR is to fix this confusion between the two types.
## Solution
Firstly, the `DynamicFunction` type was removed. Again, it was no
different than `DynamicClosure<'static>` so it wasn't a huge deal to
remove.
Secondly, `DynamicClosure<'env>` and `DynamicClosureMut<'env>` were
renamed to `DynamicFunction<'env>` and `DynamicFunctionMut<'env>`,
respectively.
Yes, we still ultimately kept the naming of `DynamicFunction`, but
changed its behavior to that of `DynamicClosure<'env>`. We need a term
to refer to both functions and closures, and "function" was the best
option.
[Originally](https://discord.com/channels/691052431525675048/1002362493634629796/1274091992162242710),
I was going to go with "callable" as the replacement term to encompass
both functions and closures (e.g. `DynamciCallable<'env>`). However, it
was
[suggested](https://discord.com/channels/691052431525675048/1002362493634629796/1274653581777047625)
by @SkiFire13 that the simpler "function" term could be used instead.
While "callable" is perhaps the better umbrella term—being truly
ambiguous over functions and closures— "function" is more familiar, used
more often, easier to discover, and is subjectively just
"better-sounding".
## Testing
Most changes are purely swapping type names or updating documentation,
but you can verify everything still works by running the following
command:
```
cargo test --package bevy_reflect
```
2024-08-19 21:52:36 +00:00
|
|
|
F: bevy_reflect::func::IntoFunction<'static, Marker> + 'static,
|
bevy_reflect: Anonymous function parsing (#14641)
# Objective
### TL;DR
#14098 added the `FunctionRegistry` but had some last minute
complications due to anonymous functions. It ended up going with a
"required name" approach to ensure anonymous functions would always have
a name.
However, this approach isn't ideal for named functions since, by
definition, they will always have a name.
Therefore, this PR aims to modify function reflection such that we can
make function registration easier for named functions, while still
allowing anonymous functions to be registered as well.
### Context
Function registration (#14098) ran into a little problem: anonymous
functions.
Anonymous functions, including function pointers, have very non-unique
type names. For example, the anonymous function `|a: i32, b: i32| a + b`
has the type name of `fn(i32, i32) -> i32`. This obviously means we'd
conflict with another function like `|a: i32, b: i32| a - b`.
The solution that #14098 landed on was to always require a name during
function registration.
The downside with this is that named functions (e.g. `fn add(a: i32, b:
i32) -> i32 { a + b }`) had to redundantly provide a name. Additionally,
manually constructed `DynamicFunction`s also ran into this ergonomics
issue.
I don't entirely know how the function registry will be used, but I have
a strong suspicion that most of its registrations will either be named
functions or manually constructed `DynamicFunction`s, with anonymous
functions only being used here and there for quick prototyping or adding
small functionality.
Why then should the API prioritize the anonymous function use case by
always requiring a name during registration?
#### Telling Functions Apart
Rust doesn't provide a lot of out-of-the-box tools for reflecting
functions. One of the biggest hurdles in attempting to solve the problem
outlined above would be to somehow tell the different kinds of functions
apart.
Let's briefly recap on the categories of functions in Rust:
| Category | Example |
| ------------------ | ----------------------------------------- |
| Named function | `fn add(a: i32, b: i32) -> i32 { a + b }` |
| Closure | `\|a: i32\| a + captured_variable` |
| Anonymous function | `\|a: i32, b: i32\| a + b` |
| Function pointer | `fn(i32, i32) -> i32` |
My first thought was to try and differentiate these categories based on
their size. However, we can see that this doesn't quite work:
| Category | `size_of` |
| ------------------ | --------- |
| Named function | 0 |
| Closure | 0+ |
| Anonymous function | 0 |
| Function pointer | 8 |
Not only does this not tell anonymous functions from named ones, but it
struggles with pretty much all of them.
My second then was to differentiate based on type name:
| Category | `type_name` |
| ------------------ | ----------------------- |
| Named function | `foo::bar::baz` |
| Closure | `foo::bar::{{closure}}` |
| Anonymous function | `fn() -> String` |
| Function pointer | `fn() -> String` |
This is much better. While it can't distinguish between function
pointers and anonymous functions, this doesn't matter too much since we
only care about whether we can _name_ the function.
So why didn't we implement this in #14098?
#### Relying on `type_name`
While this solution was known about while working on #14098, it was left
out from that PR due to it being potentially controversial.
The [docs](https://doc.rust-lang.org/stable/std/any/fn.type_name.html)
for `std::any::type_name` state:
> The returned string must not be considered to be a unique identifier
of a type as multiple types may map to the same type name. Similarly,
there is no guarantee that all parts of a type will appear in the
returned string: for example, lifetime specifiers are currently not
included. In addition, the output may change between versions of the
compiler.
So that's it then? We can't use `type_name`?
Well, this statement isn't so much a rule as it is a guideline. And Bevy
is no stranger to bending the rules to make things work or to improve
ergonomics. Remember that before `TypePath`, Bevy's scene system was
entirely dependent on `type_name`. Not to mention that `type_name` is
being used as a key into both the `TypeRegistry` and the
`FunctionRegistry`.
Bevy's practices aside, can we reliably use `type_name` for this?
My answer would be "yes".
Anonymous functions are anonymous. They have no name. There's nothing
Rust could do to give them a name apart from generating a random string
of characters. But remember that this is a diagnostic tool, it doesn't
make sense to obfuscate the type by randomizing the output. So changing
it to be anything other than what it is now is very unlikely.
The only changes that I could potentially see happening are:
1. Closures replace `{{closure}}` with the name of their variable
2. Lifetimes are included in the output
I don't think the first is likely to happen, but if it does then it
actually works out in our favor: closures are now named!
The second point is probably the likeliest. However, adding lifetimes
doesn't mean we can't still rely on `type_name` to determine whether or
not a function is named. So we should be okay in this case as well.
## Solution
Parse the `type_name` of the function in the `TypedFunction` impl to
determine if the function is named or anonymous.
This once again makes `FunctionInfo::name` optional. For manual
constructions of `DynamicFunction`, `FunctionInfo::named` or
``FunctionInfo::anonymous` can be used.
The `FunctionRegistry` API has also been reworked to account for this
change.
`FunctionRegistry::register` no longer takes a name and instead takes it
from the supplied function, returning a
`FunctionRegistrationError::MissingName` error if the name is `None`.
This also doubles as a replacement for the old
`FunctionRegistry::register_dynamic` method, which has been removed.
To handle anonymous functions, a `FunctionRegistry::register_with_name`
method has been added. This works in the same way
`FunctionRegistry::register` used to work before this PR.
The overwriting methods have been updated in a similar manner, with
modifications to `FunctionRegistry::overwrite_registration`, the removal
of `FunctionRegistry::overwrite_registration_dynamic`, and the addition
of `FunctionRegistry::overwrite_registration_with_name`.
This PR also updates the methods on `App` in a similar way:
`App::register_function` no longer requires a name argument and
`App::register_function_with_name` has been added to handle anonymous
functions (and eventually closures).
## Testing
You can run the tests locally by running:
```
cargo test --package bevy_reflect --features functions
```
---
## Internal Migration Guide
> [!important]
> Function reflection was introduced as part of the 0.15 dev cycle. This
migration guide was written for developers relying on `main` during this
cycle, and is not a breaking change coming from 0.14.
> [!note]
> This list is not exhaustive. It only contains some of the most
important changes.
`FunctionRegistry::register` no longer requires a name string for named
functions. Anonymous functions, however, need to be registered using
`FunctionRegistry::register_with_name`.
```rust
// BEFORE
registry
.register(std::any::type_name_of_val(&foo), foo)?
.register("bar", || println!("Hello world!"));
// AFTER
registry
.register(foo)?
.register_with_name("bar", || println!("Hello world!"));
```
`FunctionInfo::name` is now optional. Anonymous functions and closures
will now have their name set to `None` by default. Additionally,
`FunctionInfo::new` has been renamed to `FunctionInfo::named`.
2024-08-07 03:11:08 +00:00
|
|
|
{
|
|
|
|
let registry = self.world.resource_mut::<AppFunctionRegistry>();
|
|
|
|
registry.write().register(function).unwrap();
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`App::register_function_with_name`].
|
|
|
|
#[cfg(feature = "reflect_functions")]
|
|
|
|
pub fn register_function_with_name<F, Marker>(
|
bevy_reflect: Function registry (#14098)
# Objective
#13152 added support for reflecting functions. Now, we need a way to
register those functions such that they may be accessed anywhere within
the ECS.
## Solution
Added a `FunctionRegistry` type similar to `TypeRegistry`.
This allows a function to be registered and retrieved by name.
```rust
fn foo() -> i32 {
123
}
let mut registry = FunctionRegistry::default();
registry.register("my_function", foo);
let function = registry.get_mut("my_function").unwrap();
let value = function.call(ArgList::new()).unwrap().unwrap_owned();
assert_eq!(value.downcast_ref::<i32>(), Some(&123));
```
Additionally, I added an `AppFunctionRegistry` resource which wraps a
`FunctionRegistryArc`. Functions can be registered into this resource
using `App::register_function` or by getting a mutable reference to the
resource itself.
### Limitations
#### `Send + Sync`
In order to get this registry to work across threads, it needs to be
`Send + Sync`. This means that `DynamicFunction` needs to be `Send +
Sync`, which means that its internal function also needs to be `Send +
Sync`.
In most cases, this won't be an issue because standard Rust functions
(the type most likely to be registered) are always `Send + Sync`.
Additionally, closures tend to be `Send + Sync` as well, granted they
don't capture any `!Send` or `!Sync` variables.
This PR adds this `Send + Sync` requirement, but as mentioned above, it
hopefully shouldn't be too big of an issue.
#### Closures
Unfortunately, closures can't be registered yet. This will likely be
explored and added in a followup PR.
### Future Work
Besides addressing the limitations listed above, another thing we could
look into is improving the lookup of registered functions. One aspect is
in the performance of hashing strings. The other is in the developer
experience of having to call `std::any::type_name_of_val` to get the
name of their function (assuming they didn't give it a custom name).
## Testing
You can run the tests locally with:
```
cargo test --package bevy_reflect
```
---
## Changelog
- Added `FunctionRegistry`
- Added `AppFunctionRegistry` (a `Resource` available from `bevy_ecs`)
- Added `FunctionRegistryArc`
- Added `FunctionRegistrationError`
- Added `reflect_functions` feature to `bevy_ecs` and `bevy_app`
- `FunctionInfo` is no longer `Default`
- `DynamicFunction` now requires its wrapped function be `Send + Sync`
## Internal Migration Guide
> [!important]
> Function reflection was introduced as part of the 0.15 dev cycle. This
migration guide was written for developers relying on `main` during this
cycle, and is not a breaking change coming from 0.14.
`DynamicFunction` (both those created manually and those created with
`IntoFunction`), now require `Send + Sync`. All standard Rust functions
should meet that requirement. Closures, on the other hand, may not if
they capture any `!Send` or `!Sync` variables from its environment.
2024-08-06 01:09:48 +00:00
|
|
|
&mut self,
|
|
|
|
name: impl Into<std::borrow::Cow<'static, str>>,
|
|
|
|
function: F,
|
|
|
|
) -> &mut Self
|
|
|
|
where
|
bevy_reflect: Function reflection terminology refactor (#14813)
# Objective
One of the changes in #14704 made `DynamicFunction` effectively the same
as `DynamicClosure<'static>`. This change meant that the de facto
function type would likely be `DynamicClosure<'static>` instead of the
intended `DynamicFunction`, since the former is much more flexible.
We _could_ explore ways of making `DynamicFunction` implement `Copy`
using some unsafe code, but it likely wouldn't be worth it. And users
would likely still reach for the convenience of
`DynamicClosure<'static>` over the copy-ability of `DynamicFunction`.
The goal of this PR is to fix this confusion between the two types.
## Solution
Firstly, the `DynamicFunction` type was removed. Again, it was no
different than `DynamicClosure<'static>` so it wasn't a huge deal to
remove.
Secondly, `DynamicClosure<'env>` and `DynamicClosureMut<'env>` were
renamed to `DynamicFunction<'env>` and `DynamicFunctionMut<'env>`,
respectively.
Yes, we still ultimately kept the naming of `DynamicFunction`, but
changed its behavior to that of `DynamicClosure<'env>`. We need a term
to refer to both functions and closures, and "function" was the best
option.
[Originally](https://discord.com/channels/691052431525675048/1002362493634629796/1274091992162242710),
I was going to go with "callable" as the replacement term to encompass
both functions and closures (e.g. `DynamciCallable<'env>`). However, it
was
[suggested](https://discord.com/channels/691052431525675048/1002362493634629796/1274653581777047625)
by @SkiFire13 that the simpler "function" term could be used instead.
While "callable" is perhaps the better umbrella term—being truly
ambiguous over functions and closures— "function" is more familiar, used
more often, easier to discover, and is subjectively just
"better-sounding".
## Testing
Most changes are purely swapping type names or updating documentation,
but you can verify everything still works by running the following
command:
```
cargo test --package bevy_reflect
```
2024-08-19 21:52:36 +00:00
|
|
|
F: bevy_reflect::func::IntoFunction<'static, Marker> + 'static,
|
bevy_reflect: Function registry (#14098)
# Objective
#13152 added support for reflecting functions. Now, we need a way to
register those functions such that they may be accessed anywhere within
the ECS.
## Solution
Added a `FunctionRegistry` type similar to `TypeRegistry`.
This allows a function to be registered and retrieved by name.
```rust
fn foo() -> i32 {
123
}
let mut registry = FunctionRegistry::default();
registry.register("my_function", foo);
let function = registry.get_mut("my_function").unwrap();
let value = function.call(ArgList::new()).unwrap().unwrap_owned();
assert_eq!(value.downcast_ref::<i32>(), Some(&123));
```
Additionally, I added an `AppFunctionRegistry` resource which wraps a
`FunctionRegistryArc`. Functions can be registered into this resource
using `App::register_function` or by getting a mutable reference to the
resource itself.
### Limitations
#### `Send + Sync`
In order to get this registry to work across threads, it needs to be
`Send + Sync`. This means that `DynamicFunction` needs to be `Send +
Sync`, which means that its internal function also needs to be `Send +
Sync`.
In most cases, this won't be an issue because standard Rust functions
(the type most likely to be registered) are always `Send + Sync`.
Additionally, closures tend to be `Send + Sync` as well, granted they
don't capture any `!Send` or `!Sync` variables.
This PR adds this `Send + Sync` requirement, but as mentioned above, it
hopefully shouldn't be too big of an issue.
#### Closures
Unfortunately, closures can't be registered yet. This will likely be
explored and added in a followup PR.
### Future Work
Besides addressing the limitations listed above, another thing we could
look into is improving the lookup of registered functions. One aspect is
in the performance of hashing strings. The other is in the developer
experience of having to call `std::any::type_name_of_val` to get the
name of their function (assuming they didn't give it a custom name).
## Testing
You can run the tests locally with:
```
cargo test --package bevy_reflect
```
---
## Changelog
- Added `FunctionRegistry`
- Added `AppFunctionRegistry` (a `Resource` available from `bevy_ecs`)
- Added `FunctionRegistryArc`
- Added `FunctionRegistrationError`
- Added `reflect_functions` feature to `bevy_ecs` and `bevy_app`
- `FunctionInfo` is no longer `Default`
- `DynamicFunction` now requires its wrapped function be `Send + Sync`
## Internal Migration Guide
> [!important]
> Function reflection was introduced as part of the 0.15 dev cycle. This
migration guide was written for developers relying on `main` during this
cycle, and is not a breaking change coming from 0.14.
`DynamicFunction` (both those created manually and those created with
`IntoFunction`), now require `Send + Sync`. All standard Rust functions
should meet that requirement. Closures, on the other hand, may not if
they capture any `!Send` or `!Sync` variables from its environment.
2024-08-06 01:09:48 +00:00
|
|
|
{
|
|
|
|
let registry = self.world.resource_mut::<AppFunctionRegistry>();
|
bevy_reflect: Anonymous function parsing (#14641)
# Objective
### TL;DR
#14098 added the `FunctionRegistry` but had some last minute
complications due to anonymous functions. It ended up going with a
"required name" approach to ensure anonymous functions would always have
a name.
However, this approach isn't ideal for named functions since, by
definition, they will always have a name.
Therefore, this PR aims to modify function reflection such that we can
make function registration easier for named functions, while still
allowing anonymous functions to be registered as well.
### Context
Function registration (#14098) ran into a little problem: anonymous
functions.
Anonymous functions, including function pointers, have very non-unique
type names. For example, the anonymous function `|a: i32, b: i32| a + b`
has the type name of `fn(i32, i32) -> i32`. This obviously means we'd
conflict with another function like `|a: i32, b: i32| a - b`.
The solution that #14098 landed on was to always require a name during
function registration.
The downside with this is that named functions (e.g. `fn add(a: i32, b:
i32) -> i32 { a + b }`) had to redundantly provide a name. Additionally,
manually constructed `DynamicFunction`s also ran into this ergonomics
issue.
I don't entirely know how the function registry will be used, but I have
a strong suspicion that most of its registrations will either be named
functions or manually constructed `DynamicFunction`s, with anonymous
functions only being used here and there for quick prototyping or adding
small functionality.
Why then should the API prioritize the anonymous function use case by
always requiring a name during registration?
#### Telling Functions Apart
Rust doesn't provide a lot of out-of-the-box tools for reflecting
functions. One of the biggest hurdles in attempting to solve the problem
outlined above would be to somehow tell the different kinds of functions
apart.
Let's briefly recap on the categories of functions in Rust:
| Category | Example |
| ------------------ | ----------------------------------------- |
| Named function | `fn add(a: i32, b: i32) -> i32 { a + b }` |
| Closure | `\|a: i32\| a + captured_variable` |
| Anonymous function | `\|a: i32, b: i32\| a + b` |
| Function pointer | `fn(i32, i32) -> i32` |
My first thought was to try and differentiate these categories based on
their size. However, we can see that this doesn't quite work:
| Category | `size_of` |
| ------------------ | --------- |
| Named function | 0 |
| Closure | 0+ |
| Anonymous function | 0 |
| Function pointer | 8 |
Not only does this not tell anonymous functions from named ones, but it
struggles with pretty much all of them.
My second then was to differentiate based on type name:
| Category | `type_name` |
| ------------------ | ----------------------- |
| Named function | `foo::bar::baz` |
| Closure | `foo::bar::{{closure}}` |
| Anonymous function | `fn() -> String` |
| Function pointer | `fn() -> String` |
This is much better. While it can't distinguish between function
pointers and anonymous functions, this doesn't matter too much since we
only care about whether we can _name_ the function.
So why didn't we implement this in #14098?
#### Relying on `type_name`
While this solution was known about while working on #14098, it was left
out from that PR due to it being potentially controversial.
The [docs](https://doc.rust-lang.org/stable/std/any/fn.type_name.html)
for `std::any::type_name` state:
> The returned string must not be considered to be a unique identifier
of a type as multiple types may map to the same type name. Similarly,
there is no guarantee that all parts of a type will appear in the
returned string: for example, lifetime specifiers are currently not
included. In addition, the output may change between versions of the
compiler.
So that's it then? We can't use `type_name`?
Well, this statement isn't so much a rule as it is a guideline. And Bevy
is no stranger to bending the rules to make things work or to improve
ergonomics. Remember that before `TypePath`, Bevy's scene system was
entirely dependent on `type_name`. Not to mention that `type_name` is
being used as a key into both the `TypeRegistry` and the
`FunctionRegistry`.
Bevy's practices aside, can we reliably use `type_name` for this?
My answer would be "yes".
Anonymous functions are anonymous. They have no name. There's nothing
Rust could do to give them a name apart from generating a random string
of characters. But remember that this is a diagnostic tool, it doesn't
make sense to obfuscate the type by randomizing the output. So changing
it to be anything other than what it is now is very unlikely.
The only changes that I could potentially see happening are:
1. Closures replace `{{closure}}` with the name of their variable
2. Lifetimes are included in the output
I don't think the first is likely to happen, but if it does then it
actually works out in our favor: closures are now named!
The second point is probably the likeliest. However, adding lifetimes
doesn't mean we can't still rely on `type_name` to determine whether or
not a function is named. So we should be okay in this case as well.
## Solution
Parse the `type_name` of the function in the `TypedFunction` impl to
determine if the function is named or anonymous.
This once again makes `FunctionInfo::name` optional. For manual
constructions of `DynamicFunction`, `FunctionInfo::named` or
``FunctionInfo::anonymous` can be used.
The `FunctionRegistry` API has also been reworked to account for this
change.
`FunctionRegistry::register` no longer takes a name and instead takes it
from the supplied function, returning a
`FunctionRegistrationError::MissingName` error if the name is `None`.
This also doubles as a replacement for the old
`FunctionRegistry::register_dynamic` method, which has been removed.
To handle anonymous functions, a `FunctionRegistry::register_with_name`
method has been added. This works in the same way
`FunctionRegistry::register` used to work before this PR.
The overwriting methods have been updated in a similar manner, with
modifications to `FunctionRegistry::overwrite_registration`, the removal
of `FunctionRegistry::overwrite_registration_dynamic`, and the addition
of `FunctionRegistry::overwrite_registration_with_name`.
This PR also updates the methods on `App` in a similar way:
`App::register_function` no longer requires a name argument and
`App::register_function_with_name` has been added to handle anonymous
functions (and eventually closures).
## Testing
You can run the tests locally by running:
```
cargo test --package bevy_reflect --features functions
```
---
## Internal Migration Guide
> [!important]
> Function reflection was introduced as part of the 0.15 dev cycle. This
migration guide was written for developers relying on `main` during this
cycle, and is not a breaking change coming from 0.14.
> [!note]
> This list is not exhaustive. It only contains some of the most
important changes.
`FunctionRegistry::register` no longer requires a name string for named
functions. Anonymous functions, however, need to be registered using
`FunctionRegistry::register_with_name`.
```rust
// BEFORE
registry
.register(std::any::type_name_of_val(&foo), foo)?
.register("bar", || println!("Hello world!"));
// AFTER
registry
.register(foo)?
.register_with_name("bar", || println!("Hello world!"));
```
`FunctionInfo::name` is now optional. Anonymous functions and closures
will now have their name set to `None` by default. Additionally,
`FunctionInfo::new` has been renamed to `FunctionInfo::named`.
2024-08-07 03:11:08 +00:00
|
|
|
registry.write().register_with_name(name, function).unwrap();
|
bevy_reflect: Function registry (#14098)
# Objective
#13152 added support for reflecting functions. Now, we need a way to
register those functions such that they may be accessed anywhere within
the ECS.
## Solution
Added a `FunctionRegistry` type similar to `TypeRegistry`.
This allows a function to be registered and retrieved by name.
```rust
fn foo() -> i32 {
123
}
let mut registry = FunctionRegistry::default();
registry.register("my_function", foo);
let function = registry.get_mut("my_function").unwrap();
let value = function.call(ArgList::new()).unwrap().unwrap_owned();
assert_eq!(value.downcast_ref::<i32>(), Some(&123));
```
Additionally, I added an `AppFunctionRegistry` resource which wraps a
`FunctionRegistryArc`. Functions can be registered into this resource
using `App::register_function` or by getting a mutable reference to the
resource itself.
### Limitations
#### `Send + Sync`
In order to get this registry to work across threads, it needs to be
`Send + Sync`. This means that `DynamicFunction` needs to be `Send +
Sync`, which means that its internal function also needs to be `Send +
Sync`.
In most cases, this won't be an issue because standard Rust functions
(the type most likely to be registered) are always `Send + Sync`.
Additionally, closures tend to be `Send + Sync` as well, granted they
don't capture any `!Send` or `!Sync` variables.
This PR adds this `Send + Sync` requirement, but as mentioned above, it
hopefully shouldn't be too big of an issue.
#### Closures
Unfortunately, closures can't be registered yet. This will likely be
explored and added in a followup PR.
### Future Work
Besides addressing the limitations listed above, another thing we could
look into is improving the lookup of registered functions. One aspect is
in the performance of hashing strings. The other is in the developer
experience of having to call `std::any::type_name_of_val` to get the
name of their function (assuming they didn't give it a custom name).
## Testing
You can run the tests locally with:
```
cargo test --package bevy_reflect
```
---
## Changelog
- Added `FunctionRegistry`
- Added `AppFunctionRegistry` (a `Resource` available from `bevy_ecs`)
- Added `FunctionRegistryArc`
- Added `FunctionRegistrationError`
- Added `reflect_functions` feature to `bevy_ecs` and `bevy_app`
- `FunctionInfo` is no longer `Default`
- `DynamicFunction` now requires its wrapped function be `Send + Sync`
## Internal Migration Guide
> [!important]
> Function reflection was introduced as part of the 0.15 dev cycle. This
migration guide was written for developers relying on `main` during this
cycle, and is not a breaking change coming from 0.14.
`DynamicFunction` (both those created manually and those created with
`IntoFunction`), now require `Send + Sync`. All standard Rust functions
should meet that requirement. Closures, on the other hand, may not if
they capture any `!Send` or `!Sync` variables from its environment.
2024-08-06 01:09:48 +00:00
|
|
|
self
|
|
|
|
}
|
2024-03-31 03:16:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// The collection of sub-apps that belong to an [`App`].
|
|
|
|
#[derive(Default)]
|
|
|
|
pub struct SubApps {
|
|
|
|
/// The primary sub-app that contains the "main" world.
|
|
|
|
pub main: SubApp,
|
|
|
|
/// Other, labeled sub-apps.
|
|
|
|
pub sub_apps: HashMap<InternedAppLabel, SubApp>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl SubApps {
|
|
|
|
/// Calls [`update`](SubApp::update) for the main sub-app, and then calls
|
|
|
|
/// [`extract`](SubApp::extract) and [`update`](SubApp::update) for the rest.
|
|
|
|
pub fn update(&mut self) {
|
|
|
|
#[cfg(feature = "trace")]
|
|
|
|
let _bevy_update_span = info_span!("update").entered();
|
|
|
|
{
|
|
|
|
#[cfg(feature = "trace")]
|
|
|
|
let _bevy_frame_update_span = info_span!("main app").entered();
|
Remove extra call to clear_trackers (#13762)
Fixes #13758.
# Objective
Calling `update` on the main app already calls `clear_trackers`. Calling
it again in `SubApps::update` caused RemovedCompenet Events to be
cleared earlier than they should be.
## Solution
- Don't call clear_trackers an extra time.
## Testing
I manually tested the fix with this unit test:
```
#[cfg(test)]
mod test {
use crate::core::{FrameCount, FrameCountPlugin};
use crate::prelude::*;
#[test]
fn test_next_frame_removal() {
#[derive(Component)]
struct Foo;
#[derive(Resource)]
struct RemovedCount(usize);
let mut app = App::new();
app.add_plugins(FrameCountPlugin);
app.add_systems(Startup, |mut commands: Commands| {
for _ in 0..100 {
commands.spawn(Foo);
}
commands.insert_resource(RemovedCount(0));
});
app.add_systems(First, |counter: Res<FrameCount>| {
println!("Frame {}:", counter.0)
});
fn detector_system(
mut removals: RemovedComponents<Foo>,
foos: Query<Entity, With<Foo>>,
mut removed_c: ResMut<RemovedCount>,
) {
for e in removals.read() {
println!(" Detected removed Foo component for {e:?}");
removed_c.0 += 1;
}
let c = foos.iter().count();
println!(" Total Foos: {}", c);
assert_eq!(c + removed_c.0, 100);
}
fn deleter_system(foos: Query<Entity, With<Foo>>, mut commands: Commands) {
foos.iter().next().map(|e| {
commands.entity(e).remove::<Foo>();
});
}
app.add_systems(Update, (detector_system, deleter_system).chain());
app.update();
app.update();
app.update();
app.update();
}
}
```
2024-06-10 18:06:05 +00:00
|
|
|
self.main.run_default_schedule();
|
2024-03-31 03:16:10 +00:00
|
|
|
}
|
|
|
|
for (_label, sub_app) in self.sub_apps.iter_mut() {
|
|
|
|
#[cfg(feature = "trace")]
|
|
|
|
let _sub_app_span = info_span!("sub app", name = ?_label).entered();
|
|
|
|
sub_app.extract(&mut self.main.world);
|
|
|
|
sub_app.update();
|
|
|
|
}
|
|
|
|
|
|
|
|
self.main.world.clear_trackers();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns an iterator over the sub-apps (starting with the main one).
|
|
|
|
pub fn iter(&self) -> impl Iterator<Item = &SubApp> + '_ {
|
|
|
|
std::iter::once(&self.main).chain(self.sub_apps.values())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a mutable iterator over the sub-apps (starting with the main one).
|
|
|
|
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut SubApp> + '_ {
|
|
|
|
std::iter::once(&mut self.main).chain(self.sub_apps.values_mut())
|
|
|
|
}
|
2024-06-25 14:04:31 +00:00
|
|
|
|
|
|
|
/// Extract data from the main world into the [`SubApp`] with the given label and perform an update if it exists.
|
|
|
|
pub fn update_subapp_by_label(&mut self, label: impl AppLabel) {
|
|
|
|
if let Some(sub_app) = self.sub_apps.get_mut(&label.intern()) {
|
|
|
|
sub_app.extract(&mut self.main.world);
|
|
|
|
sub_app.update();
|
|
|
|
}
|
|
|
|
}
|
2024-03-31 03:16:10 +00:00
|
|
|
}
|