//! This example demonstrates how to load scene data from files and then dynamically1//! apply that data to entities in your Bevy `World`. This includes spawning new2//! entities and applying updates to existing ones. Scenes in Bevy encapsulate3//! serialized and deserialized `Components` or `Resources` so that you can easily4//! store, load, and manipulate data outside of a purely code-driven context.5//!6//! This example also shows how to do the following:7//! * Register your custom types for reflection, which allows them to be serialized,8//! deserialized, and manipulated dynamically.9//! * Skip serialization of fields you don't want stored in your scene files (like10//! runtime values that should always be computed dynamically).11//! * Save a new scene to disk to show how it can be updated compared to the original12//! scene file (and how that updated scene file might then be used later on).13//!14//! The example proceeds by creating components and resources, registering their types,15//! loading a scene from a file, logging when changes are detected, and finally saving16//! a new scene file to disk. This is useful for anyone wanting to see how to integrate17//! file-based scene workflows into their Bevy projects.18//!19//! # Note on working with files20//!21//! The saving behavior uses the standard filesystem APIs, which are blocking, so it22//! utilizes a thread pool (`IoTaskPool`) to avoid stalling the main thread. This23//! won't work on WASM because WASM typically doesn't have direct filesystem access.24//!2526use bevy::{asset::LoadState, prelude::*, tasks::IoTaskPool};2728use core::time::Duration;29use std::{fs::File, io::Write};3031/// The entry point of our Bevy app.32///33/// Sets up default plugins, registers all necessary component/resource types34/// for serialization/reflection, and runs the various systems in the correct schedule.35fn main() {36App::new()37.add_plugins(DefaultPlugins)38.add_systems(39Startup,40(save_scene_system, load_scene_system, infotext_system),41)42.add_systems(Update, (log_system, panic_on_fail))43.run();44}4546/// # Components, Resources, and Reflection47///48/// Below are some simple examples of how to define your own Bevy `Component` types49/// and `Resource` types so that they can be properly reflected, serialized, and50/// deserialized. The `#[derive(Reflect)]` macro enables Bevy's reflection features,51/// and we add component-specific reflection by using `#[reflect(Component)]`.52/// We also illustrate how to skip serializing fields and how `FromWorld` can help53/// create runtime-initialized data.54///55/// A sample component that is fully serializable.56///57/// This component has public `x` and `y` fields that will be included in58/// the scene files. Notice how it derives `Default`, `Reflect`, and declares59/// itself as a reflected component with `#[reflect(Component)]`.60#[derive(Component, Reflect, Default)]61#[reflect(Component)] // this tells the reflect derive to also reflect component behaviors62struct ComponentA {63/// An example `f32` field64pub x: f32,65/// Another example `f32` field66pub y: f32,67}6869/// A sample component that includes both serializable and non-serializable fields.70///71/// This is useful for skipping serialization of runtime data or fields you72/// don't want written to scene files.73#[derive(Component, Reflect)]74#[reflect(Component)]75struct ComponentB {76/// A string field that will be serialized.77pub value: String,78/// A `Duration` field that should never be serialized to the scene file, so we skip it.79#[reflect(skip_serializing)]80pub _time_since_startup: Duration,81}8283/// This implements `FromWorld` for `ComponentB`, letting us initialize runtime fields84/// by accessing the current ECS resources. In this case, we acquire the `Time` resource85/// and store the current elapsed time.86impl FromWorld for ComponentB {87fn from_world(world: &mut World) -> Self {88let time = world.resource::<Time>();89ComponentB {90_time_since_startup: time.elapsed(),91value: "Default Value".to_string(),92}93}94}9596/// A simple resource that also derives `Reflect`, allowing it to be stored in scenes.97///98/// Just like a component, you can skip serializing fields or implement `FromWorld` if needed.99#[derive(Resource, Reflect, Default)]100#[reflect(Resource)]101struct ResourceA {102/// This resource tracks a `score` value.103pub score: u32,104}105106/// # Scene File Paths107///108/// `SCENE_FILE_PATH` points to the original scene file that we'll be loading.109/// `NEW_SCENE_FILE_PATH` points to the new scene file that we'll be creating110/// (and demonstrating how to serialize to disk).111///112/// The initial scene file will be loaded below and not change when the scene is saved.113const SCENE_FILE_PATH: &str = "scenes/load_scene_example.scn.ron";114115/// The new, updated scene data will be saved here so that you can see the changes.116const NEW_SCENE_FILE_PATH: &str = "scenes/load_scene_example-new.scn.ron";117118/// Loads a scene from an asset file and spawns it in the current world.119///120/// Spawning a `DynamicSceneRoot` creates a new parent entity, which then spawns new121/// instances of the scene's entities as its children. If you modify the122/// `SCENE_FILE_PATH` scene file, or if you enable file watching, you can see123/// changes reflected immediately.124fn load_scene_system(mut commands: Commands, asset_server: Res<AssetServer>) {125commands.spawn(DynamicSceneRoot(asset_server.load(SCENE_FILE_PATH)));126}127128/// Logs changes made to `ComponentA` entities, and also checks whether `ResourceA`129/// has been recently added.130///131/// Any time a `ComponentA` is modified, that change will appear here. This system132/// demonstrates how you might detect and handle scene updates at runtime.133fn log_system(134query: Query<(Entity, &ComponentA), Changed<ComponentA>>,135res: Option<Res<ResourceA>>,136) {137for (entity, component_a) in &query {138info!(" Entity({})", entity.index());139info!(140" ComponentA: {{ x: {} y: {} }}\n",141component_a.x, component_a.y142);143}144if let Some(res) = res145&& res.is_added()146{147info!(" New ResourceA: {{ score: {} }}\n", res.score);148}149}150151/// Demonstrates how to create a new scene from scratch, populate it with data,152/// and then serialize it to a file. The new file is written to `NEW_SCENE_FILE_PATH`.153///154/// This system creates a fresh world, duplicates the type registry so that our155/// custom component types are recognized, spawns some sample entities and resources,156/// and then serializes the resulting dynamic scene.157fn save_scene_system(world: &mut World) {158// Scenes can be created from any ECS World.159// You can either create a new one for the scene or use the current World.160// For demonstration purposes, we'll create a new one.161let mut scene_world = World::new();162163// The `TypeRegistry` resource contains information about all registered types (including components).164// This is used to construct scenes, so we'll want to ensure that our previous type registrations165// exist in this new scene world as well.166// To do this, we can simply clone the `AppTypeRegistry` resource.167let type_registry = world.resource::<AppTypeRegistry>().clone();168scene_world.insert_resource(type_registry);169170let mut component_b = ComponentB::from_world(world);171component_b.value = "hello".to_string();172scene_world.spawn((173component_b,174ComponentA { x: 1.0, y: 2.0 },175Transform::IDENTITY,176Name::new("joe"),177));178scene_world.spawn(ComponentA { x: 3.0, y: 4.0 });179scene_world.insert_resource(ResourceA { score: 1 });180181// With our sample world ready to go, we can now create our scene using DynamicScene or DynamicSceneBuilder.182// For simplicity, we will create our scene using DynamicScene:183let scene = DynamicScene::from_world(&scene_world);184185// Scenes can be serialized like this:186let type_registry = world.resource::<AppTypeRegistry>();187let type_registry = type_registry.read();188let serialized_scene = scene.serialize(&type_registry).unwrap();189190// Showing the scene in the console191info!("{}", serialized_scene);192193// Writing the scene to a new file. Using a task to avoid calling the filesystem APIs in a system194// as they are blocking.195//196// This can't work in Wasm as there is no filesystem access.197#[cfg(not(target_arch = "wasm32"))]198IoTaskPool::get()199.spawn(async move {200// Write the scene RON data to file201File::create(format!("assets/{NEW_SCENE_FILE_PATH}"))202.and_then(|mut file| file.write(serialized_scene.as_bytes()))203.expect("Error while writing scene to file");204})205.detach();206}207208/// Spawns a simple 2D camera and some text indicating that the user should209/// check the console output for scene loading/saving messages.210///211/// This system is only necessary for the info message in the UI.212fn infotext_system(mut commands: Commands) {213commands.spawn(Camera2d);214commands.spawn((215Text::new("Nothing to see in this window! Check the console output!"),216TextFont {217font_size: FontSize::Px(42.0),218..default()219},220Node {221align_self: AlignSelf::FlexEnd,222..default()223},224));225}226227/// To help with Bevy's automated testing, we want the example to close with an appropriate if the228/// scene fails to load. This is most likely not something you want in your own app.229fn panic_on_fail(scenes: Query<&DynamicSceneRoot>, asset_server: Res<AssetServer>) {230for scene in &scenes {231if let Some(LoadState::Failed(err)) = asset_server.get_load_state(&scene.0) {232panic!("Failed to load scene. {err}");233}234}235}236237238