Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): prefab scene persistence — load-expand / save-collapse (REARCH_PREFABS PF2)

esengine57b3b0e92e49
diff --git a/desktop/src/engine/PrefabInstance.ts b/desktop/src/engine/PrefabInstance.ts
index 757d9ec57..a935ab606 100644
--- a/desktop/src/engine/PrefabInstance.ts
+++ b/desktop/src/engine/PrefabInstance.ts
@@ -1,5 +1,14 @@
import { flattenPrefab, diffAgainstSource } from 'esengine';
-import type { PrefabData, PrefabOverride, ProcessedEntity, PrefabEntityId } from 'esengine';
+import type { PrefabData, PrefabOverride, ProcessedEntity, PrefabEntityId, SceneData } from 'esengine';
+
+type SceneEntity = SceneData['entities'][number];
+
+/** A prefab-instance tag carried by each expanded model entity (origin + grouping). */
+export interface InstanceTag {
+ instanceRoot: number;
+ prefabId: PrefabEntityId;
+ prefab?: string; // set only on the instance root
+}
/**
* Prefab instance expand/collapse (REARCH_PREFABS.md §3-4, PF2 core).
@@ -172,3 +181,96 @@ export function collapseEntry(
): PrefabInstanceEntry {
return { id: rootId, parent: sceneParent, ...collapseInstance(prefab, prefabRef, expanded) };
}
+
+// ── Scene file ⇄ model (whole-scene expand/collapse over a prefab loader) ────
+// Load EXPANDS each prefab-instance entry into ordinary tagged entities; save
+// COLLAPSES each tagged instance subtree back to one entry. The prefab loader is
+// injected (ProjectStore reads `.esprefab` via the AssetDatabase) so this stays
+// pure + unit-testable.
+
+type LoadPrefab = (ref: string) => Promise<PrefabData | null>;
+
+/** A prefab-instance entry as it appears in a scene file (carries a `prefab` ref). */
+function isPrefabEntry(e: unknown): e is PrefabInstanceEntry {
+ return !!e && typeof e === 'object' && typeof (e as { prefab?: unknown }).prefab === 'string';
+}
+
+const toSceneEntity = (e: ProcessedEntity): SceneEntity =>
+ ({ id: e.id, name: e.name, parent: e.parent, children: e.children, components: e.components, visible: e.visible }) as unknown as SceneEntity;
+
+const toProcessed = (e: SceneEntity, prefabId: PrefabEntityId): ProcessedEntity => ({
+ id: e.id,
+ prefabEntityId: prefabId,
+ name: e.name,
+ parent: e.parent,
+ children: e.children,
+ components: e.components as ProcessedEntity['components'],
+ visible: e.visible ?? true,
+});
+
+/**
+ * Expand a scene's prefab-instance entries into ordinary entities + their tags.
+ * Non-prefab entities pass through. An unresolvable prefab ref drops the entry
+ * (logged by the caller). Returns the fully-expanded scene + the tags to apply.
+ */
+export async function expandScenePrefabs(
+ scene: SceneData,
+ loadPrefab: LoadPrefab,
+ allocateId: () => number,
+): Promise<{ scene: SceneData; tags: Array<{ id: number; tag: InstanceTag }> }> {
+ const out: SceneEntity[] = [];
+ const tags: Array<{ id: number; tag: InstanceTag }> = [];
+ for (const raw of scene.entities as unknown[]) {
+ if (!isPrefabEntry(raw)) {
+ out.push(raw as SceneEntity);
+ continue;
+ }
+ const prefab = await loadPrefab(raw.prefab);
+ if (!prefab) continue; // unresolved prefab — skip (caller warns)
+ const { entities, rootId } = expandEntry(prefab, raw, allocateId);
+ for (const pe of entities) {
+ out.push(toSceneEntity(pe));
+ tags.push({
+ id: pe.id,
+ tag: { instanceRoot: rootId, prefabId: pe.prefabEntityId, prefab: pe.id === rootId ? raw.prefab : undefined },
+ });
+ }
+ }
+ return { scene: { ...scene, entities: out } as SceneData, tags };
+}
+
+/**
+ * Collapse a model's prefab-instance subtrees back to one entry each (the inverse
+ * of {@link expandScenePrefabs}). `tagOf` is the model's instance-tag lookup;
+ * non-instance entities pass through.
+ */
+export async function collapseScenePrefabs(
+ entities: readonly SceneEntity[],
+ tagOf: (id: number) => InstanceTag | undefined,
+ loadPrefab: LoadPrefab,
+): Promise<SceneEntity[]> {
+ const groups = new Map<number, SceneEntity[]>();
+ const out: SceneEntity[] = [];
+ for (const e of entities) {
+ const tag = tagOf(e.id);
+ if (!tag) {
+ out.push(e);
+ continue;
+ }
+ const g = groups.get(tag.instanceRoot);
+ if (g) g.push(e);
+ else groups.set(tag.instanceRoot, [e]);
+ }
+ for (const [rootId, group] of groups) {
+ const rootTag = tagOf(rootId);
+ const root = group.find((e) => e.id === rootId);
+ const prefab = rootTag?.prefab ? await loadPrefab(rootTag.prefab) : null;
+ if (!rootTag?.prefab || !prefab || !root) {
+ out.push(...group); // not a resolvable instance — keep raw (lossless)
+ continue;
+ }
+ const processed = group.map((e) => toProcessed(e, tagOf(e.id)!.prefabId));
+ out.push(collapseEntry(prefab, rootTag.prefab, processed, rootId, root.parent ?? null) as unknown as SceneEntity);
+ }
+ return out;
+}
diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.ts
index db7a250c0..f285b11bd 100644
--- a/desktop/src/engine/SceneModel.ts
+++ b/desktop/src/engine/SceneModel.ts
@@ -93,6 +93,7 @@ export class SceneModelImpl {
this.data = loaded;
this.runtimeToSource.clear();
this.sourceToRuntime.clear();
+ this.prefabTags.clear();
let maxId = 0;
for (const e of loaded.entities) if (e.id > maxId) maxId = e.id;
this.nextSourceId = maxId + 1;
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 435957dae..c95ebbc60 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1,10 +1,11 @@
import { createStore } from 'zustand/vanilla';
-import { getComponent, Assets } from 'esengine';
-import type { SceneData } from 'esengine';
+import { getComponent, Assets, migratePrefabData } from 'esengine';
+import type { SceneData, PrefabData } from 'esengine';
import { EngineHost } from '@/engine/EngineHost';
import { SceneModel } from '@/engine/SceneModel';
import { Reconciler } from '@/engine/Reconciler';
import { EditorHistory } from '@/engine/EditorHistory';
+import { expandScenePrefabs, collapseScenePrefabs } from '@/engine/PrefabInstance';
import { setUserSchemas, type UserComponentSchema } from '@/engine/schema';
import { useSelection } from '@/store/selectionStore';
import { Toasts } from '@/store/Toasts';
@@ -63,6 +64,8 @@ class ProjectStoreImpl {
/** path → uuid (reverse), so a Content Browser drag (which carries a path) can
* be turned into a portable `@uuid:` ref for the model. */
private readonly pathToUuid = new Map<string, string>();
+ /** ref → loaded `.esprefab` (PrefabData), for scene load-expand / save-collapse. */
+ private readonly prefabCache = new Map<string, PrefabData>();
/** The latest scene preload result; the Reconciler resolver reads handles from
* it for entities recreated incrementally (duplicate / undo / play-stop). */
private lastAssetResult: PreloadResult | null = null;
@@ -166,16 +169,26 @@ class ProjectStoreImpl {
`are preserved verbatim in the source-of-truth model and on save (JSON-first).`,
);
}
- // Build the uuid→path registry + point the engine Assets loader at the
- // estella:// transport, then preload EVERY referenced asset type (textures,
- // materials, fonts, audio, spine, …) through the engine's own system, and
- // resolve a COPY of the scene (refs → handles) for the World.
+ // Build the uuid→path registry first (prefab + texture refs resolve through it).
await this.buildAssetRegistry();
+
+ // Expand prefab-instance entries into ordinary tagged entities (the model is
+ // always expanded; the file stores deltas) — REARCH_PREFABS.md. Internal
+ // entities get fresh ids above the file's max so they don't collide.
+ let nextId = raw.entities.reduce((m, e) => Math.max(m, (e as { id?: number }).id ?? 0), 0) + 1;
+ const { scene: expandedRaw, tags } = await expandScenePrefabs(
+ raw,
+ (ref) => this.loadPrefabAsset(ref),
+ () => nextId++,
+ );
+
+ // Preload EVERY referenced asset type through the engine's own system, and
+ // resolve a COPY of the (expanded) scene (refs → handles) for the World.
const assets = EngineHost.getResource(Assets);
- let resolved: SceneData = raw;
+ let resolved: SceneData = expandedRaw;
if (assets) {
- const result = await assets.preloadSceneAssets(raw);
- resolved = JSON.parse(JSON.stringify(raw)) as SceneData; // resolveSceneAssetPaths mutates
+ const result = await assets.preloadSceneAssets(expandedRaw);
+ resolved = JSON.parse(JSON.stringify(expandedRaw)) as SceneData; // resolveSceneAssetPaths mutates
assets.resolveSceneAssetPaths(resolved, result);
this.lastAssetResult = result; // narrowed to the handle maps the resolver reads
}
@@ -191,7 +204,9 @@ class ProjectStoreImpl {
// Incremental recreate (duplicate / undo / play-stop) re-resolves @uuid:→handle
// from the same preload result — for all types, not just textures.
Reconciler.setAssetResolver((uuid) => this.handleForUuid(uuid));
- Reconciler.adopt(raw, resolved);
+ Reconciler.adopt(expandedRaw, resolved);
+ // Re-apply prefab-instance tags (adopt cleared them) so save can collapse.
+ for (const { id, tag } of tags) SceneModel.setPrefabTag(id, tag);
EngineHost.syncEditorViewToScene();
this.store.setState({ project: { ...st, currentScene: rel } });
}
@@ -206,6 +221,7 @@ class ProjectStoreImpl {
private async buildAssetRegistry(): Promise<void> {
this.uuidToPath.clear();
this.pathToUuid.clear();
+ this.prefabCache.clear();
if (!this.state) return;
try {
const { index } = await window.estella.project.scanAssets();
@@ -244,6 +260,24 @@ class ProjectStoreImpl {
return r.materialHandles.get(path) ?? r.fontHandles.get(path) ?? 0;
}
+ /** Load a `.esprefab` asset (PrefabData) by ref, cached. The scene load-expand
+ * / save-collapse path resolves prefab instances through this. */
+ private async loadPrefabAsset(ref: string): Promise<PrefabData | null> {
+ if (!ref.startsWith(UUID_PREFIX)) return null;
+ const cached = this.prefabCache.get(ref);
+ if (cached) return cached;
+ const path = this.uuidToPath.get(ref.slice(UUID_PREFIX.length).toLowerCase());
+ if (!path) return null;
+ try {
+ const prefab = migratePrefabData(JSON.parse(await window.estella.fs.read(path))).data as PrefabData;
+ this.prefabCache.set(ref, prefab);
+ return prefab;
+ } catch (err) {
+ console.warn('[project] prefab load failed', path, err);
+ return null;
+ }
+ }
+
/** Display info for an asset ref (`@uuid:`), or null (none / unresolved). For
* the inspector's asset control: the project-relative path + a leaf name. */
assetInfo(ref: unknown): { path: string; name: string } | null {
@@ -277,15 +311,21 @@ class ProjectStoreImpl {
}
/**
- * Serialize the editor's source-of-truth model — lossless (JSON-first L4).
- * The model retains everything the World drops (unknown components/fields,
- * invisible entities, `@uuid:` asset refs), so this no longer reads from the
- * World and needs no handle→uuid restoration.
+ * Serialize the editor's source-of-truth model — lossless (JSON-first L4) +
+ * prefab-aware: collapse each expanded prefab-instance subtree back to a single
+ * `{prefab, overrides, added, removed}` delta entry (REARCH_PREFABS.md). The
+ * model retains everything the World drops (unknown components/fields, invisible
+ * entities, `@uuid:` asset refs), so this reads only the model.
*/
- private serializeCurrent(): SceneData {
+ private async serializeCurrent(): Promise<SceneData> {
const model = SceneModel.serialize();
if (!model) throw new Error('no scene loaded');
- return { ...model, name: this.state?.name ?? model.name };
+ const entities = await collapseScenePrefabs(
+ model.entities,
+ (id) => SceneModel.prefabTag(id),
+ (ref) => this.loadPrefabAsset(ref),
+ );
+ return { ...model, name: this.state?.name ?? model.name, entities };
}
private async writeScene(relPath: string, data: SceneData): Promise<void> {
@@ -308,7 +348,7 @@ class ProjectStoreImpl {
async save(): Promise<void> {
const st = this.state;
if (!st || !st.currentScene) throw new Error('no scene to save');
- await this.writeScene(st.currentScene, this.serializeCurrent());
+ await this.writeScene(st.currentScene, await this.serializeCurrent());
await this.persistLastScene(st.currentScene);
Toasts.push(`Saved ${st.currentScene.split('/').pop()}`, 'success');
}
@@ -316,7 +356,7 @@ class ProjectStoreImpl {
/** Write the current world to a project-relative path (explicit, no lossy guard). */
async saveAs(relPath: string): Promise<void> {
if (!this.state) throw new Error('no project open');
- await this.writeScene(relPath, this.serializeCurrent());
+ await this.writeScene(relPath, await this.serializeCurrent());
await this.persistLastScene(relPath);
Toasts.push(`Saved ${relPath.split('/').pop()}`, 'success');
}
diff --git a/desktop/tests/prefab-instance.test.ts b/desktop/tests/prefab-instance.test.ts
index 5347d4faf..59e664655 100644
--- a/desktop/tests/prefab-instance.test.ts
+++ b/desktop/tests/prefab-instance.test.ts
@@ -8,14 +8,17 @@
*/
import { describe, it, expect } from 'vitest';
import { migratePrefabData } from 'esengine';
-import type { PrefabData } from 'esengine';
+import type { PrefabData, SceneData } from 'esengine';
import {
expandInstance,
collapseInstance,
expandEntry,
collapseEntry,
+ expandScenePrefabs,
+ collapseScenePrefabs,
type PrefabInstanceDelta,
type PrefabInstanceEntry,
+ type InstanceTag,
} from '@/engine/PrefabInstance';
function turretPrefab(): PrefabData {
@@ -170,4 +173,54 @@ describe('Prefab instance expand/collapse round-trip', () => {
).toEqual({ x: 9, y: 0, z: 0 });
expect(back.overrides.find((o) => o.type === 'name' && o.prefabEntityId === 'barrel')?.value).toBe('BigBarrel');
});
+
+ // ── Whole-scene expand/collapse (the ProjectStore load/save core) ──
+ it('a whole scene round-trips: a prefab-instance entry ⇄ expanded+tagged ⇄ entry', async () => {
+ const prefab = turretPrefab();
+ const loadPrefab = async (ref: string) => (ref === REF ? prefab : null);
+ const scene = {
+ version: '1.0',
+ name: 's',
+ entities: [
+ { id: 1, name: 'Ground', parent: null, children: [], components: [], visible: true },
+ { id: 2, prefab: REF, parent: 1, overrides: [{ prefabEntityId: 'barrel', type: 'name', value: 'BigBarrel' }], added: [], removed: ['scope'] },
+ ],
+ } as unknown as SceneData;
+
+ let nid = 100;
+ const { scene: expanded, tags } = await expandScenePrefabs(scene, loadPrefab, () => nid++);
+ // Ground + (root + barrel) — scope removed.
+ expect(expanded.entities).toHaveLength(3);
+ expect(expanded.entities.find((e) => e.id === 2)?.name).toBe('Turret'); // root pinned to entry id
+ expect(expanded.entities.find((e) => e.name === 'BigBarrel')).toBeDefined(); // override applied
+
+ const tagMap = new Map(tags.map((t) => [t.id, t.tag]));
+ const collapsed = await collapseScenePrefabs(expanded.entities, (id) => tagMap.get(id), loadPrefab);
+
+ // Ground (untouched) + one instance entry.
+ expect(collapsed).toHaveLength(2);
+ expect(collapsed.find((e) => e.id === 1)?.name).toBe('Ground');
+ const entry = collapsed.find((e) => (e as { prefab?: string }).prefab === REF) as unknown as PrefabInstanceEntry;
+ expect(entry.id).toBe(2);
+ expect(entry.parent).toBe(1);
+ expect(entry.removed.sort()).toEqual(['scope']);
+ expect(entry.overrides.find((o) => o.type === 'name' && o.prefabEntityId === 'barrel')?.value).toBe('BigBarrel');
+ });
+
+ it('a scene with no prefab instances passes through unchanged', async () => {
+ const loadPrefab = async () => null;
+ const scene = {
+ version: '1.0',
+ name: 's',
+ entities: [{ id: 1, name: 'A', parent: null, children: [], components: [], visible: true }],
+ } as unknown as SceneData;
+ let nid = 100;
+ const { scene: expanded, tags } = await expandScenePrefabs(scene, loadPrefab, () => nid++);
+ expect(expanded.entities).toHaveLength(1);
+ expect(tags).toHaveLength(0);
+ const tagMap = new Map<number, InstanceTag>();
+ const collapsed = await collapseScenePrefabs(expanded.entities, (id) => tagMap.get(id), loadPrefab);
+ expect(collapsed).toHaveLength(1);
+ expect(collapsed[0].name).toBe('A');
+ });
});