From f2d302c6d4a27a19eab42d502b956fce85a1ef14 Mon Sep 17 00:00:00 2001 From: SeanOMik Date: Fri, 23 Feb 2024 16:39:51 -0500 Subject: [PATCH] reflect: ReflectedComponent takes ownership over reflected component when inserting into entity --- lyra-reflect/src/component.rs | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/lyra-reflect/src/component.rs b/lyra-reflect/src/component.rs index ca160a5..a6fb54d 100644 --- a/lyra-reflect/src/component.rs +++ b/lyra-reflect/src/component.rs @@ -1,4 +1,4 @@ -use std::{any::TypeId, cell::{Ref, RefMut}}; +use std::{any::{Any, TypeId}, cell::{Ref, RefMut}}; use lyra_ecs::{Component, ComponentInfo, World, Entity, DynamicBundle}; @@ -13,21 +13,21 @@ pub struct ReflectedComponent { //from_world: for<'a> fn (world: &'a mut World) -> Box, /// Inserts component into entity in the world - fn_insert: for<'a> fn (world: &'a mut World, entity: Entity, component: &dyn Reflect), + fn_insert: for<'a> fn (world: &'a mut World, entity: Entity, component: Box), /// Inserts component into a bundle - fn_bundle_insert: for<'a> fn (dynamic_bundle: &'a mut DynamicBundle, component: &dyn Reflect), + fn_bundle_insert: for<'a> fn (dynamic_bundle: &'a mut DynamicBundle, component: Box), fn_reflect: for<'a> fn (world: &'a World, entity: Entity) -> Option>, fn_reflect_mut: for<'a> fn (world: &'a mut World, entity: Entity) -> Option>, } impl ReflectedComponent { /// Insert the reflected component into an entity. - pub fn insert(&self, world: &mut World, entity: Entity, component: &dyn Reflect) { + pub fn insert(&self, world: &mut World, entity: Entity, component: Box) { (self.fn_insert)(world, entity, component); } /// Insert this component into a DynamicBundle - pub fn bundle_insert(&self, dynamic_bundle: &mut DynamicBundle, component: &dyn Reflect) { + pub fn bundle_insert(&self, dynamic_bundle: &mut DynamicBundle, component: Box) { (self.fn_bundle_insert)(dynamic_bundle, component) } @@ -42,19 +42,23 @@ impl ReflectedComponent { } } -impl FromType for ReflectedComponent { +impl FromType for ReflectedComponent { fn from_type() -> Self { ReflectedComponent { type_id: TypeId::of::(), info: ComponentInfo::new::(), - fn_insert: |world: &mut World, entity: Entity, component: &dyn Reflect| { - let mut c = C::default(); - c.apply(component); + fn_insert: |world: &mut World, entity: Entity, component: Box| { + let c = component as Box; + let c = c.downcast::() + .expect("Provided a non-matching type to ReflectedComponent insert method!"); + let c = *c; world.insert(entity, (c,)); }, - fn_bundle_insert: |bundle: &mut DynamicBundle, component: &dyn Reflect| { - let mut c = C::default(); - c.apply(component); + fn_bundle_insert: |bundle: &mut DynamicBundle, component: Box| { + let c = component as Box; + let c = c.downcast::() + .expect("Provided a non-matching type to ReflectedComponent insert method!"); + let c = *c; bundle.push(c); }, fn_reflect: |world: &World, entity: Entity| {