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 Mode — open a .esprefab to edit its structure (P2 UX)

yhhe02c99860738
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index 4ab6eb695..026f2066f 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -12,6 +12,7 @@ import '@/document/dirtyDocs'; // side effect: registers scene + asset docs on t
import { Launcher } from '@/launcher/Launcher';
import { Toaster } from '@/components/Toaster';
import { ConfirmHost } from '@/components/ConfirmHost';
+import { PrefabModeBanner } from '@/components/PrefabModeBanner';
import { LoadingScreen } from '@/components/LoadingScreen';
import { LoadGate } from '@/store/loadGate';
import { Perf } from '@/components/Perf';
@@ -258,6 +259,7 @@ export function App() {
<div className="shell">
<ErrorBoundary label="menubar"><Perf id="menubar"><MenuBar /></Perf></ErrorBoundary>
<ErrorBoundary label="toolbar"><Perf id="toolbar"><Toolbar /></Perf></ErrorBoundary>
+ <ErrorBoundary label="prefab-banner"><PrefabModeBanner /></ErrorBoundary>
<main className="shell__workspace">
<ErrorBoundary label="activitybar"><Perf id="activitybar"><ActivityBar /></Perf></ErrorBoundary>
<DockLayout />
diff --git a/desktop/src/components/PrefabModeBanner.tsx b/desktop/src/components/PrefabModeBanner.tsx
new file mode 100644
index 000000000..81910c8ba
--- /dev/null
+++ b/desktop/src/components/PrefabModeBanner.tsx
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file PrefabModeBanner.tsx — the full-width bar shown while a prefab is open
+ * in Prefab Mode (ProjectStore.openPrefab). It names the prefab being
+ * edited and offers Save + Back to Scene. Mounted in the shell between the
+ * Toolbar and the workspace; renders nothing outside prefab mode.
+ */
+import { useSyncExternalStore } from 'react';
+import { Package, ArrowLeft, Save } from 'lucide-react';
+import { ProjectStore } from '@/project/ProjectStore';
+import { Button } from './Button';
+import { t } from '@/i18n';
+
+export function PrefabModeBanner() {
+ const project = useSyncExternalStore(ProjectStore.subscribe, ProjectStore.getSnapshot);
+ const pe = project?.prefabEdit;
+ if (!pe) return null;
+ return (
+ <div className="prefab-mode-bar">
+ <span className="pmb-icon"><Package size={14} strokeWidth={1.9} /></span>
+ <span className="pmb-label">{t('proj.prefabModeBanner')}</span>
+ <span className="pmb-name">{pe.name}</span>
+ <span className="pmb-actions">
+ <Button variant="primary" onClick={() => void ProjectStore.save()}>
+ <Save size={13} strokeWidth={1.9} /> {t('proj.prefabModeSave')}
+ </Button>
+ <Button onClick={() => void ProjectStore.exitPrefabMode()}>
+ <ArrowLeft size={13} strokeWidth={1.9} /> {t('proj.prefabModeBack')}
+ </Button>
+ </span>
+ </div>
+ );
+}
diff --git a/desktop/src/i18n/messages/common.ts b/desktop/src/i18n/messages/common.ts
index d2004fb83..d33a5ad13 100644
--- a/desktop/src/i18n/messages/common.ts
+++ b/desktop/src/i18n/messages/common.ts
@@ -38,6 +38,8 @@ export const commonMessages = defineMessages({
'discard.closeProject': { en: 'Closing the project will discard them', zh: '关闭项目将丢弃这些更改' },
'discard.openProject': { en: 'Opening another project will discard them', zh: '打开其他项目将丢弃这些更改' },
'discard.openScene': { en: 'Opening {name} will discard them', zh: '打开 {name} 将丢弃这些更改' },
+ 'discard.openPrefab': { en: 'Editing prefab {name} will discard them', zh: '编辑预制体 {name} 将丢弃这些更改' },
+ 'discard.exitPrefab': { en: 'Leaving prefab mode will discard them', zh: '退出预制体编辑将丢弃这些更改' },
'discard.openAsset': { en: 'Opening {name} will discard them', zh: '打开 {name} 将丢弃这些更改' },
'discard.closeTab': { en: 'Closing {title} will discard them', zh: '关闭 {title} 将丢弃这些更改' },
'discard.reloadChanged': {
diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.ts
index 0782137c6..6e795982c 100644
--- a/desktop/src/i18n/messages/project.ts
+++ b/desktop/src/i18n/messages/project.ts
@@ -117,6 +117,12 @@ export const projectMessages = defineMessages({
'proj.prefabExternalRefsTitle': { en: 'Clear external references?', zh: '清除外部引用?' },
'proj.prefabExternalRefsBody': { en: '{count} component reference(s) point to entities outside this selection and will be cleared in the prefab.', zh: '有 {count} 处组件引用指向所选之外的实体,将在预制体中被清除。' },
'proj.prefabExternalRefsConfirm': { en: 'Create anyway', zh: '仍然创建' },
+ 'proj.openedPrefab': { en: 'Editing prefab {name}', zh: '正在编辑预制体 {name}' },
+ 'proj.savedPrefab': { en: 'Saved prefab {name}', zh: '已保存预制体 {name}' },
+ 'proj.prefabModeNested': { en: 'Nested / variant prefabs can\'t be edited in place yet', zh: '暂不支持原位编辑嵌套 / 变体预制体' },
+ 'proj.prefabModeBanner': { en: 'Editing Prefab', zh: '正在编辑预制体' },
+ 'proj.prefabModeBack': { en: 'Back to Scene', zh: '返回场景' },
+ 'proj.prefabModeSave': { en: 'Save Prefab', zh: '保存预制体' },
'proj.resaveNone': { en: 'No prefabs to re-save', zh: '没有可重新保存的预制体' },
'proj.resaveDone': { en: 'Re-saved {count} prefab(s) to the current format', zh: '已将 {count} 个预制体重新保存为当前格式' },
'proj.resaveFailed': { en: 'Re-saved {upgraded}, {failed} failed', zh: '已重新保存 {upgraded} 个,{failed} 个失败' },
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 07a9d52a4..7bec58e97 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { createStore } from 'zustand/vanilla';
-import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, setTextureParams, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides } from 'esengine';
+import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, setTextureParams, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides } from 'esengine';
import { readTextureImportSettings } from './assetImporter';
import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig, AudioProjectConfig, AssetsData, ThemeOverrides } from 'esengine';
import { EngineHost } from '@/engine/EngineHost';
@@ -141,6 +141,9 @@ interface ProjectState {
designResolution?: DesignResolution;
/** The scene currently loaded into the world (project-relative path). */
currentScene: string | null;
+ /** When editing a PREFAB asset in place (Prefab Mode) rather than a scene:
+ * the prefab's display name + path, for the banner. `currentScene` is null. */
+ prefabEdit?: { name: string; path: string } | null;
}
/**
@@ -201,6 +204,18 @@ class ProjectStoreImpl {
private readonly uuidToType = new Map<string, string>();
/** ref → loaded `.esprefab` (PrefabData), for scene load-expand / save-collapse. */
private readonly prefabCache = new Map<string, PrefabData>();
+ /** Active Prefab Mode session, or null. Holds the id-preservation map
+ * (source id → prefabEntityId) so save-back keeps each entity's identity, plus
+ * the scene to return to on exit. The reactive `prefabEdit` in ProjectState is
+ * the lightweight UI mirror. */
+ private prefabSession: {
+ ref: string;
+ path: string;
+ name: string;
+ rootSource: number;
+ idBySource: Map<number, string>;
+ returnScene: string | null;
+ } | null = null;
/** Cold refs already handed to a live load this registry generation — the touch
* listener fires on every projection of a still-cold ref, so without this a
* failing asset would re-fetch forever (and a slow one would double-load). */
@@ -481,7 +496,9 @@ class ProjectStoreImpl {
// Edit-world live theme: re-resolve ThemeStyle-tagged widgets against the
// project's effective theme, matching what a shipped runtime boots with.
applyWidgetTheme(this.uiTheme(), this.uiThemeOverrides());
- this.store.setState({ project: { ...st, currentScene: rel } });
+ // Loading a scene always leaves Prefab Mode (if it was active).
+ this.prefabSession = null;
+ this.store.setState({ project: { ...st, currentScene: rel, prefabEdit: null } });
this.knownSceneText = text;
this.knownScenePath = rel;
}
@@ -526,7 +543,8 @@ class ProjectStoreImpl {
installSpineSync(this.spineTransport());
Reconciler.adopt(blank, blank); // no @uuid: refs → resolved === raw
EngineHost.syncEditorViewToScene();
- this.store.setState({ project: { ...st, currentScene: null } });
+ this.prefabSession = null;
+ this.store.setState({ project: { ...st, currentScene: null, prefabEdit: null } });
}
/**
@@ -1767,6 +1785,117 @@ class ProjectStoreImpl {
Toasts.push(t('proj.openedScene', { name: relPath.split('/').pop() ?? relPath }), 'info', 1600);
}
+ /**
+ * Open a `.esprefab` in PREFAB MODE — edit the prefab's own entity tree in the
+ * same outliner / inspector / viewport used for scenes. The asset is flattened
+ * into ordinary entities (each remembered by its prefabEntityId so save-back
+ * preserves identity), the current scene is swapped out, and a banner offers
+ * "Back to Scene". Only FLAT prefabs for now — a nested/variant prefab would
+ * un-nest on save, so those are refused. The caller guards unsaved changes.
+ */
+ async openPrefab(path: string): Promise<void> {
+ const st = this.state;
+ if (!st) return;
+ const leaf = path.split('/').pop() ?? path;
+ if (!(await confirmDiscard(t('discard.openPrefab', { name: leaf })))) return;
+ const uuid = this.pathToUuid.get(path);
+ const ref = uuid ? UUID_PREFIX + uuid : null;
+ const prefab = ref ? await this.loadPrefabAsset(ref) : null;
+ if (!ref || !prefab) {
+ Toasts.push(t('proj.prefabLoadFailed', { name: leaf }), 'error');
+ return;
+ }
+ if (prefab.basePrefab || prefab.entities.some((e) => e.nestedPrefab)) {
+ Toasts.push(t('proj.prefabModeNested'), 'warn');
+ return;
+ }
+
+ // Flatten the asset into ordinary entities; remember each entity's stable id.
+ let nid = 0;
+ const { entities, rootId } = flattenPrefab(prefab, [], { allocateId: () => nid++, loadPrefab: () => null });
+ const idBySource = new Map(entities.map((e) => [e.id, e.prefabEntityId]));
+ const sceneData = {
+ version: '1.0',
+ name: prefab.name,
+ entities: entities.map((e) => ({
+ id: e.id, name: e.name, parent: e.parent, children: e.children,
+ components: e.components, visible: e.visible,
+ })),
+ } as unknown as SceneData;
+
+ await this.adoptDocument(sceneData);
+ this.prefabSession = { ref, path, name: prefab.name, rootSource: rootId, idBySource, returnScene: st.currentScene };
+ this.store.setState({ project: { ...st, currentScene: null, prefabEdit: { name: prefab.name, path } } });
+ Toasts.push(t('proj.openedPrefab', { name: prefab.name }), 'info', 1600);
+ }
+
+ /**
+ * Adopt an in-memory SceneData into the editor (preload assets → build the World
+ * → adopt as the model), mirroring {@link loadCurrentScene}'s tail. No file read
+ * or prefab-tag handling — the caller owns those. Used by Prefab Mode.
+ */
+ private async adoptDocument(raw: SceneData): Promise<void> {
+ const assets = EngineHost.getResource(Assets);
+ let resolved: SceneData = raw;
+ if (assets) {
+ const result = await assets.preloadSceneAssets(raw);
+ resolved = JSON.parse(JSON.stringify(raw)) as SceneData;
+ assets.resolveSceneAssetPaths(resolved, result);
+ this.lastAssetResult = result;
+ }
+ EditorHistory.clearScene();
+ useSelection.getState().select(null);
+ Reconciler.setAssetResolver((ref) => this.handleForRef(ref));
+ Reconciler.setRefPathResolver((ref) => this.resolveRef(ref));
+ Reconciler.setAssetTouchListener((ref, slot) => this.hotLoadAsset(ref, slot));
+ installSpineSync(this.spineTransport());
+ Reconciler.adopt(raw, resolved);
+ EngineHost.syncEditorViewToScene();
+ applyWidgetTheme(this.uiTheme(), this.uiThemeOverrides());
+ }
+
+ /**
+ * Save the prefab being edited in Prefab Mode back to its `.esprefab`, PRESERVING
+ * each entity's prefabEntityId (so existing instances' overrides still resolve)
+ * and minting uuids only for entities added during the session.
+ */
+ async savePrefab(): Promise<void> {
+ const pe = this.prefabSession;
+ if (!pe) return;
+ const model = SceneModel.serialize();
+ if (!model) return;
+ const idBySource = new Map(pe.idBySource);
+ for (const e of model.entities) if (!idBySource.has(e.id)) idBySource.set(e.id, crypto.randomUUID());
+ const prefab = extractPrefab(
+ model.entities as unknown as ExtractEntity[],
+ pe.rootSource,
+ pe.name,
+ (srcId) => idBySource.get(srcId) ?? crypto.randomUUID(),
+ );
+ try {
+ await window.estella.fs.write(pe.path, JSON.stringify(prefab, null, 2) + '\n');
+ } catch {
+ Toasts.push(t('proj.applyWriteFailed', { name: pe.path.split('/').pop() ?? pe.path }), 'error');
+ return;
+ }
+ this.prefabCache.set(pe.ref, prefab);
+ this.prefabSession = { ...pe, idBySource };
+ EditorHistory.markSaved();
+ Toasts.push(t('proj.savedPrefab', { name: pe.name }), 'success');
+ }
+
+ /** Leave Prefab Mode and return to the scene that was open (or a blank one). */
+ async exitPrefabMode(): Promise<void> {
+ if (!this.prefabSession) return;
+ if (!(await confirmDiscard(t('discard.exitPrefab')))) return;
+ const back = this.prefabSession.returnScene;
+ this.prefabSession = null;
+ const st = this.state;
+ if (st) this.store.setState({ project: { ...st, prefabEdit: null } });
+ if (back) await this.openScene(back);
+ else await this.newScene();
+ }
+
/** True if the changed paths include the open scene document. */
isOpenScenePath(paths: readonly string[]): boolean {
const cur = this.state?.currentScene;
@@ -1819,6 +1948,7 @@ class ProjectStoreImpl {
* editor's engine never loaded. The old lossy overwrite-block is gone.
*/
async save(): Promise<void> {
+ if (this.prefabSession) { await this.savePrefab(); return; }
const st = this.state;
if (!st || !st.currentScene) throw new Error('no scene to save');
await this.writeScene(st.currentScene, await this.serializeCurrent());
diff --git a/desktop/src/project/assetOpen.ts b/desktop/src/project/assetOpen.ts
index 0869c6e9e..ee37263d7 100644
--- a/desktop/src/project/assetOpen.ts
+++ b/desktop/src/project/assetOpen.ts
@@ -27,6 +27,7 @@ export const ASSET_OPEN: Partial<Record<AssetType, (path: string, name: string)
if (!(await confirmDiscard(t('discard.openScene', { name })))) return;
void ProjectStore.openScene(path);
},
+ prefab: (path) => void ProjectStore.openPrefab(path),
audio: (path) => toggleAudioPreview(path),
animation: (path) => void openAnimationClip(path),
animclip: (path) => void openFlipbook(path),
diff --git a/desktop/src/theme/menus.css b/desktop/src/theme/menus.css
index fccbb074b..0f4b60846 100644
--- a/desktop/src/theme/menus.css
+++ b/desktop/src/theme/menus.css
@@ -160,6 +160,18 @@
.apply-diff .ad-ent { color: var(--text); font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.apply-diff .ad-detail { color: var(--text-dim); font-family: var(--mono); font-size: var(--fs-2xs); margin-left: auto; flex-shrink: 0; }
+/* ── Prefab Mode banner (shell bar while editing a .esprefab in place) ── */
+.prefab-mode-bar {
+ display: flex; align-items: center; gap: 8px;
+ padding: 5px 12px; flex-shrink: 0;
+ background: var(--info-warm-soft); border-bottom: 1px solid var(--info-warm-line);
+ color: var(--text); font-size: var(--fs-sm);
+}
+.prefab-mode-bar .pmb-icon { color: var(--info-warm); display: grid; place-items: center; }
+.prefab-mode-bar .pmb-label { color: var(--text-dim); }
+.prefab-mode-bar .pmb-name { font-weight: 600; color: var(--info-warm); }
+.prefab-mode-bar .pmb-actions { margin-left: auto; display: flex; gap: 6px; }
+
/* ── New Tilemap tileset chooser ── */
.tmpick { display: flex; flex-direction: column; gap: 10px; }
.tmpick__hint { font-size: var(--fs-sm); color: var(--text-mute); }
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 3f93124eb..670cadd9d 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -8447,7 +8447,7 @@ DragPlugin
## extractPrefab — function
```
-(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: () => PrefabEntityId): PrefabData
+(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: (sourceId: number) => PrefabEntityId): PrefabData
```
## facingFromQuat — function
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index d6b04e1ee..608c85f86 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -8442,7 +8442,7 @@ DragPlugin
## extractPrefab — function
```
-(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: () => PrefabEntityId): PrefabData
+(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: (sourceId: number) => PrefabEntityId): PrefabData
```
## facingFromQuat — function
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 103210f3c..07f81c4a6 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -8466,7 +8466,7 @@ DragPlugin
## extractPrefab — function
```
-(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: () => PrefabEntityId): PrefabData
+(entities: readonly ExtractEntity[], rootId: number, name: string, makeId?: (sourceId: number) => PrefabEntityId): PrefabData
```
## facingFromQuat — function
diff --git a/sdk/src/prefab/sceneInstance.ts b/sdk/src/prefab/sceneInstance.ts
index 5bb32f15a..01722ba4a 100644
--- a/sdk/src/prefab/sceneInstance.ts
+++ b/sdk/src/prefab/sceneInstance.ts
@@ -436,15 +436,16 @@ export function extractPrefab(
entities: readonly ExtractEntity[],
rootId: number,
name: string,
- makeId: () => PrefabEntityId = () => crypto.randomUUID(),
+ makeId: (sourceId: number) => PrefabEntityId = () => crypto.randomUUID(),
): PrefabData {
- // Root first so it reads first in the file. Ids are minted by `makeId`
+ // Root first so it reads first in the file. Ids come from `makeId(sourceId)`
// (UUIDs by default) so a newly authored prefab's entity identities are
- // globally unique — two prefabs, or two instantiations of one, never share
- // a `prefabEntityId` and so never collide when nested (see PREFAB_ADDRESS_SEP).
+ // globally unique. Passing the source id lets a caller PRESERVE existing ids
+ // (Prefab Mode's save-back keeps each entity's prefabEntityId so instances'
+ // overrides survive) while still minting for newly-added entities.
const ordered = [...entities].sort((a, b) => (a.id === rootId ? -1 : b.id === rootId ? 1 : 0));
const idMap = new Map<number, string>();
- ordered.forEach((e) => idMap.set(e.id, makeId()));
+ ordered.forEach((e) => idMap.set(e.id, makeId(e.id)));
const inSubtree = (sid: number | null): boolean => sid != null && idMap.has(sid);
const prefabEntities: PrefabEntityData[] = ordered.map((e) => ({