diff --git a/src/nodes/drawable/model.rs b/src/nodes/drawable/model.rs index 6567b18..7028abc 100644 --- a/src/nodes/drawable/model.rs +++ b/src/nodes/drawable/model.rs @@ -199,7 +199,7 @@ fn gen_model_parts( client.scenegraph.add_node(Node::generate(&client, false)); let spatial = Spatial::add_to( &node, - Some(parent_spatial), + Some(parent_spatial.clone()), transform.compute_matrix(), false, ); @@ -241,6 +241,7 @@ fn gen_model_parts( .and_then(|v| v.bounds.get().copied()) .unwrap_or_default() }); + spatial.set_spatial_parent(&parent_spatial); spatial.set_local_transform(transform.compute_matrix()); spatial.set_entity(entity); diff --git a/src/nodes/spatial/mod.rs b/src/nodes/spatial/mod.rs index 4e0e7b8..6b9b435 100644 --- a/src/nodes/spatial/mod.rs +++ b/src/nodes/spatial/mod.rs @@ -30,6 +30,7 @@ impl Plugin for SpatialNodePlugin { PostUpdate, ( spawn_spatial_nodes, + despawn_unneeded_spatial_nodes, update_spatial_node_parenting, update_spatial_nodes, ) @@ -48,7 +49,7 @@ fn spawn_spatial_nodes(mut cmds: Commands) { let entity = cmds .spawn((SpatialNode(Arc::downgrade(&spatial)), Name::new("Spatial"))) .id(); - _ = spatial.set_entity(entity); + spatial.set_entity(entity); } } @@ -60,13 +61,18 @@ fn update_spatial_node_parenting( let Some(spatial) = spatial.0.upgrade() else { continue; }; - let parent_entity = spatial + + let Some(parent_entity) = spatial .get_parent() - .and_then(|v| v.entity.lock().as_ref().map(|v| v.0)); + .map(|v| v.entity.lock().as_ref().map(|v| v.0)) + else { + continue; + }; // no changes needed, early exit if parent.map(|v| v.0) == parent_entity { continue; } + info!("changing bevy parent: {:?} to {:?}", parent.map(|v| v.0), parent_entity); match parent_entity { Some(e) => cmds.entity(entity).insert(ChildOf(e)), None => cmds.entity(entity).remove::(), @@ -74,6 +80,15 @@ fn update_spatial_node_parenting( } } +fn despawn_unneeded_spatial_nodes(query: Query<(Entity, &SpatialNode)>, cmds: ParallelCommands) { + query.par_iter().for_each(|(entity, spatial_node)| { + if spatial_node.0.upgrade().is_none() { + info!("despawn {entity}"); + cmds.command_scope(|mut cmds| cmds.entity(entity).despawn()); + } + }); +} + fn update_spatial_nodes( mut query: Query<( &mut BevyTransform, @@ -321,6 +336,7 @@ impl Spatial { self.parent.lock().clone() } fn set_parent(self: &Arc, new_parent: &Arc) { + info!("setting parent for {:?}", self.node().map(|v| v.id)); if let Some(parent) = self.get_parent() { parent.children.remove(self); }