
# Objective Co-Authored-By: davier [bricedavier@gmail.com](mailto:bricedavier@gmail.com) Fixes #3576. Adds a `resources` field in scene serialization data to allow de/serializing resources that have reflection enabled. ## Solution Most of this code is taken from a previous closed PR: https://github.com/bevyengine/bevy/pull/3580. Most of the credit goes to @Davier , what I did was mostly getting it to work on the latest main branch of Bevy, along with adding a few asserts in the currently existing tests to be sure everything is working properly. This PR changes the scene format to include resources in this way: ``` ( resources: { // List of resources here, keyed by resource type name. }, entities: [ // Previous scene format here ], ) ``` An example taken from the tests: ``` ( resources: { "bevy_scene::serde::tests::MyResource": ( foo: 123, ), }, entities: { // Previous scene format here }, ) ``` For this, a `resources` fields has been added on the `DynamicScene` and the `DynamicSceneBuilder` structs. The latter now also has a method named `extract_resources` to properly extract the existing resources registered in the local type registry, in a similar way to `extract_entities`. --- ## Changelog Added: Reflect resources registered in the type registry used by dynamic scenes will now be properly de/serialized in scene data. ## Migration Guide Since the scene format has been changed, the user may not be able to use scenes saved prior to this PR due to the `resources` scene field being missing. ~~To preserve backwards compatibility, I will try to make the `resources` fully optional so that old scenes can be loaded without issue.~~ ## TODOs - [x] I may have to update a few doc blocks still referring to dynamic scenes as mere container of entities, since they now include resources as well. - [x] ~~I want to make the `resources` key optional, as specified in the Migration Guide, so that old scenes will be compatible with this change.~~ Since this would only be trivial for ron format, I think it might be better to consider it in a separate PR/discussion to figure out if it could be done for binary serialization too. - [x] I suppose it might be a good idea to add a resources in the scene example so that users will quickly notice they can serialize resources just like entities. --------- Co-authored-by: Carter Anderson <mcanders1@gmail.com>
163 lines
6.6 KiB
Rust
163 lines
6.6 KiB
Rust
use crate::{DynamicSceneBuilder, Scene, SceneSpawnError};
|
|
use anyhow::Result;
|
|
use bevy_app::AppTypeRegistry;
|
|
use bevy_ecs::{
|
|
entity::EntityMap,
|
|
reflect::{ReflectComponent, ReflectMapEntities},
|
|
world::World,
|
|
};
|
|
use bevy_reflect::{Reflect, TypeRegistryArc, TypeUuid};
|
|
|
|
#[cfg(feature = "serialize")]
|
|
use crate::serde::SceneSerializer;
|
|
use bevy_ecs::reflect::ReflectResource;
|
|
#[cfg(feature = "serialize")]
|
|
use serde::Serialize;
|
|
|
|
/// A collection of serializable resources and dynamic entities.
|
|
///
|
|
/// Each dynamic entity in the collection contains its own run-time defined set of components.
|
|
/// To spawn a dynamic scene, you can use either:
|
|
/// * [`SceneSpawner::spawn_dynamic`](crate::SceneSpawner::spawn_dynamic)
|
|
/// * adding the [`DynamicSceneBundle`](crate::DynamicSceneBundle) to an entity
|
|
/// * adding the [`Handle<DynamicScene>`](bevy_asset::Handle) to an entity (the scene will only be
|
|
/// visible if the entity already has [`Transform`](bevy_transform::components::Transform) and
|
|
/// [`GlobalTransform`](bevy_transform::components::GlobalTransform) components)
|
|
#[derive(Default, TypeUuid)]
|
|
#[uuid = "749479b1-fb8c-4ff8-a775-623aa76014f5"]
|
|
pub struct DynamicScene {
|
|
pub resources: Vec<Box<dyn Reflect>>,
|
|
pub entities: Vec<DynamicEntity>,
|
|
}
|
|
|
|
/// A reflection-powered serializable representation of an entity and its components.
|
|
pub struct DynamicEntity {
|
|
/// The transiently unique identifier of a corresponding `Entity`.
|
|
pub entity: u32,
|
|
/// A vector of boxed components that belong to the given entity and
|
|
/// implement the `Reflect` trait.
|
|
pub components: Vec<Box<dyn Reflect>>,
|
|
}
|
|
|
|
impl DynamicScene {
|
|
/// Create a new dynamic scene from a given scene.
|
|
pub fn from_scene(scene: &Scene, type_registry: &AppTypeRegistry) -> Self {
|
|
Self::from_world(&scene.world, type_registry)
|
|
}
|
|
|
|
/// Create a new dynamic scene from a given world.
|
|
pub fn from_world(world: &World, type_registry: &AppTypeRegistry) -> Self {
|
|
let mut builder =
|
|
DynamicSceneBuilder::from_world_with_type_registry(world, type_registry.clone());
|
|
|
|
builder.extract_entities(world.iter_entities().map(|entity| entity.id()));
|
|
builder.extract_resources();
|
|
|
|
builder.build()
|
|
}
|
|
|
|
/// Write the resources, 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 provided [`AppTypeRegistry`] resource, or doesn't reflect the
|
|
/// [`Component`](bevy_ecs::component::Component) or [`Resource`](bevy_ecs::prelude::Resource) trait.
|
|
pub fn write_to_world_with(
|
|
&self,
|
|
world: &mut World,
|
|
entity_map: &mut EntityMap,
|
|
type_registry: &AppTypeRegistry,
|
|
) -> Result<(), SceneSpawnError> {
|
|
let type_registry = type_registry.read();
|
|
|
|
for resource in &self.resources {
|
|
let registration = type_registry
|
|
.get_with_name(resource.type_name())
|
|
.ok_or_else(|| SceneSpawnError::UnregisteredType {
|
|
type_name: resource.type_name().to_string(),
|
|
})?;
|
|
let reflect_resource = registration.data::<ReflectResource>().ok_or_else(|| {
|
|
SceneSpawnError::UnregisteredResource {
|
|
type_name: resource.type_name().to_string(),
|
|
}
|
|
})?;
|
|
|
|
// If the world already contains an instance of the given resource
|
|
// just apply the (possibly) new value, otherwise insert the resource
|
|
reflect_resource.apply_or_insert(world, &**resource);
|
|
}
|
|
|
|
for scene_entity in &self.entities {
|
|
// Fetch the entity with the given entity id from the `entity_map`
|
|
// or spawn a new entity with a transiently unique id if there is
|
|
// no corresponding entry.
|
|
let entity = *entity_map
|
|
.entry(bevy_ecs::entity::Entity::from_raw(scene_entity.entity))
|
|
.or_insert_with(|| world.spawn_empty().id());
|
|
let entity_mut = &mut world.entity_mut(entity);
|
|
|
|
// Apply/ add each component to the given entity.
|
|
for component in &scene_entity.components {
|
|
let registration = type_registry
|
|
.get_with_name(component.type_name())
|
|
.ok_or_else(|| SceneSpawnError::UnregisteredType {
|
|
type_name: component.type_name().to_string(),
|
|
})?;
|
|
let reflect_component =
|
|
registration.data::<ReflectComponent>().ok_or_else(|| {
|
|
SceneSpawnError::UnregisteredComponent {
|
|
type_name: component.type_name().to_string(),
|
|
}
|
|
})?;
|
|
|
|
// If the entity already has the given component attached,
|
|
// just apply the (possibly) new value, otherwise add the
|
|
// component to the entity.
|
|
reflect_component.apply_or_insert(entity_mut, &**component);
|
|
}
|
|
}
|
|
|
|
for registration in type_registry.iter() {
|
|
if let Some(map_entities_reflect) = registration.data::<ReflectMapEntities>() {
|
|
map_entities_reflect
|
|
.map_entities(world, entity_map)
|
|
.unwrap();
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Write the resources, 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, ®istry)
|
|
}
|
|
|
|
// TODO: move to AssetSaver when it is implemented
|
|
/// Serialize this dynamic scene into rust object notation (ron).
|
|
#[cfg(feature = "serialize")]
|
|
pub fn serialize_ron(&self, registry: &TypeRegistryArc) -> Result<String, ron::Error> {
|
|
serialize_ron(SceneSerializer::new(self, registry))
|
|
}
|
|
}
|
|
|
|
/// Serialize a given Rust data structure into rust object notation (ron).
|
|
#[cfg(feature = "serialize")]
|
|
pub fn serialize_ron<S>(serialize: S) -> Result<String, ron::Error>
|
|
where
|
|
S: Serialize,
|
|
{
|
|
let pretty_config = ron::ser::PrettyConfig::default()
|
|
.indentor(" ".to_string())
|
|
.new_line("\n".to_string());
|
|
ron::ser::to_string_pretty(&serialize, pretty_config)
|
|
}
|