use bevy::{
prelude::*,
reflect::TypeRegistry,
scene::DynamicEntity,
};
use crate::{
error::Error,
prelude::*,
reflect::{
EntityMap,
ReflectMap,
SnapshotDeserializer,
SnapshotSerializer,
},
};
#[derive(Reflect, Clone, Debug)]
#[reflect(Clone)]
#[type_path = "bevy_save"]
pub struct Snapshot {
pub entities: EntityMap,
pub resources: ReflectMap,
}
impl Snapshot {
pub fn from_world(world: &World) -> Self {
Self::builder(world).extract_all().build()
}
pub fn builder(world: &World) -> BuilderRef {
BuilderRef::new(world)
}
}
impl Snapshot {
pub fn entities(&self) -> &[DynamicEntity] {
unsafe { &*(std::ptr::from_ref(self.entities.as_slice()) as *const _) }
}
pub fn resources(&self) -> &[Box<dyn PartialReflect>] {
unsafe { &*(std::ptr::from_ref(self.resources.as_slice()) as *const _) }
}
}
impl Snapshot {
pub fn apply(&self, world: &mut World) -> Result<(), Error> {
self.applier(world).apply()
}
pub fn applier<'w, 'i>(&'i self, world: &'w mut World) -> ApplierRef<'w, 'i> {
ApplierRef::new(self, world)
}
pub fn serializer<'a>(&'a self, registry: &'a TypeRegistry) -> SnapshotSerializer<'a> {
SnapshotSerializer::new(self, registry)
}
pub fn deserializer(registry: &TypeRegistry) -> SnapshotDeserializer<'_> {
SnapshotDeserializer::new(registry)
}
}