mirror of
https://github.com/bevyengine/bevy.git
synced 2026-07-06 02:23:17 -04:00
535cf401cc
Part 2 of #23619 In **Bevy 0.19** we are landing a subset of Bevy's Next Generation Scene system (often known as BSN), which now lives in the `bevy_scene` / `bevy::scene` crate. However the old `bevy_scene` system still needs to stick around for a bit longer, as it provides some features that Bevy's Next Generation Scene system doesn't (yet!): 1. It is not _yet_ possible to write a World _to_ BSN, so the old system is still necessary for "round trip World serialization". 2. The GLTF scene loader has not yet been ported to BSN, so the old system is still necessary to spawn GLTF scenes in Bevy. For this reason, we have renamed the old `bevy_scene` crate to `bevy_world_serialization`. If you were referencing `bevy_scene::*` or `bevy::scene::*` types, rename those paths to `bevy_world_serialization::*` and `bevy::world_serialization::*` respectively. Additionally, to avoid confusion / conflicts with the new scene system, all "scene" terminology / types have been reframed as "world serialization": - `Scene` -> `WorldAsset` (as this was always just a World wrapper) - `SceneRoot` -> `WorldAssetRoot` - `DynamicScene` -> `DynamicWorld` - `DynamicScene::from_scene` -> `DynamicWorld::from_world_asset` - `DynamicSceneBuilder` -> `DynamicWorldBuilder` - `DynamicSceneRoot` -> `DynamicWorldRoot` - `SceneInstanceReady` -> `WorldInstanceReady` - `SceneLoader` -> `WorldAssetLoader` - `ScenePlugin` -> `WorldSerializationPlugin` - `SceneRootTemplate` -> `WorldAssetRootTemplate` - `SceneSpawner` -> `WorldInstanceSpawner` - `SceneFilter` -> `WorldFilter` - `SceneLoaderError` -> `WorldAssetLoaderError` - `SceneSpawnError` -> `WorldInstanceSpawnError` Note that I went with `bevy_world_serialization` over `bevy_ecs_serialization`, as that is what all of the internal features described themselves as. I think it is both more specific and does a better job of making itself decoupled from `bevy_ecs` proper.
254 lines
8.1 KiB
Rust
254 lines
8.1 KiB
Rust
//! A glTF scene viewer plugin. Provides controls for directional lighting, and switching between scene cameras.
|
|
//! To use in your own application:
|
|
//! - Copy the code for the `SceneViewerPlugin` and add the plugin to your App.
|
|
//! - Insert an initialized `SceneHandle` resource into your App's `AssetServer`.
|
|
|
|
use bevy::{
|
|
camera_controller::free_camera::FreeCamera,
|
|
gizmos::skinned_mesh_bounds::SkinnedMeshBoundsGizmoConfigGroup, gltf::Gltf,
|
|
input::common_conditions::input_just_pressed, prelude::*, world_serialization::InstanceId,
|
|
};
|
|
|
|
use std::{f32::consts::*, fmt};
|
|
|
|
#[derive(Resource)]
|
|
pub struct SceneHandle {
|
|
pub gltf_handle: Handle<Gltf>,
|
|
scene_index: usize,
|
|
instance_id: Option<InstanceId>,
|
|
pub is_loaded: bool,
|
|
pub has_light: bool,
|
|
}
|
|
|
|
impl SceneHandle {
|
|
pub fn new(gltf_handle: Handle<Gltf>, scene_index: usize) -> Self {
|
|
Self {
|
|
gltf_handle,
|
|
scene_index,
|
|
instance_id: None,
|
|
is_loaded: false,
|
|
has_light: false,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(not(feature = "gltf_animation"))]
|
|
const INSTRUCTIONS: &str = r#"
|
|
Scene Controls:
|
|
L - animate light direction
|
|
U - toggle shadows
|
|
F - toggle camera frusta
|
|
C - cycle through the camera controller and any cameras loaded from the scene
|
|
|
|
compile with "--features animation" for animation controls.
|
|
"#;
|
|
|
|
#[cfg(feature = "gltf_animation")]
|
|
const INSTRUCTIONS: &str = "
|
|
Scene Controls:
|
|
L - animate light direction
|
|
U - toggle shadows
|
|
B - toggle bounding boxes
|
|
F - toggle camera frusta
|
|
J - toggle skinned mesh joint bounding boxes
|
|
C - cycle through the camera controller and any cameras loaded from the scene
|
|
|
|
Space - Play/Pause animation
|
|
Enter - Cycle through animations
|
|
";
|
|
|
|
impl fmt::Display for SceneHandle {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
write!(f, "{INSTRUCTIONS}")
|
|
}
|
|
}
|
|
|
|
pub struct SceneViewerPlugin;
|
|
|
|
impl Plugin for SceneViewerPlugin {
|
|
fn build(&self, app: &mut App) {
|
|
app.init_resource::<CameraTracker>()
|
|
.add_systems(PreUpdate, scene_load_check)
|
|
.add_systems(
|
|
Update,
|
|
(
|
|
update_lights,
|
|
camera_tracker,
|
|
(
|
|
toggle_bounding_boxes.run_if(input_just_pressed(KeyCode::KeyB)),
|
|
toggle_camera_frusta.run_if(input_just_pressed(KeyCode::KeyF)),
|
|
toggle_skinned_mesh_bounds.run_if(input_just_pressed(KeyCode::KeyJ)),
|
|
)
|
|
.chain(),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
fn toggle_bounding_boxes(mut config: ResMut<GizmoConfigStore>) {
|
|
config.config_mut::<AabbGizmoConfigGroup>().1.draw_all ^= true;
|
|
}
|
|
|
|
fn toggle_camera_frusta(mut config: ResMut<GizmoConfigStore>) {
|
|
config.config_mut::<FrustumGizmoConfigGroup>().1.draw_all ^= true;
|
|
}
|
|
|
|
fn toggle_skinned_mesh_bounds(mut config: ResMut<GizmoConfigStore>) {
|
|
config
|
|
.config_mut::<SkinnedMeshBoundsGizmoConfigGroup>()
|
|
.1
|
|
.draw_all ^= true;
|
|
}
|
|
|
|
fn scene_load_check(
|
|
asset_server: Res<AssetServer>,
|
|
mut scenes: ResMut<Assets<WorldAsset>>,
|
|
gltf_assets: Res<Assets<Gltf>>,
|
|
mut scene_handle: ResMut<SceneHandle>,
|
|
mut scene_spawner: ResMut<WorldInstanceSpawner>,
|
|
) {
|
|
match scene_handle.instance_id {
|
|
None => {
|
|
if asset_server
|
|
.load_state(&scene_handle.gltf_handle)
|
|
.is_loaded()
|
|
{
|
|
let gltf = gltf_assets.get(&scene_handle.gltf_handle).unwrap();
|
|
if gltf.scenes.len() > 1 {
|
|
info!(
|
|
"Displaying scene {} out of {}",
|
|
scene_handle.scene_index,
|
|
gltf.scenes.len()
|
|
);
|
|
info!("You can select the scene by adding '#Scene' followed by a number to the end of the file path (e.g '#Scene1' to load the second scene).");
|
|
}
|
|
|
|
let gltf_scene_handle =
|
|
gltf.scenes
|
|
.get(scene_handle.scene_index)
|
|
.unwrap_or_else(|| {
|
|
panic!(
|
|
"glTF file doesn't contain scene {}!",
|
|
scene_handle.scene_index
|
|
)
|
|
});
|
|
let mut scene = scenes.get_mut(gltf_scene_handle).unwrap();
|
|
|
|
let mut query = scene
|
|
.world
|
|
.query::<(Option<&DirectionalLight>, Option<&PointLight>)>();
|
|
scene_handle.has_light =
|
|
query
|
|
.iter(&scene.world)
|
|
.any(|(maybe_directional_light, maybe_point_light)| {
|
|
maybe_directional_light.is_some() || maybe_point_light.is_some()
|
|
});
|
|
|
|
scene_handle.instance_id = Some(scene_spawner.spawn(gltf_scene_handle.clone()));
|
|
|
|
info!("Spawning scene...");
|
|
}
|
|
}
|
|
Some(instance_id) if !scene_handle.is_loaded => {
|
|
if scene_spawner.instance_is_ready(instance_id) {
|
|
info!("...done!");
|
|
scene_handle.is_loaded = true;
|
|
}
|
|
}
|
|
Some(_) => {}
|
|
}
|
|
}
|
|
|
|
fn update_lights(
|
|
key_input: Res<ButtonInput<KeyCode>>,
|
|
time: Res<Time>,
|
|
mut query: Query<(&mut Transform, &mut DirectionalLight)>,
|
|
mut animate_directional_light: Local<bool>,
|
|
) {
|
|
for (_, mut light) in &mut query {
|
|
if key_input.just_pressed(KeyCode::KeyU) {
|
|
light.shadow_maps_enabled = !light.shadow_maps_enabled;
|
|
}
|
|
}
|
|
|
|
if key_input.just_pressed(KeyCode::KeyL) {
|
|
*animate_directional_light = !*animate_directional_light;
|
|
}
|
|
if *animate_directional_light {
|
|
for (mut transform, _) in &mut query {
|
|
transform.rotation = Quat::from_euler(
|
|
EulerRot::ZYX,
|
|
0.0,
|
|
time.elapsed_secs() * PI / 15.0,
|
|
-FRAC_PI_4,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Resource, Default)]
|
|
struct CameraTracker {
|
|
active_index: Option<usize>,
|
|
cameras: Vec<Entity>,
|
|
}
|
|
|
|
impl CameraTracker {
|
|
fn track_camera(&mut self, entity: Entity) -> bool {
|
|
self.cameras.push(entity);
|
|
if self.active_index.is_none() {
|
|
self.active_index = Some(self.cameras.len() - 1);
|
|
true
|
|
} else {
|
|
false
|
|
}
|
|
}
|
|
|
|
fn active_camera(&self) -> Option<Entity> {
|
|
self.active_index.map(|i| self.cameras[i])
|
|
}
|
|
|
|
fn set_next_active(&mut self) -> Option<Entity> {
|
|
let active_index = self.active_index?;
|
|
let new_i = (active_index + 1) % self.cameras.len();
|
|
self.active_index = Some(new_i);
|
|
Some(self.cameras[new_i])
|
|
}
|
|
}
|
|
|
|
fn camera_tracker(
|
|
mut camera_tracker: ResMut<CameraTracker>,
|
|
keyboard_input: Res<ButtonInput<KeyCode>>,
|
|
mut queries: ParamSet<(
|
|
Query<(Entity, &mut Camera), (Added<Camera>, Without<FreeCamera>)>,
|
|
Query<(Entity, &mut Camera), (Added<Camera>, With<FreeCamera>)>,
|
|
Query<&mut Camera>,
|
|
)>,
|
|
) {
|
|
// track added scene camera entities first, to ensure they are preferred for the
|
|
// default active camera
|
|
for (entity, mut camera) in queries.p0().iter_mut() {
|
|
camera.is_active = camera_tracker.track_camera(entity);
|
|
}
|
|
|
|
// iterate added custom camera entities second
|
|
for (entity, mut camera) in queries.p1().iter_mut() {
|
|
camera.is_active = camera_tracker.track_camera(entity);
|
|
}
|
|
|
|
if keyboard_input.just_pressed(KeyCode::KeyC) {
|
|
// disable currently active camera
|
|
if let Some(e) = camera_tracker.active_camera()
|
|
&& let Ok(mut camera) = queries.p2().get_mut(e)
|
|
{
|
|
camera.is_active = false;
|
|
}
|
|
|
|
// enable next active camera
|
|
if let Some(e) = camera_tracker.set_next_active()
|
|
&& let Ok(mut camera) = queries.p2().get_mut(e)
|
|
{
|
|
camera.is_active = true;
|
|
}
|
|
}
|
|
}
|