use bevy_asset::Handle;
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
bundle::Bundle,
change_detection::ResMut,
entity::Entity,
prelude::{Changed, Component, Without},
system::{Commands, Query},
};
#[cfg(feature = "bevy_render")]
use bevy_render::prelude::{InheritedVisibility, ViewVisibility, Visibility};
use bevy_transform::components::{GlobalTransform, Transform};
use crate::{DynamicScene, InstanceId, Scene, SceneSpawner};
#[derive(Component, Deref, DerefMut)]
pub struct SceneInstance(InstanceId);
#[derive(Default, Bundle)]
pub struct SceneBundle {
pub scene: Handle<Scene>,
pub transform: Transform,
pub global_transform: GlobalTransform,
#[cfg(feature = "bevy_render")]
pub visibility: Visibility,
#[cfg(feature = "bevy_render")]
pub inherited_visibility: InheritedVisibility,
#[cfg(feature = "bevy_render")]
pub view_visibility: ViewVisibility,
}
#[derive(Default, Bundle)]
pub struct DynamicSceneBundle {
pub scene: Handle<DynamicScene>,
pub transform: Transform,
pub global_transform: GlobalTransform,
#[cfg(feature = "bevy_render")]
pub visibility: Visibility,
#[cfg(feature = "bevy_render")]
pub inherited_visibility: InheritedVisibility,
#[cfg(feature = "bevy_render")]
pub view_visibility: ViewVisibility,
}
pub fn scene_spawner(
mut commands: Commands,
mut scene_to_spawn: Query<
(Entity, &Handle<Scene>, Option<&mut SceneInstance>),
(Changed<Handle<Scene>>, Without<Handle<DynamicScene>>),
>,
mut dynamic_scene_to_spawn: Query<
(Entity, &Handle<DynamicScene>, Option<&mut SceneInstance>),
(Changed<Handle<DynamicScene>>, Without<Handle<Scene>>),
>,
mut scene_spawner: ResMut<SceneSpawner>,
) {
for (entity, scene, instance) in &mut scene_to_spawn {
let new_instance = scene_spawner.spawn_as_child(scene.clone(), entity);
if let Some(mut old_instance) = instance {
scene_spawner.despawn_instance(**old_instance);
*old_instance = SceneInstance(new_instance);
} else {
commands.entity(entity).insert(SceneInstance(new_instance));
}
}
for (entity, dynamic_scene, instance) in &mut dynamic_scene_to_spawn {
let new_instance = scene_spawner.spawn_dynamic_as_child(dynamic_scene.clone(), entity);
if let Some(mut old_instance) = instance {
scene_spawner.despawn_instance(**old_instance);
*old_instance = SceneInstance(new_instance);
} else {
commands.entity(entity).insert(SceneInstance(new_instance));
}
}
}