
Fixes #17535 Bevy's approach to handling "entity mapping" during spawning and cloning needs some work. The addition of [Relations](https://github.com/bevyengine/bevy/pull/17398) both [introduced a new "duplicate entities" bug when spawning scenes in the scene system](#17535) and made the weaknesses of the current mapping system exceedingly clear: 1. Entity mapping requires _a ton_ of boilerplate (implement or derive VisitEntities and VisitEntitesMut, then register / reflect MapEntities). Knowing the incantation is challenging and if you forget to do it in part or in whole, spawning subtly breaks. 2. Entity mapping a spawned component in scenes incurs unnecessary overhead: look up ReflectMapEntities, create a _brand new temporary instance_ of the component using FromReflect, map the entities in that instance, and then apply that on top of the actual component using reflection. We can do much better. Additionally, while our new [Entity cloning system](https://github.com/bevyengine/bevy/pull/16132) is already pretty great, it has some areas we can make better: * It doesn't expose semantic info about the clone (ex: ignore or "clone empty"), meaning we can't key off of that in places where it would be useful, such as scene spawning. Rather than duplicating this info across contexts, I think it makes more sense to add that info to the clone system, especially given that we'd like to use cloning code in some of our spawning scenarios. * EntityCloner is currently built in a way that prioritizes a single entity clone * EntityCloner's recursive cloning is built to be done "inside out" in a parallel context (queue commands that each have a clone of EntityCloner). By making EntityCloner the orchestrator of the clone we can remove internal arcs, improve the clarity of the code, make EntityCloner mutable again, and simplify the builder code. * EntityCloner does not currently take into account entity mapping. This is necessary to do true "bullet proof" cloning, would allow us to unify the per-component scene spawning and cloning UX, and ultimately would allow us to use EntityCloner in place of raw reflection for scenes like `Scene(World)` (which would give us a nice performance boost: fewer archetype moves, less reflection overhead). ## Solution ### Improved Entity Mapping First, components now have first-class "entity visiting and mapping" behavior: ```rust #[derive(Component, Reflect)] #[reflect(Component)] struct Inventory { size: usize, #[entities] items: Vec<Entity>, } ``` Any field with the `#[entities]` annotation will be viewable and mappable when cloning and spawning scenes. Compare that to what was required before! ```rust #[derive(Component, Reflect, VisitEntities, VisitEntitiesMut)] #[reflect(Component, MapEntities)] struct Inventory { #[visit_entities(ignore)] size: usize, items: Vec<Entity>, } ``` Additionally, for relationships `#[entities]` is implied, meaning this "just works" in scenes and cloning: ```rust #[derive(Component, Reflect)] #[relationship(relationship_target = Children)] #[reflect(Component)] struct ChildOf(pub Entity); ``` Note that Component _does not_ implement `VisitEntities` directly. Instead, it has `Component::visit_entities` and `Component::visit_entities_mut` methods. This is for a few reasons: 1. We cannot implement `VisitEntities for C: Component` because that would conflict with our impl of VisitEntities for anything that implements `IntoIterator<Item=Entity>`. Preserving that impl is more important from a UX perspective. 2. We should not implement `Component: VisitEntities` VisitEntities in the Component derive, as that would increase the burden of manual Component trait implementors. 3. Making VisitEntitiesMut directly callable for components would make it easy to invalidate invariants defined by a component author. By putting it in the `Component` impl, we can make it harder to call naturally / unavailable to autocomplete using `fn visit_entities_mut(this: &mut Self, ...)`. `ReflectComponent::apply_or_insert` is now `ReflectComponent::apply_or_insert_mapped`. By moving mapping inside this impl, we remove the need to go through the reflection system to do entity mapping, meaning we no longer need to create a clone of the target component, map the entities in that component, and patch those values on top. This will make spawning mapped entities _much_ faster (The default `Component::visit_entities_mut` impl is an inlined empty function, so it will incur no overhead for unmapped entities). ### The Bug Fix To solve #17535, spawning code now skips entities with the new `ComponentCloneBehavior::Ignore` and `ComponentCloneBehavior::RelationshipTarget` variants (note RelationshipTarget is a temporary "workaround" variant that allows scenes to skip these components. This is a temporary workaround that can be removed as these cases should _really_ be using EntityCloner logic, which should be done in a followup PR. When that is done, `ComponentCloneBehavior::RelationshipTarget` can be merged into the normal `ComponentCloneBehavior::Custom`). ### Improved Cloning * `Option<ComponentCloneHandler>` has been replaced by `ComponentCloneBehavior`, which encodes additional intent and context (ex: `Default`, `Ignore`, `Custom`, `RelationshipTarget` (this last one is temporary)). * Global per-world entity cloning configuration has been removed. This felt overly complicated, increased our API surface, and felt too generic. Each clone context can have different requirements (ex: what a user wants in a specific system, what a scene spawner wants, etc). I'd prefer to see how far context-specific EntityCloners get us first. * EntityCloner's internals have been reworked to remove Arcs and make it mutable. * EntityCloner is now directly stored on EntityClonerBuilder, simplifying the code somewhat * EntityCloner's "bundle scratch" pattern has been moved into the new BundleScratch type, improving its usability and making it usable in other contexts (such as future cross-world cloning code). Currently this is still private, but with some higher level safe APIs it could be used externally for making dynamic bundles * EntityCloner's recursive cloning behavior has been "externalized". It is now responsible for orchestrating recursive clones, meaning it no longer needs to be sharable/clone-able across threads / read-only. * EntityCloner now does entity mapping during clones, like scenes do. This gives behavior parity and also makes it more generically useful. * `RelatonshipTarget::RECURSIVE_SPAWN` is now `RelationshipTarget::LINKED_SPAWN`, and this field is used when cloning relationship targets to determine if cloning should happen recursively. The new `LINKED_SPAWN` term was picked to make it more generically applicable across spawning and cloning scenarios. ## Next Steps * I think we should adapt EntityCloner to support cross world cloning. I think this PR helps set the stage for that by making the internals slightly more generalized. We could have a CrossWorldEntityCloner that reuses a lot of this infrastructure. * Once we support cross world cloning, we should use EntityCloner to spawn `Scene(World)` scenes. This would yield significant performance benefits (no archetype moves, less reflection overhead). --------- Co-authored-by: eugineerd <70062110+eugineerd@users.noreply.github.com> Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
169 lines
6.5 KiB
Rust
169 lines
6.5 KiB
Rust
use core::any::TypeId;
|
|
|
|
use crate::{DynamicScene, SceneSpawnError};
|
|
use bevy_asset::Asset;
|
|
use bevy_ecs::{
|
|
component::ComponentCloneBehavior,
|
|
entity::{hash_map::EntityHashMap, Entity, SceneEntityMapper},
|
|
entity_disabling::DefaultQueryFilters,
|
|
reflect::{AppTypeRegistry, ReflectComponent, ReflectResource},
|
|
world::World,
|
|
};
|
|
use bevy_reflect::{PartialReflect, TypePath};
|
|
|
|
/// A composition of [`World`] objects.
|
|
///
|
|
/// To spawn a scene, you can use either:
|
|
/// * [`SceneSpawner::spawn`](crate::SceneSpawner::spawn)
|
|
/// * adding the [`SceneRoot`](crate::components::SceneRoot) component to an entity.
|
|
#[derive(Asset, TypePath, Debug)]
|
|
pub struct Scene {
|
|
/// The world of the scene, containing its entities and resources.
|
|
pub world: World,
|
|
}
|
|
|
|
impl Scene {
|
|
/// Creates a new scene with the given world.
|
|
pub fn new(world: World) -> Self {
|
|
Self { world }
|
|
}
|
|
|
|
/// Create a new scene from a given dynamic scene.
|
|
pub fn from_dynamic_scene(
|
|
dynamic_scene: &DynamicScene,
|
|
type_registry: &AppTypeRegistry,
|
|
) -> Result<Scene, SceneSpawnError> {
|
|
let mut world = World::new();
|
|
let mut entity_map = EntityHashMap::default();
|
|
dynamic_scene.write_to_world_with(&mut world, &mut entity_map, type_registry)?;
|
|
|
|
Ok(Self { world })
|
|
}
|
|
|
|
/// Clone the scene.
|
|
///
|
|
/// This method will return a [`SceneSpawnError`] if a type either is not registered in the
|
|
/// provided [`AppTypeRegistry`] or doesn't reflect the [`Component`](bevy_ecs::component::Component) trait.
|
|
pub fn clone_with(&self, type_registry: &AppTypeRegistry) -> Result<Scene, SceneSpawnError> {
|
|
let mut new_world = World::new();
|
|
let mut entity_map = EntityHashMap::default();
|
|
self.write_to_world_with(&mut new_world, &mut entity_map, type_registry)?;
|
|
Ok(Self { world: new_world })
|
|
}
|
|
|
|
/// Write the entities and their corresponding components to the given world.
|
|
///
|
|
/// This method will return a [`SceneSpawnError`] if a type either is not registered in the
|
|
/// provided [`AppTypeRegistry`] or doesn't reflect the [`Component`](bevy_ecs::component::Component) trait.
|
|
pub fn write_to_world_with(
|
|
&self,
|
|
world: &mut World,
|
|
entity_map: &mut EntityHashMap<Entity>,
|
|
type_registry: &AppTypeRegistry,
|
|
) -> Result<(), SceneSpawnError> {
|
|
let type_registry = type_registry.read();
|
|
|
|
let self_dqf_id = self
|
|
.world
|
|
.components()
|
|
.get_resource_id(TypeId::of::<DefaultQueryFilters>());
|
|
|
|
// Resources archetype
|
|
for (component_id, resource_data) in self.world.storages().resources.iter() {
|
|
if Some(component_id) == self_dqf_id {
|
|
continue;
|
|
}
|
|
if !resource_data.is_present() {
|
|
continue;
|
|
}
|
|
|
|
let component_info = self
|
|
.world
|
|
.components()
|
|
.get_info(component_id)
|
|
.expect("component_ids in archetypes should have ComponentInfo");
|
|
|
|
let type_id = component_info
|
|
.type_id()
|
|
.expect("reflected resources must have a type_id");
|
|
|
|
let registration =
|
|
type_registry
|
|
.get(type_id)
|
|
.ok_or_else(|| SceneSpawnError::UnregisteredType {
|
|
std_type_name: component_info.name().to_string(),
|
|
})?;
|
|
let reflect_resource = registration.data::<ReflectResource>().ok_or_else(|| {
|
|
SceneSpawnError::UnregisteredResource {
|
|
type_path: registration.type_info().type_path().to_string(),
|
|
}
|
|
})?;
|
|
reflect_resource.copy(&self.world, world, &type_registry);
|
|
}
|
|
|
|
// Ensure that all scene entities have been allocated in the destination
|
|
// world before handling components that may contain references that need mapping.
|
|
for archetype in self.world.archetypes().iter() {
|
|
for scene_entity in archetype.entities() {
|
|
entity_map
|
|
.entry(scene_entity.id())
|
|
.or_insert_with(|| world.spawn_empty().id());
|
|
}
|
|
}
|
|
|
|
for archetype in self.world.archetypes().iter() {
|
|
for scene_entity in archetype.entities() {
|
|
let entity = *entity_map
|
|
.get(&scene_entity.id())
|
|
.expect("should have previously spawned an entity");
|
|
|
|
for component_id in archetype.components() {
|
|
let component_info = self
|
|
.world
|
|
.components()
|
|
.get_info(component_id)
|
|
.expect("component_ids in archetypes should have ComponentInfo");
|
|
|
|
match component_info.clone_behavior() {
|
|
ComponentCloneBehavior::Ignore
|
|
| ComponentCloneBehavior::RelationshipTarget(_) => continue,
|
|
_ => {}
|
|
}
|
|
|
|
let registration = type_registry
|
|
.get(component_info.type_id().unwrap())
|
|
.ok_or_else(|| SceneSpawnError::UnregisteredType {
|
|
std_type_name: component_info.name().to_string(),
|
|
})?;
|
|
let reflect_component =
|
|
registration.data::<ReflectComponent>().ok_or_else(|| {
|
|
SceneSpawnError::UnregisteredComponent {
|
|
type_path: registration.type_info().type_path().to_string(),
|
|
}
|
|
})?;
|
|
|
|
let Some(component) = reflect_component
|
|
.reflect(self.world.entity(scene_entity.id()))
|
|
.map(PartialReflect::clone_value)
|
|
else {
|
|
continue;
|
|
};
|
|
|
|
// If this component references entities in the scene,
|
|
// update them to the entities in the world.
|
|
SceneEntityMapper::world_scope(entity_map, world, |world, mapper| {
|
|
reflect_component.apply_or_insert_mapped(
|
|
&mut world.entity_mut(entity),
|
|
component.as_partial_reflect(),
|
|
&type_registry,
|
|
mapper,
|
|
);
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
}
|