Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/scene/scene.rs
6592 views
1
//! This example demonstrates how to load scene data from files and then dynamically
2
//! apply that data to entities in your Bevy `World`. This includes spawning new
3
//! entities and applying updates to existing ones. Scenes in Bevy encapsulate
4
//! serialized and deserialized `Components` or `Resources` so that you can easily
5
//! store, load, and manipulate data outside of a purely code-driven context.
6
//!
7
//! This example also shows how to do the following:
8
//! * Register your custom types for reflection, which allows them to be serialized,
9
//! deserialized, and manipulated dynamically.
10
//! * Skip serialization of fields you don't want stored in your scene files (like
11
//! runtime values that should always be computed dynamically).
12
//! * Save a new scene to disk to show how it can be updated compared to the original
13
//! scene file (and how that updated scene file might then be used later on).
14
//!
15
//! The example proceeds by creating components and resources, registering their types,
16
//! loading a scene from a file, logging when changes are detected, and finally saving
17
//! a new scene file to disk. This is useful for anyone wanting to see how to integrate
18
//! file-based scene workflows into their Bevy projects.
19
//!
20
//! # Note on working with files
21
//!
22
//! The saving behavior uses the standard filesystem APIs, which are blocking, so it
23
//! utilizes a thread pool (`IoTaskPool`) to avoid stalling the main thread. This
24
//! won't work on WASM because WASM typically doesn't have direct filesystem access.
25
//!
26
27
use bevy::{asset::LoadState, prelude::*, tasks::IoTaskPool};
28
use core::time::Duration;
29
use std::{fs::File, io::Write};
30
31
/// The entry point of our Bevy app.
32
///
33
/// Sets up default plugins, registers all necessary component/resource types
34
/// for serialization/reflection, and runs the various systems in the correct schedule.
35
fn main() {
36
App::new()
37
.add_plugins(DefaultPlugins)
38
.add_systems(
39
Startup,
40
(save_scene_system, load_scene_system, infotext_system),
41
)
42
.add_systems(Update, (log_system, panic_on_fail))
43
.run();
44
}
45
46
/// # Components, Resources, and Reflection
47
///
48
/// Below are some simple examples of how to define your own Bevy `Component` types
49
/// and `Resource` types so that they can be properly reflected, serialized, and
50
/// 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 help
53
/// 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 in
58
/// the scene files. Notice how it derives `Default`, `Reflect`, and declares
59
/// 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 behaviors
62
struct ComponentA {
63
/// An example `f32` field
64
pub x: f32,
65
/// Another example `f32` field
66
pub y: f32,
67
}
68
69
/// A sample component that includes both serializable and non-serializable fields.
70
///
71
/// This is useful for skipping serialization of runtime data or fields you
72
/// don't want written to scene files.
73
#[derive(Component, Reflect)]
74
#[reflect(Component)]
75
struct ComponentB {
76
/// A string field that will be serialized.
77
pub value: String,
78
/// A `Duration` field that should never be serialized to the scene file, so we skip it.
79
#[reflect(skip_serializing)]
80
pub _time_since_startup: Duration,
81
}
82
83
/// This implements `FromWorld` for `ComponentB`, letting us initialize runtime fields
84
/// by accessing the current ECS resources. In this case, we acquire the `Time` resource
85
/// and store the current elapsed time.
86
impl FromWorld for ComponentB {
87
fn from_world(world: &mut World) -> Self {
88
let time = world.resource::<Time>();
89
ComponentB {
90
_time_since_startup: time.elapsed(),
91
value: "Default Value".to_string(),
92
}
93
}
94
}
95
96
/// 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)]
101
struct ResourceA {
102
/// This resource tracks a `score` value.
103
pub score: u32,
104
}
105
106
/// # Scene File Paths
107
///
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 creating
110
/// (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.
113
const SCENE_FILE_PATH: &str = "scenes/load_scene_example.scn.ron";
114
115
/// The new, updated scene data will be saved here so that you can see the changes.
116
const NEW_SCENE_FILE_PATH: &str = "scenes/load_scene_example-new.scn.ron";
117
118
/// 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 new
121
/// instances of the scene's entities as its children. If you modify the
122
/// `SCENE_FILE_PATH` scene file, or if you enable file watching, you can see
123
/// changes reflected immediately.
124
fn load_scene_system(mut commands: Commands, asset_server: Res<AssetServer>) {
125
commands.spawn(DynamicSceneRoot(asset_server.load(SCENE_FILE_PATH)));
126
}
127
128
/// 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 system
132
/// demonstrates how you might detect and handle scene updates at runtime.
133
fn log_system(
134
query: Query<(Entity, &ComponentA), Changed<ComponentA>>,
135
res: Option<Res<ResourceA>>,
136
) {
137
for (entity, component_a) in &query {
138
info!(" Entity({})", entity.index());
139
info!(
140
" ComponentA: {{ x: {} y: {} }}\n",
141
component_a.x, component_a.y
142
);
143
}
144
if let Some(res) = res
145
&& res.is_added()
146
{
147
info!(" New ResourceA: {{ score: {} }}\n", res.score);
148
}
149
}
150
151
/// 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 our
155
/// custom component types are recognized, spawns some sample entities and resources,
156
/// and then serializes the resulting dynamic scene.
157
fn 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.
161
let mut scene_world = World::new();
162
163
// 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 registrations
165
// exist in this new scene world as well.
166
// To do this, we can simply clone the `AppTypeRegistry` resource.
167
let type_registry = world.resource::<AppTypeRegistry>().clone();
168
scene_world.insert_resource(type_registry);
169
170
let mut component_b = ComponentB::from_world(world);
171
component_b.value = "hello".to_string();
172
scene_world.spawn((
173
component_b,
174
ComponentA { x: 1.0, y: 2.0 },
175
Transform::IDENTITY,
176
Name::new("joe"),
177
));
178
scene_world.spawn(ComponentA { x: 3.0, y: 4.0 });
179
scene_world.insert_resource(ResourceA { score: 1 });
180
181
// 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:
183
let scene = DynamicScene::from_world(&scene_world);
184
185
// Scenes can be serialized like this:
186
let type_registry = world.resource::<AppTypeRegistry>();
187
let type_registry = type_registry.read();
188
let serialized_scene = scene.serialize(&type_registry).unwrap();
189
190
// Showing the scene in the console
191
info!("{}", serialized_scene);
192
193
// Writing the scene to a new file. Using a task to avoid calling the filesystem APIs in a system
194
// as they are blocking.
195
//
196
// This can't work in Wasm as there is no filesystem access.
197
#[cfg(not(target_arch = "wasm32"))]
198
IoTaskPool::get()
199
.spawn(async move {
200
// Write the scene RON data to file
201
File::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
}
207
208
/// Spawns a simple 2D camera and some text indicating that the user should
209
/// check the console output for scene loading/saving messages.
210
///
211
/// This system is only necessary for the info message in the UI.
212
fn infotext_system(mut commands: Commands) {
213
commands.spawn(Camera2d);
214
commands.spawn((
215
Text::new("Nothing to see in this window! Check the console output!"),
216
TextFont {
217
font_size: 42.0,
218
..default()
219
},
220
Node {
221
align_self: AlignSelf::FlexEnd,
222
..default()
223
},
224
));
225
}
226
227
/// To help with Bevy's automated testing, we want the example to close with an appropriate if the
228
/// scene fails to load. This is most likely not something you want in your own app.
229
fn panic_on_fail(scenes: Query<&DynamicSceneRoot>, asset_server: Res<AssetServer>) {
230
for scene in &scenes {
231
if let Some(LoadState::Failed(err)) = asset_server.get_load_state(&scene.0) {
232
panic!("Failed to load scene. {err}");
233
}
234
}
235
}
236
237