bevy/crates/bevy_scene/src/bundle.rs
Christian Hughes 584d14808a
Allow World::entity family of functions to take multiple entities and get multiple references back (#15614)
# Objective

Following the pattern established in #15593, we can reduce the API
surface of `World` by providing a single function to grab both a
singular entity reference, or multiple entity references.

## Solution

The following functions can now also take multiple entity IDs and will
return multiple entity references back:
- `World::entity`
- `World::get_entity`
- `World::entity_mut`
- `World::get_entity_mut`
- `DeferredWorld::entity_mut`
- `DeferredWorld::get_entity_mut`

If you pass in X, you receive Y:
- give a single `Entity`, receive a single `EntityRef`/`EntityWorldMut`
(matches current behavior)
- give a `[Entity; N]`/`&[Entity; N]` (array), receive an equally-sized
`[EntityRef; N]`/`[EntityMut; N]`
- give a `&[Entity]` (slice), receive a
`Vec<EntityRef>`/`Vec<EntityMut>`
- give a `&EntityHashSet`, receive a
`EntityHashMap<EntityRef>`/`EntityHashMap<EntityMut>`

Note that `EntityWorldMut` is only returned in the single-entity case,
because having multiple at the same time would lead to UB. Also,
`DeferredWorld` receives an `EntityMut` in the single-entity case
because it does not allow structural access.

## Testing

- Added doc-tests on `World::entity`, `World::entity_mut`, and
`DeferredWorld::entity_mut`
- Added tests for aliased mutability and entity existence

---

## Showcase

<details>
  <summary>Click to view showcase</summary>

The APIs for fetching `EntityRef`s and `EntityMut`s from the `World`
have been unified.

```rust
// This code will be referred to by subsequent code blocks.
let world = World::new();
let e1 = world.spawn_empty().id();
let e2 = world.spawn_empty().id();
let e3 = world.spawn_empty().id();
```

Querying for a single entity remains mostly the same:

```rust
// 0.14
let eref: EntityRef = world.entity(e1);
let emut: EntityWorldMut = world.entity_mut(e1);
let eref: Option<EntityRef> = world.get_entity(e1);
let emut: Option<EntityWorldMut> = world.get_entity_mut(e1);

// 0.15
let eref: EntityRef = world.entity(e1);
let emut: EntityWorldMut = world.entity_mut(e1);
let eref: Result<EntityRef, Entity> = world.get_entity(e1);
let emut: Result<EntityWorldMut, Entity> = world.get_entity_mut(e1);
```

Querying for multiple entities with an array has changed:

```rust
// 0.14
let erefs: [EntityRef; 2] = world.many_entities([e1, e2]);
let emuts: [EntityMut; 2] = world.many_entities_mut([e1, e2]);
let erefs: Result<[EntityRef; 2], Entity> = world.get_many_entities([e1, e2]);
let emuts: Result<[EntityMut; 2], QueryEntityError> = world.get_many_entities_mut([e1, e2]);

// 0.15
let erefs: [EntityRef; 2] = world.entity([e1, e2]);
let emuts: [EntityMut; 2] = world.entity_mut([e1, e2]);
let erefs: Result<[EntityRef; 2], Entity> = world.get_entity([e1, e2]);
let emuts: Result<[EntityMut; 2], EntityFetchError> = world.get_entity_mut([e1, e2]);
```

Querying for multiple entities with a slice has changed:

```rust
let ids = vec![e1, e2, e3]);

// 0.14
let erefs: Result<Vec<EntityRef>, Entity> = world.get_many_entities_dynamic(&ids[..]);
let emuts: Result<Vec<EntityMut>, QueryEntityError> = world.get_many_entities_dynamic_mut(&ids[..]);

// 0.15
let erefs: Result<Vec<EntityRef>, Entity> = world.get_entity(&ids[..]);
let emuts: Result<Vec<EntityMut>, EntityFetchError> = world.get_entity_mut(&ids[..]);
let erefs: Vec<EntityRef> = world.entity(&ids[..]); // Newly possible!
let emuts: Vec<EntityMut> = world.entity_mut(&ids[..]); // Newly possible!
```

Querying for multiple entities with an `EntityHashSet` has changed:

```rust
let set = EntityHashSet::from_iter([e1, e2, e3]);

// 0.14
let emuts: Result<Vec<EntityMut>, QueryEntityError> = world.get_many_entities_from_set_mut(&set);

// 0.15
let emuts: Result<EntityHashMap<EntityMut>, EntityFetchError> = world.get_entity_mut(&set);
let erefs: Result<EntityHashMap<EntityRef>, EntityFetchError> = world.get_entity(&set); // Newly possible!
let emuts: EntityHashMap<EntityMut> = world.entity_mut(&set); // Newly possible!
let erefs: EntityHashMap<EntityRef> = world.entity(&set); // Newly possible!
```

</details>

## Migration Guide

- `World::get_entity` now returns `Result<_, Entity>` instead of
`Option<_>`.
- Use `world.get_entity(..).ok()` to return to the previous behavior.
- `World::get_entity_mut` and `DeferredWorld::get_entity_mut` now return
`Result<_, EntityFetchError>` instead of `Option<_>`.
- Use `world.get_entity_mut(..).ok()` to return to the previous
behavior.
- Type inference for `World::entity`, `World::entity_mut`,
`World::get_entity`, `World::get_entity_mut`,
`DeferredWorld::entity_mut`, and `DeferredWorld::get_entity_mut` has
changed, and might now require the input argument's type to be
explicitly written when inside closures.
- The following functions have been deprecated, and should be replaced
as such:
    - `World::many_entities` -> `World::entity::<[Entity; N]>`
    - `World::many_entities_mut` -> `World::entity_mut::<[Entity; N]>`
    - `World::get_many_entities` -> `World::get_entity::<[Entity; N]>`
- `World::get_many_entities_dynamic` -> `World::get_entity::<&[Entity]>`
- `World::get_many_entities_mut` -> `World::get_entity_mut::<[Entity;
N]>`
- The equivalent return type has changed from `Result<_,
QueryEntityError>` to `Result<_, EntityFetchError>`
- `World::get_many_entities_dynamic_mut` ->
`World::get_entity_mut::<&[Entity]>1
- The equivalent return type has changed from `Result<_,
QueryEntityError>` to `Result<_, EntityFetchError>`
- `World::get_many_entities_from_set_mut` ->
`World::get_entity_mut::<&EntityHashSet>`
- The equivalent return type has changed from `Result<Vec<EntityMut>,
QueryEntityError>` to `Result<EntityHashMap<EntityMut>,
EntityFetchError>`. If necessary, you can still convert the
`EntityHashMap` into a `Vec`.
2024-10-07 15:21:40 +00:00

189 lines
6.8 KiB
Rust

#![expect(deprecated)]
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
bundle::Bundle,
change_detection::ResMut,
entity::Entity,
prelude::{Changed, Component, Without},
system::{Commands, Query},
};
#[cfg(feature = "bevy_render")]
use bevy_render::prelude::{InheritedVisibility, ViewVisibility, Visibility};
use bevy_transform::components::{GlobalTransform, Transform};
use crate::{DynamicSceneRoot, InstanceId, SceneRoot, SceneSpawner};
/// [`InstanceId`] of a spawned scene. It can be used with the [`SceneSpawner`] to
/// interact with the spawned scene.
#[derive(Component, Deref, DerefMut)]
pub struct SceneInstance(pub(crate) InstanceId);
/// A component bundle for a [`Scene`](crate::Scene) root.
///
/// The scene from `scene` will be spawned as a child of the entity with this component.
/// Once it's spawned, the entity will have a [`SceneInstance`] component.
#[derive(Default, Bundle, Clone)]
#[deprecated(
since = "0.15.0",
note = "Use the `SceneRoot` component instead. Inserting `SceneRoot` will also insert the other components required by scenes automatically."
)]
pub struct SceneBundle {
/// Handle to the scene to spawn.
pub scene: SceneRoot,
/// Transform of the scene root entity.
pub transform: Transform,
/// Global transform of the scene root entity.
pub global_transform: GlobalTransform,
/// User-driven visibility of the scene root entity.
#[cfg(feature = "bevy_render")]
pub visibility: Visibility,
/// Inherited visibility of the scene root entity.
#[cfg(feature = "bevy_render")]
pub inherited_visibility: InheritedVisibility,
/// Algorithmically-computed visibility of the scene root entity for rendering.
#[cfg(feature = "bevy_render")]
pub view_visibility: ViewVisibility,
}
/// A component bundle for a [`DynamicScene`](crate::DynamicScene) root.
///
/// The dynamic scene from `scene` will be spawn as a child of the entity with this component.
/// Once it's spawned, the entity will have a [`SceneInstance`] component.
#[derive(Default, Bundle, Clone)]
#[deprecated(
since = "0.15.0",
note = "Use the `DynamicSceneRoot` component instead. Inserting `DynamicSceneRoot` will also insert the other components required by scenes automatically."
)]
pub struct DynamicSceneBundle {
/// Handle to the scene to spawn.
pub scene: DynamicSceneRoot,
/// Transform of the scene root entity.
pub transform: Transform,
/// Global transform of the scene root entity.
pub global_transform: GlobalTransform,
/// User-driven visibility of the scene root entity.
#[cfg(feature = "bevy_render")]
pub visibility: Visibility,
/// Inherited visibility of the scene root entity.
#[cfg(feature = "bevy_render")]
pub inherited_visibility: InheritedVisibility,
/// Algorithmically-computed visibility of the scene root entity for rendering.
#[cfg(feature = "bevy_render")]
pub view_visibility: ViewVisibility,
}
/// System that will spawn scenes from the [`SceneRoot`] and [`DynamicSceneRoot`] components.
pub fn scene_spawner(
mut commands: Commands,
mut scene_to_spawn: Query<
(Entity, &SceneRoot, Option<&mut SceneInstance>),
(Changed<SceneRoot>, Without<DynamicSceneRoot>),
>,
mut dynamic_scene_to_spawn: Query<
(Entity, &DynamicSceneRoot, Option<&mut SceneInstance>),
(Changed<DynamicSceneRoot>, Without<SceneRoot>),
>,
mut scene_spawner: ResMut<SceneSpawner>,
) {
for (entity, scene, instance) in &mut scene_to_spawn {
let new_instance = scene_spawner.spawn_as_child(scene.0.clone(), entity);
if let Some(mut old_instance) = instance {
scene_spawner.despawn_instance(**old_instance);
*old_instance = SceneInstance(new_instance);
} else {
commands.entity(entity).insert(SceneInstance(new_instance));
}
}
for (entity, dynamic_scene, instance) in &mut dynamic_scene_to_spawn {
let new_instance = scene_spawner.spawn_dynamic_as_child(dynamic_scene.0.clone(), entity);
if let Some(mut old_instance) = instance {
scene_spawner.despawn_instance(**old_instance);
*old_instance = SceneInstance(new_instance);
} else {
commands.entity(entity).insert(SceneInstance(new_instance));
}
}
}
#[cfg(test)]
mod tests {
use crate::{DynamicScene, DynamicSceneRoot, ScenePlugin, SceneSpawner};
use bevy_app::{App, ScheduleRunnerPlugin};
use bevy_asset::{AssetPlugin, Assets};
use bevy_ecs::{
component::Component,
entity::Entity,
prelude::{AppTypeRegistry, ReflectComponent, World},
};
use bevy_hierarchy::{Children, HierarchyPlugin};
use bevy_reflect::Reflect;
#[derive(Component, Reflect, Default)]
#[reflect(Component)]
struct ComponentA {
pub x: f32,
pub y: f32,
}
#[test]
fn spawn_and_delete() {
let mut app = App::new();
app.add_plugins(ScheduleRunnerPlugin::default())
.add_plugins(HierarchyPlugin)
.add_plugins(AssetPlugin::default())
.add_plugins(ScenePlugin)
.register_type::<ComponentA>();
app.update();
let mut scene_world = World::new();
// create a new DynamicScene manually
let type_registry = app.world().resource::<AppTypeRegistry>().clone();
scene_world.insert_resource(type_registry);
scene_world.spawn(ComponentA { x: 3.0, y: 4.0 });
let scene = DynamicScene::from_world(&scene_world);
let scene_handle = app
.world_mut()
.resource_mut::<Assets<DynamicScene>>()
.add(scene);
// spawn the scene as a child of `entity` using `DynamicSceneRoot`
let entity = app
.world_mut()
.spawn(DynamicSceneRoot(scene_handle.clone()))
.id();
// run the app's schedule once, so that the scene gets spawned
app.update();
// make sure that the scene was added as a child of the root entity
let (scene_entity, scene_component_a) = app
.world_mut()
.query::<(Entity, &ComponentA)>()
.single(app.world());
assert_eq!(scene_component_a.x, 3.0);
assert_eq!(scene_component_a.y, 4.0);
assert_eq!(
app.world().entity(entity).get::<Children>().unwrap().len(),
1
);
// let's try to delete the scene
let mut scene_spawner = app.world_mut().resource_mut::<SceneSpawner>();
scene_spawner.despawn(&scene_handle);
// run the scene spawner system to despawn the scene
app.update();
// the scene entity does not exist anymore
assert!(app.world().get_entity(scene_entity).is_err());
// the root entity does not have any children anymore
assert!(app.world().entity(entity).get::<Children>().is_none());
}
}