Create a scene from a dynamic scene (#6229)

# Objective

- Add a method to create a `Scene` from a `DynamicScene`
This commit is contained in:
François 2022-10-17 16:25:12 +00:00
parent 88700f3595
commit b09b2c1056
2 changed files with 32 additions and 5 deletions

View file

@ -50,14 +50,15 @@ impl DynamicScene {
/// Write the dynamic entities and their corresponding components to the given world.
///
/// This method will return a [`SceneSpawnError`] if a type either is not registered
/// or doesn't reflect the [`Component`](bevy_ecs::component::Component) trait.
pub fn write_to_world(
/// in the provided [`AppTypeRegistry`] resource, or doesn't reflect the
/// [`Component`](bevy_ecs::component::Component) trait.
pub fn write_to_world_with(
&self,
world: &mut World,
entity_map: &mut EntityMap,
type_registry: &AppTypeRegistry,
) -> Result<(), SceneSpawnError> {
let registry = world.resource::<AppTypeRegistry>().clone();
let type_registry = registry.read();
let type_registry = type_registry.read();
for scene_entity in &self.entities {
// Fetch the entity with the given entity id from the `entity_map`
@ -99,6 +100,20 @@ impl DynamicScene {
Ok(())
}
/// Write the dynamic entities and their corresponding components to the given world.
///
/// This method will return a [`SceneSpawnError`] if a type either is not registered
/// in the world's [`AppTypeRegistry`] resource, or doesn't reflect the
/// [`Component`](bevy_ecs::component::Component) trait.
pub fn write_to_world(
&self,
world: &mut World,
entity_map: &mut EntityMap,
) -> Result<(), SceneSpawnError> {
let registry = world.resource::<AppTypeRegistry>().clone();
self.write_to_world_with(world, entity_map, &registry)
}
// TODO: move to AssetSaver when it is implemented
/// Serialize this dynamic scene into rust object notation (ron).
pub fn serialize_ron(&self, registry: &TypeRegistryArc) -> Result<String, ron::Error> {

View file

@ -6,7 +6,7 @@ use bevy_ecs::{
};
use bevy_reflect::TypeUuid;
use crate::{InstanceInfo, SceneSpawnError};
use crate::{DynamicScene, InstanceInfo, SceneSpawnError};
/// To spawn a scene, you can use either:
/// * [`SceneSpawner::spawn`](crate::SceneSpawner::spawn)
@ -25,6 +25,18 @@ impl Scene {
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 = EntityMap::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