Hazel

Scenes

A scene is a .bsn text file: a flat list of entities, each a list of reflected components. Saving walks the live World and writes only what describes the scene; loading reads the file back through the type registry and rebuilds everything that was left out. This page covers the format, what gets written, how loading recovers from types that changed, and what a component author has to do to stay compatible with scenes already on disk.

The code is in three places:

CrateRole
renzora_bsnThe format: the scene IR (DynamicScene, DynamicEntity), the text serializer, type resolution and aliases
renzora_engine::scene_ioThe pipelines: what a save extracts, what a load repairs and rehydrates, nested scenes and prefabs
renzora_sceneThe editor side: scene tabs, reloading a file edited outside the editor, missing-asset reports

The format

Bevy's own scene serialization was removed when Bevy moved to BSN, and BSN has no runtime text loader yet, so Renzora owns an interim format. It is BSN-shaped, and every value inside it is encoded by bevy_reflect's own serde, so only the container grammar is Renzora's.

// renzora interim bsn v1
entity 4294967295 {
    bevy_ecs::name::Name: ("Player"),
    bevy_transform::components::transform::Transform: (translation:(x:0,y:1,z:0),rotation:(0,0,0,1),scale:(x:1,y:1,z:1)),
    my_game::health::Health: (current:100.0,max:100.0),
}
entity 4294967294 {
    bevy_ecs::name::Name: ("Sword"),
    bevy_ecs::hierarchy::ChildOf: (4294967295),
}
  • The first line is a fixed header.
  • Each component is <full type path>: <RON value>,. The value is what TypedReflectSerializer produces, and it is read back with TypedReflectDeserializer.
  • Hierarchy is the reflected ChildOf component, not nesting. Entity references are remapped to fresh entities on load.
  • The id after entity is Entity::to_bits(), not an index: index 0 is 4294967295, index 1 is 4294967294, with the generation in the high 32 bits. Hand-written ids that do not decode are rejected with invalid entity id bits rather than silently pointing at the wrong entity.
  • resource <path>: <value>, lines exist in the grammar, but a normal save writes no resources (see below).

The serializer sits behind renzora_bsn::SceneSerializer (serialize, deserialize, deserialize_lossy), implemented by BsnSerializer. When Bevy ships a runtime BSN loader, that implementation is the one thing that changes.

The default entry scene is scenes/main.bsn (main_scene in project.toml).

What a save writes

renzora_engine::scene_io::save_scene(world, path) writes a scene file; serialize_scene_to_string(world) returns the text; save_current_scene(world) saves to the scene the editor last had open, falling back to main_scene.

A save is a description, not a dump. It writes deliberately less than the world holds, and a load puts the rest back. That is what lets a scene authored with a plugin installed still load in a build without it.

Which entities. saveable_entities picks entities that:

  • have a Name. An entity without one is never saved. This is the rule that catches people most often: something spawned in code without a Name disappears on the next load;
  • are not editor chrome (HideInHierarchy, the editor camera, and anything under a hidden ancestor);
  • are not Persistent. Those belong to an autoload scene (below), and saving them would bake a second copy into this file;
  • are not the generated insides of a model or a nested scene (descendants of a SceneInstance or MeshInstanceData). Those come from their own files.

Every saved entity also gets a SceneEntityId (a fresh one if it has none or shares one with an entity already seen, which is what a duplicate does), and a SiblingIndex that records its order under its parent.

Which components. extract_authored runs the reflected components of those entities through a deny list. Denied:

  • all resources;
  • derived render state: meshes and 3D materials (rebuilt from MeshInstanceData and material references), cameras' runtime parts, Aabb, ViewVisibility, InheritedVisibility, shadow cascades, RenderEntity, SyncToRenderWorld, TransformTreeChanged;
  • Children (rebuilt from ChildOf);
  • runtime state owned by a subsystem: animation playback, networking components, the physics engine's own bodies, engine-managed rendering settings (Solari lighting, DLSS, temporal jitter, mip bias);
  • anything whose value fails to serialize.

A component that is not registered in the type registry is invisible to reflection, and therefore never saved at all.

When it happens. Explicitly from the editor (Ctrl+S, the autosave timer), and when Play starts: Play writes the open scene to disk so the game process loads what you see, even with autosave off.

What a load does

load_scene(world, path) is the synchronous load used by the editor and at boot. In order:

  1. Refuses a scene that is already being loaded further up the stack, so a scene that instances itself cannot recurse forever.
  2. Reads the file from the mounted .rpak archive if the game has one, otherwise from disk.
  3. Deserializes lossily (deserialize_lossy): a component whose type cannot be resolved, or whose value does not deserialize into the current type, is skipped and the rest of the entity loads. The skipped type paths are logged and announced with SceneLoadedWithSkippedTypes { path, skipped }, which the editor shows as a notification.
  4. Prunes entities that should never have been saved: orphans whose ChildOf points at a parent outside the scene (typically editor UI an older save leaked), and stray UI.
  5. Writes the entities into the world, reinserts ChildOf so hierarchy hooks fire, and restores sibling order from SiblingIndex.
  6. Expands nested scenes and prefabs (expand_scene_instances).
  7. Rehydrates what the save left out: meshes from MeshInstanceData, sprites, cameras, lights and visibility.

The result is reported as observer events (trigger them with world.trigger, observe with On<SceneLoaded>):

EventFields
SceneLoadedpath
SceneLoadFailedpath, error
SceneLoadedWithSkippedTypespath, skipped: Vec<String>

SceneLoadState (phase: Idle, Loading, Ready, Failed; current_path; progress) tracks the most recent load for UI. The synchronous load jumps from 0 to 1 in one frame.

A load requested by a game (a script's scene load, pushed to PendingSceneLoad) despawns the current scene (everything not Persistent) and then streams the new one: parsing happens on a task pool, and entities are written a few milliseconds' worth per frame, so progress moves smoothly. See Streaming.

Resolving types that moved or were renamed

A scene names every component by its full type path, and a Rust type path changes whenever the type moves module or crate. The loader resolves each path in three steps:

  1. Exact match in the type registry.
  2. Short name. If the exact path is unknown, the last segment (Health) is matched against registered types. This handles a type that moved without any action from you. It only applies when the short name is unambiguous: if two registered types are both called Health, the entry is skipped rather than given to the wrong one.
  3. Alias. For a type that was renamed, register an alias from the old name to the new one in the owning plugin's build:
// Scenes saved before the rename still load.
renzora_bsn::register_component_alias("Health", "Vitals");

old may be the old short name or the old full path; current is the new name. Either way, the next save writes the current path, so a scene heals on save.

A few changes are handled inside renzora_bsn itself: enum variants Bevy renamed (Default becoming Normal for UI alignment) are mapped, and types Bevy removed outright (FocusPolicy, Interaction, RelativeCursorPosition) are dropped quietly instead of being reported.

Contract types sidestep the problem by pinning their path: #[type_path = "renzora::core::components"] on a component keeps the saved path stable however the crate that defines it is reorganised.

Adding a field to a saved component

A scene saved before a field existed has no value for it. TypedReflectDeserializer wants a complete value, so without a default the component is skipped in every older scene, and the skip report names the component, not the field. Give every field added after scenes exist a default, on both paths a value can take:

use bevy::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Component, Reflect, Serialize, Deserialize, Default, Clone)]
#[reflect(Component, Default, Serialize, Deserialize)]
pub struct Spawner {
    pub interval: f32,
    /// Added after scenes existed: older files load with 8.
    #[serde(default = "default_max_alive")]
    #[reflect(default = "default_max_alive")]
    pub max_alive: u32,
}

fn default_max_alive() -> u32 {
    8
}

#[reflect(default)] covers a type deserialized through reflection; #[serde(default)] covers one registered with #[reflect(Deserialize)], where reflection hands the value to serde. Using both means the field works whichever way the type is registered later. A plain #[reflect(default)] / #[serde(default)] uses the field type's Default.

Removing a field is not free either. Reflection deserialization rejects a field the type no longer has (unknown field), so the component is skipped in every scene that still carries the old value, until each is re-saved. Leave the field in place, unused, until your scenes have been opened and saved again, then delete it.

In short: adding a field needs a default, removing one breaks old files until they are re-saved, moving the type needs nothing, and only a rename needs an alias.

Nested scenes and prefabs

An entity with a SceneInstance { source, .. } stands for the contents of another .bsn file. On load, its contents are spawned as its children from that file; on save, only the instance entity is written, because its children belong to the other file. A prefab is the same mechanism: renzora::core::prefab::prefab_bundle(path, transform) builds the entity, and spawn_prefab(world, path, transform) spawns it.

A SceneInstance can also be streamed, loading and unloading its contents by camera distance in a running game. See Streaming.

The editor refuses a reference that would make a scene contain itself (would_create_reference_cycle), and the loader's cycle guard catches any that get through.

Autoload scenes

project.toml's autoload lists scenes that load before main_scene and stay loaded:

autoload = ["scenes/hud.bsn", "scenes/music.bsn"]

Every entity they spawn is tagged renzora::Persistent. A scene load despawns everything else and skips those, so a HUD, music player or loading screen survives level changes. Saving skips them too, so the open scene never bakes in a copy. In the editor, Play loads them and Stop unloads them, so they can be tested without an export.

In the editor

renzora_scene adds the authoring side:

  • External edits. When the open .bsn changes on disk from outside the editor (a text editor, version control), it is reloaded. It is not reloaded when the change is the editor's own save (SelfWrites recognises it), during Play or Simulate, or when the tab has unsaved edits, in which case the editor asks which version to keep (ExternalSceneEdits, prompt by default).
  • Missing assets. A model or material file deleted while scenes still reference it raises a Console warning and a Problems entry, cleared when the file comes back.

Checklist for a component that should save

  1. Derive Reflect and add #[reflect(Component)].
  2. Register the type (app.register_type::<T>()) from a Runtime plugin, so the shipped game knows it. A type registered only by an editor plugin is skipped when the game loads the scene.
  3. Put it on an entity with a Name.
  4. Give fields added later a default.
  5. Register an alias when you rename the type.

See Components for the full component recipe, including the Inspector.