Making Edits Undoable
How the editor's undo history works, and how to put a panel's or tool's edits on it so that Ctrl+Z, Ctrl+Y and the History panel see them.
The model
Undo is a command system, not a snapshot of the world. Every user action is an UndoCommand that knows how to apply itself and how to reverse itself:
pub trait UndoCommand: Any + Send + Sync {
fn label(&self) -> &str { "edit" } // shown in the History panel
fn execute(&mut self, world: &mut World); // first apply, and every redo
fn undo(&mut self, world: &mut World);
fn merge(&mut self, other: &dyn UndoCommand) -> bool { false }
}
Commands live on per-document stacks in the UndoStacks resource, keyed by UndoContext:
| Context | Used by |
|---|---|
UndoContext::Scene | The open scene: viewport, Hierarchy, Inspector, terrain, tilemaps. The default. |
UndoContext::MaterialGraph(path) | A material document, one stack per file. |
UndoContext::Other(path) | Any other asset document (particle effects, animation clips and so on), one stack per file. |
Each stack holds up to MAX_DEPTH (500) steps.
Where it lives
The trait, the contexts, the stacks and the entry points (execute, record, seal, active_context, undo_once, redo_once) are in the contract, renzora_shell_api::undo; a native plugin reaches them as renzora::undo. They depend on nothing but Bevy, so a plugin can implement UndoCommand for its own edits and push them onto the same history the editor shows.
That split is deliberate. UndoStacks is a resource, so what matters is its TypeId: a plugin with a private copy of the trait and the resource would push onto a stack that Ctrl+Z never reads, so the edit would look undoable and silently not be.
renzora_undo holds the UndoPlugin (routing and shortcuts), every concrete command, and re-exports the contract module, so renzora_undo::execute and friends work from engine crates. The History panel is renzora_history.
The rule: record a command, do not just mutate
// Not applied yet: execute applies it, then records it.
renzora_undo::execute(world, ctx, Box::new(cmd));
// Already applied during the gesture: record it without applying it again.
renzora_undo::record(world, ctx, Box::new(cmd));
Both mark the scene as edited when they land on the scene stack. Outside the editor (no UndoStacks resource, as in a shipped game) they still apply or skip as named, and record nothing, so shared code does not need an editor check.
For ctx, use renzora_undo::active_context(world) when the edit belongs to whatever the user is looking at (the Inspector does this), and an explicit context in a document editor.
You do not write a Ctrl+Z handler. UndoPlugin reads the Undo and Redo bindings from the key bindings (skipping them while a text field has the keyboard) and always acts on UndoStacks::active. A plugin that handles its own Ctrl+Z fights that router, and its edits never appear in the History panel.
route_undo_context keeps active pointing at the focused document: the active document tab decides (a material tab gets its MaterialGraph stack, another asset tab its Other stack, a scene tab Scene), and a focused viewport always means Scene.
Picking a command
A field edit: FieldChangeCmd
use renzora_undo::{active_context, execute, FieldChangeCmd};
use std::sync::Arc;
let ctx = active_context(world);
execute(world, ctx, Box::new(FieldChangeCmd {
entity,
field_name: "Intensity",
old,
new,
set_fn: Arc::new(field.set_fn), // FieldWriter
}));
set_fn is a FieldWriter, an Arc<dyn Fn(&mut World, Entity, FieldValue) + Send + Sync>. It is boxed rather than a bare fn pointer because reflection-generated fields carry a type path and field path known only at runtime, which a function pointer cannot capture; a plain fn (such as an inspector FieldDef::set_fn) coerces in through Arc::new. merge folds consecutive edits of the same entity and field into one step, so a drag that writes every frame is a single entry.
A component changed by a button, drop or menu item
record_component_change::<C>(world, entity, before, label, after_restore) records a change you have already made to one component: before is the component as it was (None if it was absent), and the current state is read when you call it. Undo puts before back, inserting or removing as needed. It records and seals in one call, so it is the one-line way to make a one-off action undoable. after_restore runs after each undo and redo, for a component that needs a nudge to take effect (a material that must re-resolve).
record_component_scrub::<C>(world, entity, before, label) is the same for a value written every frame of a drag: consecutive calls on the same component and entity merge into one step, and the gesture seal splits one drag from the next. Call it on every write of the gesture.
Spawning, deleting, duplicating
- Delete:
delete_entities_with_undo(world, &entities)snapshots each entity's subtree (all components and children) to BSN before despawning, so undo restores lights, cameras, imported models, 2D nodes and groups faithfully. From a user-facing delete, preferdelete_entities_with_undo_reselect, which also moves the selection to the nearest surviving neighbour, so the gizmo and Inspector do not point at a despawned id. Never hand-roll adespawnfor scene entities. - Spawn:
record_spawned(world, &roots, label)records entities an editor action just created; undo removes them and redo restores them from a snapshot taken at the call. - Duplicate:
duplicate_entities_with_undo(world, &sources)returns the copies.
To restore a single component's value through reflection (to undo a component removal, for instance), use capture_component and insert_component_reflected from renzora_scripting_api::reflection.
Several changes that are one action: CompoundCmd
renzora_undo::execute(world, ctx, Box::new(renzora_undo::CompoundCmd {
label: "Paste".to_string(),
cmds: vec![Box::new(first), Box::new(second)],
}));
The parts undo together, in reverse order, as one History entry.
Blob edits: SnapshotCmd<S>
For edits that are awkward to express as fine-grained commands (heightmaps, tile layers, a whole asset document), capture a before blob when the gesture starts and an after blob when it ends, and record a SnapshotCmd, since the change already happened live:
renzora_undo::record(world, renzora_undo::UndoContext::Scene, Box::new(renzora_undo::SnapshotCmd {
label: "Terrain".to_string(),
before,
after,
restore: restore_terrain, // fn(&mut World, &S)
merge_key: None,
}));
Undo restores before; redo restores after. S is whatever cloneable payload the edit needs; keep it as small as the edit. Two consecutive snapshots with the same Some(merge_key), not separated by a seal, coalesce: the first before and the last after are kept. None never merges. renzora_terrain_editor::systems::terrain_stroke_end_system is a complete example.
For anything else, implement UndoCommand yourself; the built-ins in crates/renzora_undo/src/lib.rs (TransformCmd, RenameCmd, ReparentCmd and others) are the templates.
The change-observer pattern
When an editor edits one cheaply cloned document through many scattered code paths (a material graph, a particle effect, an animation clip), do not wrap every edit site. Run one observer that snapshots the document when it changes:
- Keep a shadow copy of the document in a
Resource, with a cheap identity of which document it is (path, entity or selection key). - Each frame, compare the document with the shadow, with
PartialEqor a serialized form when the type does not derive it. - If the identity changed (a different document was loaded), reseed the shadow and return: loading is not an edit.
- If the document changed,
recordaSnapshotCmdwith amerge_key, so a per-frame scrub collapses into one step, then update the shadow. - In
restore, apply the blob and update the shadow to match. Otherwise undo looks like a fresh edit to the observer and feeds itself back into the stack.
This covers every present and future edit path from one place. material_undo_observer in crates/renzora_material_editor/src/graph.rs is the reference; the particle editor, animation timeline and terrain graph editor use the same pattern.
Tilemaps are the exception: their document is a set of child sprite entities, so they snapshot the layer's tiles at stroke boundaries instead (tilemap_stroke_begin and tilemap_stroke_end in crates/renzora_tilemap/editor/src/lib.rs), like terrain.
Seal at gesture boundaries
Merging means two separate drags of the same field would fold into one step. UndoPlugin seals the active stack in PostUpdate (after the frame's edits are recorded) on a left mouse release, Enter, numpad Enter or Escape, so most gestures split for free. If your editor has its own commit point, seal explicitly:
renzora_undo::seal(world, &ctx); // the next record starts a new step
Checklist
- Depend on
renzora_undo(engine crate) or userenzora::undo(native plugin). - Replace direct world writes in edit handlers with
executeorrecordand the right command. - Record into the right context:
active_contextfor scene edits, the document's own context in a document editor. sealat your commit point if a mouse release or Enter does not mark it.- Check that the entries appear in the History panel and that Ctrl+Z and Ctrl+Y walk them.