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: add prefab system with save, instantiate, override tracking and edit mode

esengine79d97ee9ce8d
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index 0a7eb8838..a91ac33d7 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -4,6 +4,7 @@
*/
import type { App, Entity } from 'esengine';
+import type { EntityData } from './types/SceneTypes';
import * as esengine from 'esengine';
import {
Draw, Geometry, Material, BlendMode, DataType, ShaderSources,
@@ -111,6 +112,7 @@ export class Editor {
private shortcutManager_: ShortcutManager;
private activeBottomPanelId_: string | null = 'content-browser';
private assetLibraryReady_: Promise<void> = Promise.resolve();
+ private clipboard_: EntityData[] | null = null;
constructor(container: HTMLElement, options?: EditorOptions) {
this.container_ = container;
@@ -281,6 +283,11 @@ export class Editor {
}
async saveScene(): Promise<void> {
+ if (this.store_.isEditingPrefab) {
+ await this.store_.savePrefabEditing();
+ return;
+ }
+
const filePath = this.store_.filePath;
if (filePath && hasFileHandle()) {
@@ -315,6 +322,10 @@ export class Editor {
}
async openSceneFromPath(scenePath: string): Promise<void> {
+ if (this.store_.isEditingPrefab) {
+ await this.store_.exitPrefabEditMode();
+ }
+
await this.assetLibraryReady_;
const scene = await loadSceneFromPath(scenePath);
if (scene) {
@@ -348,8 +359,73 @@ export class Editor {
);
for (const comp of entityData.components) {
- this.store_.addComponent(newEntity, comp.type, { ...comp.data });
+ this.store_.addComponent(newEntity, comp.type, JSON.parse(JSON.stringify(comp.data)));
+ }
+ }
+
+ copySelected(): void {
+ const entity = this.store_.selectedEntity;
+ if (entity === null) return;
+
+ const tree = this.collectEntityTree_(entity as number);
+ if (tree.length === 0) return;
+
+ this.clipboard_ = JSON.parse(JSON.stringify(tree));
+ for (const e of this.clipboard_!) {
+ delete e.prefab;
+ }
+ }
+
+ pasteEntity(): void {
+ if (!this.clipboard_ || this.clipboard_.length === 0) return;
+
+ const cloned: EntityData[] = JSON.parse(JSON.stringify(this.clipboard_));
+ const parent = this.store_.selectedEntity;
+ const rootData = cloned[0];
+
+ const scene = this.store_.scene;
+ const siblings = scene.entities
+ .filter(e => e.parent === (parent as number | null))
+ .map(e => e.name);
+ const siblingNames = new Set(siblings);
+ const newName = generateUniqueName(rootData.name, siblingNames);
+
+ const oldIdToNewId = new Map<number, Entity>();
+
+ const newRoot = this.store_.createEntity(newName, parent);
+ oldIdToNewId.set(rootData.id, newRoot);
+ for (const comp of rootData.components) {
+ this.store_.addComponent(newRoot, comp.type, { ...comp.data });
+ }
+
+ for (let i = 1; i < cloned.length; i++) {
+ const entityData = cloned[i];
+ const newParent = oldIdToNewId.get(entityData.parent!);
+ if (newParent === undefined) continue;
+
+ const newEntity = this.store_.createEntity(entityData.name, newParent);
+ oldIdToNewId.set(entityData.id, newEntity);
+
+ for (const comp of entityData.components) {
+ this.store_.addComponent(newEntity, comp.type, { ...comp.data });
+ }
+ }
+
+ this.store_.selectEntity(newRoot);
+ }
+
+ hasClipboard(): boolean {
+ return this.clipboard_ !== null && this.clipboard_.length > 0;
+ }
+
+ private collectEntityTree_(entityId: number): EntityData[] {
+ const entity = this.store_.getEntityData(entityId);
+ if (!entity) return [];
+ const result: EntityData[] = [entity];
+ for (const childId of entity.children) {
+ result.push(...this.collectEntityTree_(childId));
}
+ return result;
}
showBuildSettings(): void {
diff --git a/editor/src/commands/PrefabCommands.ts b/editor/src/commands/PrefabCommands.ts
new file mode 100644
index 000000000..76a0bbecc
--- /dev/null
+++ b/editor/src/commands/PrefabCommands.ts
@@ -0,0 +1,335 @@
+/**
+ * @file PrefabCommands.ts
+ * @brief Prefab-related undo/redo commands
+ */
+
+import type { SceneData, EntityData } from '../types/SceneTypes';
+import type { PrefabData, PrefabOverride } from '../types/PrefabTypes';
+import { BaseCommand } from './Command';
+import { instantiatePrefab, computeNextEntityId } from '../prefab/PrefabInstantiator';
+
+// =============================================================================
+// InstantiatePrefabCommand
+// =============================================================================
+
+export class InstantiatePrefabCommand extends BaseCommand {
+ readonly type = 'instantiate_prefab';
+ readonly description: string;
+ private createdEntityIds_: number[] = [];
+ private nextEntityIdBefore_: number;
+
+ constructor(
+ private scene_: SceneData,
+ private prefab_: PrefabData,
+ private prefabPath_: string,
+ private parentEntityId_: number | null,
+ private nextEntityId_: number
+ ) {
+ super();
+ this.description = `Instantiate prefab "${prefab_.name}"`;
+ this.nextEntityIdBefore_ = nextEntityId_;
+ }
+
+ execute(): void {
+ const result = instantiatePrefab(
+ this.prefab_,
+ this.prefabPath_,
+ this.scene_,
+ this.parentEntityId_,
+ this.nextEntityId_
+ );
+
+ for (const entity of result.createdEntities) {
+ this.scene_.entities.push(entity);
+ }
+
+ if (this.parentEntityId_ !== null) {
+ const parent = this.scene_.entities.find(e => e.id === this.parentEntityId_);
+ if (parent && !parent.children.includes(result.rootEntityId)) {
+ parent.children.push(result.rootEntityId);
+ }
+ }
+
+ this.createdEntityIds_ = result.createdEntities.map(e => e.id);
+ }
+
+ undo(): void {
+ const idsToRemove = new Set(this.createdEntityIds_);
+
+ if (this.parentEntityId_ !== null) {
+ const parent = this.scene_.entities.find(e => e.id === this.parentEntityId_);
+ if (parent) {
+ parent.children = parent.children.filter(id => !idsToRemove.has(id));
+ }
+ }
+
+ this.scene_.entities = this.scene_.entities.filter(e => !idsToRemove.has(e.id));
+ }
+
+ get rootEntityId(): number {
+ return this.createdEntityIds_[0] ?? -1;
+ }
+
+ get createdEntityIds(): number[] {
+ return this.createdEntityIds_;
+ }
+}
+
+// =============================================================================
+// UnpackPrefabCommand
+// =============================================================================
+
+export class UnpackPrefabCommand extends BaseCommand {
+ readonly type = 'unpack_prefab';
+ readonly description: string;
+ private savedPrefabData_: Map<number, EntityData['prefab']> = new Map();
+
+ constructor(
+ private scene_: SceneData,
+ private instanceId_: string
+ ) {
+ super();
+ this.description = 'Unpack prefab';
+ }
+
+ execute(): void {
+ this.savedPrefabData_.clear();
+ for (const entity of this.scene_.entities) {
+ if (entity.prefab?.instanceId === this.instanceId_) {
+ this.savedPrefabData_.set(entity.id, { ...entity.prefab });
+ delete entity.prefab;
+ }
+ }
+ }
+
+ undo(): void {
+ for (const [entityId, prefabData] of this.savedPrefabData_) {
+ const entity = this.scene_.entities.find(e => e.id === entityId);
+ if (entity) {
+ entity.prefab = prefabData;
+ }
+ }
+ }
+}
+
+// =============================================================================
+// RevertPrefabInstanceCommand
+// =============================================================================
+
+export class RevertPrefabInstanceCommand extends BaseCommand {
+ readonly type = 'revert_prefab';
+ readonly description: string;
+ private savedEntities_: Map<number, EntityData> = new Map();
+
+ constructor(
+ private scene_: SceneData,
+ private instanceId_: string,
+ private prefab_: PrefabData,
+ private prefabPath_: string
+ ) {
+ super();
+ this.description = `Revert prefab "${prefab_.name}"`;
+ }
+
+ execute(): void {
+ this.savedEntities_.clear();
+
+ const instanceEntities = this.scene_.entities.filter(
+ e => e.prefab?.instanceId === this.instanceId_
+ );
+ if (instanceEntities.length === 0) return;
+
+ for (const entity of instanceEntities) {
+ this.savedEntities_.set(entity.id, {
+ ...entity,
+ components: entity.components.map(c => ({ type: c.type, data: { ...c.data } })),
+ prefab: entity.prefab ? { ...entity.prefab, overrides: [...entity.prefab.overrides] } : undefined,
+ });
+ }
+
+ const rootEntity = instanceEntities.find(e => e.prefab?.isRoot);
+ if (!rootEntity) return;
+
+ const idMapping = new Map<number, number>();
+ for (const entity of instanceEntities) {
+ if (entity.prefab) {
+ idMapping.set(entity.prefab.prefabEntityId, entity.id);
+ }
+ }
+
+ for (const pe of this.prefab_.entities) {
+ const sceneId = idMapping.get(pe.prefabEntityId);
+ if (sceneId === undefined) continue;
+
+ const entity = this.scene_.entities.find(e => e.id === sceneId);
+ if (!entity) continue;
+
+ entity.name = pe.name;
+ entity.visible = pe.visible;
+ entity.components = pe.components.map(c => ({
+ type: c.type,
+ data: JSON.parse(JSON.stringify(c.data)),
+ }));
+
+ if (entity.prefab) {
+ entity.prefab.overrides = [];
+ }
+ }
+ }
+
+ undo(): void {
+ for (const [entityId, saved] of this.savedEntities_) {
+ const entity = this.scene_.entities.find(e => e.id === entityId);
+ if (!entity) continue;
+
+ entity.name = saved.name;
+ entity.visible = saved.visible;
+ entity.components = saved.components;
+ if (saved.prefab) {
+ entity.prefab = saved.prefab;
+ }
+ }
+ }
+}
+
+// =============================================================================
+// ApplyPrefabOverridesCommand
+// =============================================================================
+
+export class ApplyPrefabOverridesCommand extends BaseCommand {
+ readonly type = 'apply_prefab';
+ readonly description: string;
+ private savedPrefab_: PrefabData | null = null;
+ private savedOtherInstances_: Map<number, EntityData>[] = [];
+
+ constructor(
+ private scene_: SceneData,
+ private instanceId_: string,
+ private prefab_: PrefabData,
+ private prefabPath_: string,
+ private onSave_: (prefab: PrefabData, path: string) => Promise<void>
+ ) {
+ super();
+ this.description = `Apply to prefab "${prefab_.name}"`;
+ }
+
+ execute(): void {
+ this.savedPrefab_ = JSON.parse(JSON.stringify(this.prefab_));
+
+ const instanceEntities = this.scene_.entities.filter(
+ e => e.prefab?.instanceId === this.instanceId_
+ );
+
+ for (const entity of instanceEntities) {
+ if (!entity.prefab) continue;
+ const pe = this.prefab_.entities.find(
+ pe => pe.prefabEntityId === entity.prefab!.prefabEntityId
+ );
+ if (!pe) continue;
+
+ pe.name = entity.name;
+ pe.visible = entity.visible;
+ pe.components = entity.components.map(c => ({
+ type: c.type,
+ data: JSON.parse(JSON.stringify(c.data)),
+ }));
+ }
+
+ const rootEntity = instanceEntities.find(e => e.prefab?.isRoot);
+ if (rootEntity?.prefab) {
+ rootEntity.prefab.overrides = [];
+ }
+
+ this.updateOtherInstances(instanceEntities);
+
+ this.onSave_(this.prefab_, this.prefabPath_);
+ }
+
+ undo(): void {
+ if (this.savedPrefab_) {
+ this.prefab_.entities = this.savedPrefab_.entities;
+ }
+
+ for (const savedMap of this.savedOtherInstances_) {
+ for (const [entityId, saved] of savedMap) {
+ const entity = this.scene_.entities.find(e => e.id === entityId);
+ if (!entity) continue;
+ entity.name = saved.name;
+ entity.visible = saved.visible;
+ entity.components = saved.components;
+ }
+ }
+ }
+
+ private updateOtherInstances(sourceEntities: EntityData[]): void {
+ const otherInstanceIds = new Set<string>();
+ for (const entity of this.scene_.entities) {
+ if (entity.prefab?.prefabPath === this.prefabPath_ &&
+ entity.prefab.instanceId !== this.instanceId_ &&
+ entity.prefab.isRoot) {
+ otherInstanceIds.add(entity.prefab.instanceId);
+ }
+ }
+
+ for (const otherId of otherInstanceIds) {
+ const savedMap = new Map<number, EntityData>();
+ const otherEntities = this.scene_.entities.filter(
+ e => e.prefab?.instanceId === otherId
+ );
+
+ for (const entity of otherEntities) {
+ savedMap.set(entity.id, {
+ ...entity,
+ components: entity.components.map(c => ({ type: c.type, data: { ...c.data } })),
+ });
+ }
+ this.savedOtherInstances_.push(savedMap);
+
+ const otherRoot = otherEntities.find(e => e.prefab?.isRoot);
+ const otherOverrides = otherRoot?.prefab?.overrides ?? [];
+
+ for (const entity of otherEntities) {
+ if (!entity.prefab) continue;
+ const pe = this.prefab_.entities.find(
+ pe => pe.prefabEntityId === entity.prefab!.prefabEntityId
+ );
+ if (!pe) continue;
+
+ entity.name = pe.name;
+ entity.visible = pe.visible;
+ entity.components = pe.components.map(c => ({
+ type: c.type,
+ data: JSON.parse(JSON.stringify(c.data)),
+ }));
+
+ for (const override of otherOverrides) {
+ if (override.prefabEntityId !== entity.prefab.prefabEntityId) continue;
+ this.applyOverrideToEntity(entity, override);
+ }
+ }
+ }
+ }
+
+ private applyOverrideToEntity(entity: EntityData, override: PrefabOverride): void {
+ switch (override.type) {
+ case 'property':
+ if (override.componentType && override.propertyName !== undefined) {
+ const comp = entity.components.find(c => c.type === override.componentType);
+ if (comp) {
+ comp.data[override.propertyName!] = override.value;
+ }
+ }
+ break;
+ case 'name':
+ if (typeof override.value === 'string') {
+ entity.name = override.value;
+ }
+ break;
+ case 'visibility':
+ if (typeof override.value === 'boolean') {
+ entity.visible = override.value;
+ }
+ break;
+ }
+ }
+}
diff --git a/editor/src/commands/index.ts b/editor/src/commands/index.ts
index ed049c318..becbd6a86 100644
--- a/editor/src/commands/index.ts
+++ b/editor/src/commands/index.ts
@@ -13,5 +13,11 @@ export {
AddComponentCommand,
RemoveComponentCommand,
} from './EntityCommands';
+export {
+ InstantiatePrefabCommand,
+ UnpackPrefabCommand,
+ RevertPrefabInstanceCommand,
+ ApplyPrefabOverridesCommand,
+} from './PrefabCommands';
export { CompoundCommand } from './CompoundCommand';
export { CommandHistory } from './CommandHistory';
diff --git a/editor/src/io/SceneSerializer.ts b/editor/src/io/SceneSerializer.ts
index e3b2d993e..63334f0ee 100644
--- a/editor/src/io/SceneSerializer.ts
+++ b/editor/src/io/SceneSerializer.ts
@@ -66,6 +66,25 @@ export class SceneSerializer {
for (const component of entity.components) {
this.validateComponent(component);
}
+
+ if (entity.prefab) {
+ this.validatePrefabInstance(entity.prefab);
+ }
+ }
+
+ private validatePrefabInstance(prefab: import('../types/PrefabTypes').PrefabInstanceData): void {
+ if (!prefab.prefabPath || typeof prefab.prefabPath !== 'string') {
+ throw new Error('PrefabInstanceData must have prefabPath');
+ }
+ if (typeof prefab.prefabEntityId !== 'number') {
+ throw new Error('PrefabInstanceData must have numeric prefabEntityId');
+ }
+ if (!prefab.instanceId) {
+ prefab.instanceId = `prefab_migrated_${Date.now()}`;
+ }
+ if (!Array.isArray(prefab.overrides)) {
+ prefab.overrides = [];
+ }
}
private validateComponent(component: ComponentData): void {
diff --git a/editor/src/panels/ContentBrowserPanel.ts b/editor/src/panels/ContentBrowserPanel.ts
index 6882a7459..1f46c97ad 100644
--- a/editor/src/panels/ContentBrowserPanel.ts
+++ b/editor/src/panels/ContentBrowserPanel.ts
@@ -13,7 +13,10 @@ import { getEditorContext } from '../context/EditorContext';
import { joinPath, getParentDir } from '../utils/path';
import type { NativeFS, DirectoryEntry } from '../types/NativeFS';
import { getAssetLibrary } from '../asset/AssetLibrary';
+import { getGlobalPathResolver } from '../asset';
import { showErrorToast } from '../ui/Toast';
+import { createEmptyScene } from '../types/SceneTypes';
+import { getSettingsValue } from '../settings';
// =============================================================================
// Types
@@ -35,7 +38,7 @@ interface FolderNode {
interface AssetItem {
name: string;
path: string;
- type: 'folder' | 'scene' | 'script' | 'image' | 'audio' | 'json' | 'material' | 'shader' | 'spine' | 'font' | 'file';
+ type: 'folder' | 'scene' | 'script' | 'image' | 'audio' | 'json' | 'material' | 'shader' | 'spine' | 'font' | 'prefab' | 'file';
}
export interface ContentBrowserOptions {
@@ -65,6 +68,8 @@ function getAssetType(entry: DirectoryEntry): AssetItem['type'] {
const ext = getFileExtension(entry.name);
switch (ext) {
+ case '.esprefab':
+ return 'prefab';
case '.esscene':
return 'scene';
case '.ts':
@@ -102,6 +107,8 @@ function getAssetIcon(type: AssetItem['type'], size: number = 32): string {
switch (type) {
case 'folder':
return icons.folder(size);
+ case 'prefab':
+ return icons.package(size);
case 'scene':
return icons.layers(size);
case 'script':
@@ -478,6 +485,33 @@ export class ContentBrowserPanel {
const item = target.closest('.es-asset-item') as HTMLElement;
item?.classList.remove('es-dragging');
});
+
+ this.gridContainer_?.addEventListener('dragover', (e) => {
+ const types = e.dataTransfer?.types ?? [];
+ if (!Array.from(types).includes('application/esengine-entity')) return;
+ e.preventDefault();
+ e.dataTransfer!.dropEffect = 'copy';
+ this.gridContainer_?.classList.add('es-drag-over');
+ });
+
+ this.gridContainer_?.addEventListener('dragleave', (e) => {
+ const related = e.relatedTarget as HTMLElement;
+ if (this.gridContainer_?.contains(related)) return;
+ this.gridContainer_?.classList.remove('es-drag-over');
+ });
+
+ this.gridContainer_?.addEventListener('drop', (e) => {
+ this.gridContainer_?.classList.remove('es-drag-over');
+
+ const entityIdStr = e.dataTransfer?.getData('application/esengine-entity');
+ if (!entityIdStr) return;
+
+ e.preventDefault();
+ const entityId = parseInt(entityIdStr, 10);
+ if (isNaN(entityId)) return;
+
+ this.saveDroppedEntityAsPrefab(entityId);
+ });
}
private showAssetContextMenu(e: MouseEvent, path: string, type: AssetItem['type']): void {
@@ -763,11 +797,10 @@ export const ${className} = defineComponent('${className}', {
const platform = getPlatformAdapter();
const filePath = `${parentPath}/${name}`;
- const content = JSON.stringify({
- version: '1.0',
- name: name.replace('.esscene', ''),
- entities: [],
- }, null, 2);
+ const w = getSettingsValue<number>('project.designWidth') || 1920;
+ const h = getSettingsValue<number>('project.designHeight') || 1080;
+ const scene = createEmptyScene(name.replace('.esscene', ''), { width: w, height: h });
+ const content = JSON.stringify(scene, null, 2);
try {
await platform.writeTextFile(filePath, content);
@@ -919,6 +952,13 @@ void main() {
return;
}
+ if (type === 'prefab') {
+ const resolver = getGlobalPathResolver();
+ const relativePath = resolver.toRelativePath(path);
+ this.store_.enterPrefabEditMode(relativePath);
+ return;
+ }
+
const shell = getNativeShell();
if (!shell) return;
@@ -1112,4 +1152,49 @@ void main() {
type: 'folder' as const,
}));
}
+
+ private async saveDroppedEntityAsPrefab(entityId: number): Promise<void> {
+ const entityData = this.store_.getEntityData(entityId);
+ if (!entityData) return;
+
+ const targetDir = this.currentPath_;
+ if (!targetDir) return;
+
+ const platform = getPlatformAdapter();
+
+ const name = await showInputDialog({
+ title: 'Save as Prefab',
+ placeholder: 'Prefab name',
+ defaultValue: entityData.name,
+ confirmText: 'Save',
+ validator: async (value) => {
+ if (!value.trim()) return 'Name is required';
+ if (/[<>:"/\\|?*\x00-\x1f]/.test(value.trim())) {
+ return 'Name contains invalid characters';
+ }
+ const fileName = value.trim().endsWith('.esprefab')
+ ? value.trim()
+ : `${value.trim()}.esprefab`;
+ const fullPath = joinPath(targetDir, fileName);
+ if (await platform.exists(fullPath)) {
+ return 'A file with this name already exists';
+ }
+ return null;
+ },
+ });
+
+ if (!name) return;
+
+ const fileName = name.trim().endsWith('.esprefab')
+ ? name.trim()
+ : `${name.trim()}.esprefab`;
+ const filePath = joinPath(targetDir, fileName);
+
+ const success = await this.store_.saveAsPrefab(entityId, filePath);
+ if (success) {
+ this.refresh();
+ } else {
+ showErrorToast('Failed to save prefab', filePath);
+ }
+ }
}
diff --git a/editor/src/panels/HierarchyPanel.ts b/editor/src/panels/HierarchyPanel.ts
index 31e848ef7..de4755766 100644
--- a/editor/src/panels/HierarchyPanel.ts
+++ b/editor/src/panels/HierarchyPanel.ts
@@ -11,9 +11,11 @@ import { getGlobalPathResolver } from '../asset';
import { getDefaultComponentData } from '../schemas/ComponentSchemas';
import { showContextMenu, type ContextMenuItem } from '../ui/ContextMenu';
import { getContextMenuItems, type ContextMenuContext } from '../ui/ContextMenuRegistry';
-import { getEditorContext } from '../context/EditorContext';
+import { getEditorContext, getEditorInstance } from '../context/EditorContext';
import { getPlatformAdapter } from '../platform/PlatformAdapter';
import { generateUniqueName } from '../utils/naming';
+import { showInputDialog } from '../ui/dialog';
+import { joinPath, getParentDir } from '../utils/path';
type DropPosition = 'before' | 'after' | 'inside';
@@ -27,6 +29,7 @@ export class HierarchyPanel {
private treeContainer_: HTMLElement;
private searchInput_: HTMLInputElement | null = null;
private footerContainer_: HTMLElement | null = null;
+ private prefabEditBar_: HTMLElement | null = null;
private unsubscribe_: (() => void) | null = null;
private searchFilter_: string = '';
private expandedIds_: Set<number> = new Set();
@@ -45,6 +48,10 @@ export class HierarchyPanel {
<button class="es-btn es-btn-icon" title="Close">${icons.x(12)}</button>
</div>
</div>
+ <div class="es-prefab-edit-bar" style="display: none;">
+ <button class="es-prefab-back-btn">${icons.chevronRight(12)} Back to Scene</button>
+ <span class="es-prefab-edit-name">${icons.package(12)} </span>
+ </div>
<div class="es-hierarchy-toolbar">
<input type="text" class="es-input es-hierarchy-search" placeholder="Search...">
<button class="es-btn es-btn-icon" data-action="add" title="Create Entity">${icons.plus()}</button>
@@ -64,6 +71,12 @@ export class HierarchyPanel {
this.treeContainer_ = this.container_.querySelector('.es-hierarchy-tree')!;
this.searchInput_ = this.container_.querySelector('.es-hierarchy-search');
this.footerContainer_ = this.container_.querySelector('.es-hierarchy-footer');
+ this.prefabEditBar_ = this.container_.querySelector('.es-prefab-edit-bar');
+
+ const backBtn = this.container_.querySelector('.es-prefab-back-btn');
+ backBtn?.addEventListener('click', () => {
+ this.store_.exitPrefabEditMode();
+ });
this.setupEvents();
this.unsubscribe_ = store.subscribe(() => this.render());
@@ -327,6 +340,11 @@ export class HierarchyPanel {
asset: { type: string; path: string; name: string },
parent: Entity | null
): Promise<void> {
+ if (asset.type === 'prefab') {
+ await this.createEntityFromPrefab(asset.path, parent);
+ return;
+ }
+
const baseName = asset.name.replace(/\.[^.]+$/, '');
if (asset.type === 'spine' || asset.type === 'json') {
@@ -435,6 +453,20 @@ export class HierarchyPanel {
const scene = this.store_.scene;
const selectedEntity = this.store_.selectedEntity;
+ if (this.prefabEditBar_) {
+ if (this.store_.isEditingPrefab) {
+ this.prefabEditBar_.style.display = '';
+ const nameEl = this.prefabEditBar_.querySelector('.es-prefab-edit-name');
+ if (nameEl) {
+ const path = this.store_.prefabEditingPath ?? '';
+ const fileName = path.split('/').pop() ?? path;
+ nameEl.innerHTML = `${icons.package(12)} ${this.escapeHtml(fileName)}`;
+ }
+ } else {
+ this.prefabEditBar_.style.display = 'none';
+ }
+ }
+
if (selectedEntity !== null && selectedEntity !== this.lastSelectedEntity_) {
this.expandAncestors(selectedEntity, scene);
}
@@ -476,15 +508,18 @@ export class HierarchyPanel {
}
private getEntityIcon(entity: EntityData): string {
+ if (entity.prefab?.isRoot) return icons.package(12);
+
const hasCamera = entity.components.some(c => c.type === 'Camera');
const hasSprite = entity.components.some(c => c.type === 'Sprite');
const hasText = entity.components.some(c => c.type === 'Text');
const hasBitmapText = entity.components.some(c => c.type === 'BitmapText');
+ const hasTextInput = entity.components.some(c => c.type === 'TextInput');
const hasSpine = entity.components.some(c => c.type === 'SpineAnimation');
if (hasCamera) return icons.camera(12);
if (hasSpine) return icons.bone(12);
- if (hasText || hasBitmapText) return icons.type(12);
+ if (hasText || hasBitmapText || hasTextInput) return icons.type(12);
if (hasSprite) return icons.image(12);
return icons.box(12);
}
@@ -518,9 +553,10 @@ export class HierarchyPanel {
const isVisible = this.store_.isEntityVisible(entity.id);
const visibilityIcon = isVisible ? icons.eye(10) : icons.eyeOff(10);
const hiddenClass = isVisible ? '' : ' es-entity-hidden';
+ const prefabClass = entity.prefab?.isRoot ? ' es-prefab-root' : (entity.prefab ? ' es-prefab-child' : '');
return `
- <div class="es-hierarchy-item ${isSelected ? 'es-selected' : ''}${hiddenClass} ${hasChildren ? 'es-has-children' : ''} ${isExpanded ? 'es-expanded' : ''}"
+ <div class="es-hierarchy-item ${isSelected ? 'es-selected' : ''}${hiddenClass}${prefabClass} ${hasChildren ? 'es-has-children' : ''} ${isExpanded ? 'es-expanded' : ''}"
data-entity-id="${entity.id}" style="--depth: ${depth}">
<div class="es-hierarchy-row" draggable="true" style="padding-left: ${8 + depth * 16}px">
${hasChildren ? `<span class="es-hierarchy-expand">${expandIcon}</span>` : '<span class="es-hierarchy-spacer"></span>'}
@@ -550,6 +586,7 @@ export class HierarchyPanel {
}
uiChildren.push(
{ label: 'New Button', onClick: () => this.createButtonEntity(entity) },
+ { label: 'New TextInput', onClick: () => this.createTextInputEntity(entity) },
{ label: 'New Panel', onClick: () => this.createPanelEntity(entity) },
{ label: 'New ScreenSpace Root', onClick: () => this.createScreenSpaceRootEntity(entity) },
);
@@ -587,10 +624,44 @@ export class HierarchyPanel {
];
if (entity !== null) {
+ const editor = getEditorInstance();
items.push(
{ label: 'Duplicate', icon: icons.copy(14), onClick: () => this.duplicateEntity(entity) },
+ { label: 'Copy', icon: icons.copy(14), onClick: () => { this.store_.selectEntity(entity); editor?.copySelected(); } },
+ { label: 'Paste', icon: icons.template(14), disabled: !editor?.hasClipboard(), onClick: () => { this.store_.selectEntity(entity); editor?.pasteEntity(); } },
{ label: 'Delete', icon: icons.trash(14), onClick: () => this.store_.deleteEntity(entity) }
);
+
+ items.push({ label: '', separator: true });
+ items.push({
+ label: 'Save as Prefab...',
+ icon: icons.package(14),
+ onClick: () => this.saveEntityAsPrefab(entity),
+ });
+
+ if (this.store_.isPrefabRoot(entity as number)) {
+ const instanceId = this.store_.getPrefabInstanceId(entity as number);
+ const prefabPath = this.store_.getPrefabPath(entity as number);
+ if (instanceId && prefabPath) {
+ items.push(
+ {
+ label: 'Revert Prefab',
+ icon: icons.rotateCw(14),
+ onClick: () => this.store_.revertPrefabInstance(instanceId, prefabPath),
+ },
+ {
+ label: 'Apply to Prefab',
+ icon: icons.check(14),
+ onClick: () => this.store_.applyPrefabOverrides(instanceId, prefabPath),
+ },
+ {
+ label: 'Unpack Prefab',
+ icon: icons.package(14),
+ onClick: () => this.store_.unpackPrefab(instanceId),
+ },
+ );
+ }
+ }
}
const location = entity !== null ? 'hierarchy.entity' : 'hierarchy.background';
@@ -635,6 +706,18 @@ export class HierarchyPanel {
this.store_.addComponent(newEntity, 'Button', getDefaultComponentData('Button'));
}
+ private createTextInputEntity(parent: Entity | null): void {
+ const newEntity = this.store_.createEntity('TextInput', parent);
+ this.store_.addComponent(newEntity, 'LocalTransform', getDefaultComponentData('LocalTransform'));
+ this.store_.addComponent(newEntity, 'Sprite', getDefaultComponentData('Sprite'));
+ this.store_.addComponent(newEntity, 'UIRect', {
+ ...getDefaultComponentData('UIRect'),
+ size: { x: 200, y: 36 },
+ });
+ this.store_.addComponent(newEntity, 'Interactable', getDefaultComponentData('Interactable'));
+ this.store_.addComponent(newEntity, 'TextInput', getDefaultComponentData('TextInput'));
+ }
+
private createPanelEntity(parent: Entity | null): void {
const newEntity = this.store_.createEntity('Panel', parent);
this.store_.addComponent(newEntity, 'LocalTransform', getDefaultComponentData('LocalTransform'));
@@ -671,10 +754,55 @@ export class HierarchyPanel {
);
for (const comp of entityData.components) {
- this.store_.addComponent(newEntity, comp.type, { ...comp.data });
+ this.store_.addComponent(newEntity, comp.type, JSON.parse(JSON.stringify(comp.data)));
}
}
+ private async saveEntityAsPrefab(entity: Entity): Promise<void> {
+ const entityData = this.store_.getEntityData(entity as number);
+ if (!entityData) return;
+
+ const projectPath = getEditorInstance()?.projectPath;
+ if (!projectPath) return;
+
+ const projectDir = getParentDir(projectPath);
+ const assetsDir = joinPath(projectDir, 'assets');
+
+ const name = await showInputDialog({
+ title: 'Save as Prefab',
+ placeholder: 'Prefab name',
+ defaultValue: entityData.name,
+ confirmText: 'Save',
+ validator: async (value) => {
+ if (!value.trim()) return 'Name is required';
+ if (/[<>:"/\\|?*\x00-\x1f]/.test(value.trim())) {
+ return 'Name contains invalid characters';
+ }
+ return null;
+ },
+ });
+
+ if (!name) return;
+
+ const fileName = name.trim().endsWith('.esprefab')
+ ? name.trim()
+ : `${name.trim()}.esprefab`;
+ const filePath = joinPath(assetsDir, fileName);
+
+ const success = await this.store_.saveAsPrefab(entity as number, filePath);
+ if (!success) {
+ console.error('[HierarchyPanel] Failed to save prefab:', filePath);
+ }
+ }
+
+ private async createEntityFromPrefab(
+ prefabPath: string,
+ parent: Entity | null
+ ): Promise<void> {
+ const relativePath = this.toRelativePath(prefabPath);
+ await this.store_.instantiatePrefab(relativePath, parent);
+ }
+
private escapeHtml(text: string): string {
const div = document.createElement('div');
div.textContent = text;
diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.ts
index 1cd6d0052..875a683fe 100644
--- a/editor/src/panels/InspectorPanel.ts
+++ b/editor/src/panels/InspectorPanel.ts
@@ -33,6 +33,7 @@ export class InspectorPanel {
private currentEntity_: Entity | null = null;
private currentAssetPath_: string | null = null;
private currentComponentCount_: number = 0;
+ private currentPrefabPath_: string | undefined = undefined;
private imageUrlRef_: ImageUrlRef = { current: null };
private footerContainer_: HTMLElement | null = null;
@@ -156,12 +157,14 @@ export class InspectorPanel {
private renderEntityInspector(entity: Entity): void {
const entityData = this.store_.getSelectedEntityData();
const componentCount = entityData?.components.length ?? 0;
+ const prefabPath = entityData?.prefab?.prefabPath;
const entityChanged = entity !== this.currentEntity_;
const componentsChanged = componentCount !== this.currentComponentCount_;
+ const prefabChanged = prefabPath !== this.currentPrefabPath_;
const wasAsset = this.currentAssetPath_ !== null;
- if (!entityChanged && !componentsChanged && !wasAsset) {
+ if (!entityChanged && !componentsChanged && !prefabChanged && !wasAsset) {
this.updateEditors();
this.updateVisibilityIcon();
if (entityData) {
@@ -173,6 +176,7 @@ export class InspectorPanel {
this.currentEntity_ = entity;
this.currentAssetPath_ = null;
this.currentComponentCount_ = componentCount;
+ this.currentPrefabPath_ = prefabPath;
this.disposeEditors();
this.cleanupImageUrl();
this.contentContainer_.innerHTML = '';
diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.ts
index b323c8e0d..4b2f74b6b 100644
--- a/editor/src/panels/SceneViewPanel.ts
+++ b/editor/src/panels/SceneViewPanel.ts
@@ -811,7 +811,11 @@ export class SceneViewPanel {
this.animationId_ = requestAnimationFrame(() => {
this.animationId_ = null;
- this.render();
+ try {
+ this.render();
+ } catch (e) {
+ console.warn('[SceneViewPanel] Render error, skipping frame:', e);
+ }
if (this.continuousRender_) {
this.requestRender();
}
diff --git a/editor/src/panels/inspector/EntityInspector.ts b/editor/src/panels/inspector/EntityInspector.ts
index e45b2474e..72abde268 100644
--- a/editor/src/panels/inspector/EntityInspector.ts
+++ b/editor/src/panels/inspector/EntityInspector.ts
@@ -14,13 +14,14 @@ import {
} from '../../schemas/ComponentSchemas';
import { icons } from '../../utils/icons';
import { showAddComponentPopup } from '../AddComponentPopup';
-import { getEditorContext } from '../../context/EditorContext';
+import { getEditorContext, getEditorInstance } from '../../context/EditorContext';
import {
type EditorInfo,
escapeHtml,
getComponentIcon,
getProjectDir,
} from './InspectorHelpers';
+import { isPropertyOverridden } from '../../prefab';
import {
getComponentInspector,
getInspectorSections,
@@ -51,10 +52,13 @@ export function renderEntityHeader(
const isVisible = store.isEntityVisible(entity as number);
const visibilityIcon = isVisible ? icons.eye(14) : icons.eyeOff(14);
+ const entityData = store.getEntityData(entity as number);
+ const entityIcon = entityData?.prefab?.isRoot ? icons.package(16) : icons.box(16);
+
const header = document.createElement('div');
header.className = 'es-inspector-entity-header';
header.innerHTML = `
- <span class="es-entity-icon">${icons.box(16)}</span>
+ <span class="es-entity-icon">${entityIcon}</span>
<input type="text" class="es-entity-name-input" value="${escapeHtml(name)}">
<span class="es-entity-visibility">${visibilityIcon}</span>
<span class="es-entity-id">ID:${entity}</span>
@@ -82,6 +86,53 @@ export function renderEntityHeader(
});
container.appendChild(header);
+
+ if (entityData?.prefab) {
+ renderPrefabInfoBar(container, entity, entityData, store);
+ }
+}
+
+function renderPrefabInfoBar(
+ container: HTMLElement,
+ entity: Entity,
+ entityData: import('../../types/SceneTypes').EntityData,
+ store: EditorStore
+): void {
+ const prefab = entityData.prefab!;
+ const pathDisplay = prefab.prefabPath.split('/').pop() ?? prefab.prefabPath;
+
+ const bar = document.createElement('div');
+ bar.className = 'es-prefab-info-bar';
+ bar.innerHTML = `
+ ${icons.package(12)}
+ <span class="es-prefab-info-path es-prefab-info-link" title="${escapeHtml(prefab.prefabPath)}">${escapeHtml(pathDisplay)}</span>
+ `;
+
+ const pathEl = bar.querySelector('.es-prefab-info-link');
+ pathEl?.addEventListener('click', () => {
+ getEditorInstance()?.navigateToAsset(prefab.prefabPath);
+ });
+
+ if (prefab.isRoot) {
+ const revertBtn = document.createElement('button');
+ revertBtn.className = 'es-btn';
+ revertBtn.textContent = 'Revert';
+ revertBtn.addEventListener('click', () => {
+ store.revertPrefabInstance(prefab.instanceId, prefab.prefabPath);
+ });
+
+ const applyBtn = document.createElement('button');
+ applyBtn.className = 'es-btn';
+ applyBtn.textContent = 'Apply';
+ applyBtn.addEventListener('click', () => {
+ store.applyPrefabOverrides(prefab.instanceId, prefab.prefabPath);
+ });
+
+ bar.appendChild(revertBtn);
+ bar.appendChild(applyBtn);
+ }
+
+ container.appendChild(bar);
}
// =============================================================================
@@ -201,6 +252,16 @@ export function renderComponent(
const row = document.createElement('div');
row.className = 'es-property-row';
+ const entityData = store.getEntityData(entity as number);
+ if (entityData?.prefab && isPropertyOverridden(
+ store.scene,
+ entity as number,
+ component.type,
+ propMeta.name
+ )) {
+ row.classList.add('es-overridden');
+ }
+
const label = document.createElement('label');
label.className = 'es-property-label';
label.textContent = propMeta.name;
diff --git a/editor/src/prefab/PrefabInstantiator.ts b/editor/src/prefab/PrefabInstantiator.ts
new file mode 100644
index 000000000..ef3a12284
--- /dev/null
+++ b/editor/src/prefab/PrefabInstantiator.ts
@@ -0,0 +1,266 @@
+/**
+ * @file PrefabInstantiator.ts
+ * @brief Prefab instantiation into scene
+ */
+
+import type { SceneData, EntityData, ComponentData } from '../types/SceneTypes';
+import type { PrefabData, PrefabOverride, PrefabInstanceData } from '../types/PrefabTypes';
+import { loadPrefabFromPath } from './PrefabSerializer';
+
+// =============================================================================
+// Instantiation Result
+// =============================================================================
+
+export interface InstantiateResult {
+ rootEntityId: number;
+ createdEntities: EntityData[];
+}
+
+// =============================================================================
+// ID Allocation
+// =============================================================================
+
+export function computeNextEntityId(scene: SceneData): number {
+ return scene.entities.reduce((max, e) => Math.max(max, e.id), 0) + 1;
+}
+
+// =============================================================================
+// Instance ID Generation
+// =============================================================================
+
+let instanceCounter = 0;
+
+function generateInstanceId(): string {
+ return `prefab_${Date.now()}_${++instanceCounter}`;
+}
+
+// =============================================================================
+// Instantiation (non-recursive)
+// =============================================================================
+
+export function instantiatePrefab(
+ prefab: PrefabData,
+ prefabPath: string,
+ scene: SceneData,
+ parentEntityId: number | null,
+ nextEntityIdStart: number,
+ overrides: PrefabOverride[] = []
+): InstantiateResult {
+ const idMapping = new Map<number, number>();
+ let nextId = nextEntityIdStart;
+
+ for (const pe of prefab.entities) {
+ idMapping.set(pe.prefabEntityId, nextId++);
+ }
+
+ const instanceId = generateInstanceId();
+ const createdEntities: EntityData[] = [];
+
+ for (const pe of prefab.entities) {
+ const sceneId = idMapping.get(pe.prefabEntityId)!;
+ const isRoot = pe.prefabEntityId === prefab.rootEntityId;
+
+ let parent: number | null;
+ if (isRoot) {
+ parent = parentEntityId;
+ } else {
+ parent = pe.parent !== null ? idMapping.get(pe.parent) ?? null : null;
+ }
+
+ const children = pe.children
+ .map(cid => idMapping.get(cid))
+ .filter((id): id is number => id !== undefined);
+
+ const prefabInstance: PrefabInstanceData = {
+ prefabPath,
+ prefabEntityId: pe.prefabEntityId,
+ isRoot,
+ instanceId,
+ overrides: isRoot ? [...overrides] : [],
+ };
+
+ const entity: EntityData = {
+ id: sceneId,
+ name: pe.name,
+ parent,
+ children,
+ components: deepCloneComponents(pe.components),
+ visible: pe.visible,
+ prefab: prefabInstance,
+ };
+
+ applyOverrides(entity, overrides);
+ createdEntities.push(entity);
+ }
+
+ return {
+ rootEntityId: idMapping.get(prefab.rootEntityId)!,
+ createdEntities,
+ };
+}
+
+// =============================================================================
+// Recursive Instantiation (Phase 5)
+// =============================================================================
+
+export async function instantiatePrefabRecursive(
+ prefabPath: string,
+ scene: SceneData,
+ parentEntityId: number | null,
+ nextEntityIdStart: number,
+ overrides: PrefabOverride[] = []
+): Promise<InstantiateResult | null> {
+ const prefab = await loadPrefabFromPath(prefabPath);
+ if (!prefab) return null;
+
+ const idMapping = new Map<number, number>();
+ let nextId = nextEntityIdStart;
+
+ for (const pe of prefab.entities) {
+ if (!pe.nestedPrefab) {
+ idMapping.set(pe.prefabEntityId, nextId++);
+ }
+ }
+
+ const instanceId = generateInstanceId();
+ const allCreated: EntityData[] = [];
+
+ for (const pe of prefab.entities) {
+ const isRoot = pe.prefabEntityId === prefab.rootEntityId;
+
+ if (pe.nestedPrefab) {
+ const nestedParentPrefabId = pe.parent;
+ const nestedParentSceneId = nestedParentPrefabId !== null
+ ? idMapping.get(nestedParentPrefabId) ?? null
+ : (isRoot ? parentEntityId : null);
+
+ const nestedResult = await instantiatePrefabRecursive(
+ pe.nestedPrefab.prefabPath,
+ scene,
+ nestedParentSceneId,
+ nextId,
+ pe.nestedPrefab.overrides
+ );
+
+ if (nestedResult) {
+ idMapping.set(pe.prefabEntityId, nestedResult.rootEntityId);
+ nextId = computeNextIdAfter(nestedResult.createdEntities, nextId);
+ allCreated.push(...nestedResult.createdEntities);
+ }
+ continue;
+ }
+
+ const sceneId = idMapping.get(pe.prefabEntityId)!;
+
+ let parent: number | null;
+ if (isRoot) {
+ parent = parentEntityId;
+ } else {
+ parent = pe.parent !== null ? idMapping.get(pe.parent) ?? null : null;
+ }
+
+ const children = pe.children
+ .map(cid => idMapping.get(cid))
+ .filter((id): id is number => id !== undefined);
+
+ const prefabInstance: PrefabInstanceData = {
+ prefabPath,
+ prefabEntityId: pe.prefabEntityId,
+ isRoot,
+ instanceId,
+ overrides: isRoot ? [...overrides] : [],
+ };
+
+ const entity: EntityData = {
+ id: sceneId,
+ name: pe.name,
+ parent,
+ children,
+ components: deepCloneComponents(pe.components),
+ visible: pe.visible,
+ prefab: prefabInstance,
+ };
+
+ applyOverrides(entity, overrides);
+ allCreated.push(entity);
+ }
+
+ const rootSceneId = idMapping.get(prefab.rootEntityId);
+ if (rootSceneId === undefined) return null;
+
+ return {
+ rootEntityId: rootSceneId,
+ createdEntities: allCreated,
+ };
+}
+
+// =============================================================================
+// Override Application
+// =============================================================================
+
+function applyOverrides(entity: EntityData, overrides: PrefabOverride[]): void {
+ const prefabEntityId = entity.prefab?.prefabEntityId;
+ if (prefabEntityId === undefined) return;
+
+ for (const override of overrides) {
+ if (override.prefabEntityId !== prefabEntityId) continue;
+
+ switch (override.type) {
+ case 'property':
+ if (override.componentType && override.propertyName !== undefined) {
+ const comp = entity.components.find(c => c.type === override.componentType);
+ if (comp) {
+ comp.data[override.propertyName] = override.value;
+ }
+ }
+ break;
+ case 'name':
+ if (typeof override.value === 'string') {
+ entity.name = override.value;
+ }
+ break;
+ case 'visibility':
+ if (typeof override.value === 'boolean') {
+ entity.visible = override.value;
+ }
+ break;
+ case 'component_added':
+ if (override.componentData) {
+ const exists = entity.components.some(c => c.type === override.componentData!.type);
+ if (!exists) {
+ entity.components.push({
+ type: override.componentData.type,
+ data: JSON.parse(JSON.stringify(override.componentData.data)),
+ });
+ }
+ }
+ break;
+ case 'component_removed':
+ if (override.componentType) {
+ entity.components = entity.components.filter(c => c.type !== override.componentType);
+ }
+ break;
+ }
+ }
+}
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+function deepCloneComponents(components: ComponentData[]): ComponentData[] {
+ return components.map(c => ({
+ type: c.type,
+ data: JSON.parse(JSON.stringify(c.data)),
+ }));
+}
+
+function computeNextIdAfter(entities: EntityData[], currentNext: number): number {
+ let max = currentNext;
+ for (const e of entities) {
+ if (e.id >= max) {
+ max = e.id + 1;
+ }
+ }
+ return max;
+}
diff --git a/editor/src/prefab/PrefabOverrideTracker.ts b/editor/src/prefab/PrefabOverrideTracker.ts
new file mode 100644
index 000000000..40df56809
--- /dev/null
+++ b/editor/src/prefab/PrefabOverrideTracker.ts
@@ -0,0 +1,176 @@
+/**
+ * @file PrefabOverrideTracker.ts
+ * @brief Override recording and querying for prefab instances
+ */
+
+import type { EntityData, SceneData } from '../types/SceneTypes';
+import type { PrefabOverride } from '../types/PrefabTypes';
+
+// =============================================================================
+// Query
+// =============================================================================
+
+export function isPropertyOverridden(
+ scene: SceneData,
+ entityId: number,
+ componentType: string,
+ propertyName: string
+): boolean {
+ const entity = scene.entities.find(e => e.id === entityId);
+ if (!entity?.prefab) return false;
+
+ const root = findInstanceRoot(scene, entity.prefab.instanceId);
+ if (!root?.prefab) return false;
+
+ return root.prefab.overrides.some(
+ o => o.prefabEntityId === entity.prefab!.prefabEntityId &&
+ o.type === 'property' &&
+ o.componentType === componentType &&
+ o.propertyName === propertyName
+ );
+}
+
+export function getOverridesForEntity(
+ scene: SceneData,
+ entityId: number
+): PrefabOverride[] {
+ const entity = scene.entities.find(e => e.id === entityId);
+ if (!entity?.prefab) return [];
+
+ const root = findInstanceRoot(scene, entity.prefab.instanceId);
+ if (!root?.prefab) return [];
+
+ return root.prefab.overrides.filter(
+ o => o.prefabEntityId === entity.prefab!.prefabEntityId
+ );
+}
+
+export function hasAnyOverrides(scene: SceneData, instanceId: string): boolean {
+ const root = findInstanceRoot(scene, instanceId);
+ return (root?.prefab?.overrides.length ?? 0) > 0;
+}
+
+// =============================================================================
+// Recording
+// =============================================================================
+
+export function recordPropertyOverride(
+ scene: SceneData,
+ entityId: number,
+ componentType: string,
+ propertyName: string,
+ value: unknown
+): void {
+ const entity = scene.entities.find(e => e.id === entityId);
+ if (!entity?.prefab) return;
+
+ const root = findInstanceRoot(scene, entity.prefab.instanceId);
+ if (!root?.prefab) return;
+
+ const existing = root.prefab.overrides.findIndex(
+ o => o.prefabEntityId === entity.prefab!.prefabEntityId &&
+ o.type === 'property' &&
+ o.componentType === componentType &&
+ o.propertyName === propertyName
+ );
+
+ const override: PrefabOverride = {
+ prefabEntityId: entity.prefab.prefabEntityId,
+ type: 'property',
+ componentType,
+ propertyName,
+ value: JSON.parse(JSON.stringify(value)),
+ };
+
+ if (existing !== -1) {
+ root.prefab.overrides[existing] = override;
+ } else {
+ root.prefab.overrides.push(override);
+ }
+}
+
+export function recordNameOverride(
+ scene: SceneData,
+ entityId: number,
+ name: string
+): void {
+ const entity = scene.entities.find(e => e.id === entityId);
+ if (!entity?.prefab) return;
+
+ const root = findInstanceRoot(scene, entity.prefab.instanceId);
+ if (!root?.prefab) return;
+
+ const existing = root.prefab.overrides.findIndex(
+ o => o.prefabEntityId === entity.prefab!.prefabEntityId && o.type === 'name'
+ );
+
+ const override: PrefabOverride = {
+ prefabEntityId: entity.prefab.prefabEntityId,
+ type: 'name',
+ value: name,
+ };
+
+ if (existing !== -1) {
+ root.prefab.overrides[existing] = override;
+ } else {
+ root.prefab.overrides.push(override);
+ }
+}
+
+export function recordVisibilityOverride(
+ scene: SceneData,
+ entityId: number,
+ visible: boolean
+): void {
+ const entity = scene.entities.find(e => e.id === entityId);
+ if (!entity?.prefab) return;
+
+ const root = findInstanceRoot(scene, entity.prefab.instanceId);
+ if (!root?.prefab) return;
+
+ const existing = root.prefab.overrides.findIndex(
+ o => o.prefabEntityId === entity.prefab!.prefabEntityId && o.type === 'visibility'
+ );
+
+ const override: PrefabOverride = {
+ prefabEntityId: entity.prefab.prefabEntityId,
+ type: 'visibility',
+ value: visible,
+ };
+
+ if (existing !== -1) {
+ root.prefab.overrides[existing] = override;
+ } else {
+ root.prefab.overrides.push(override);
+ }
+}
+
+export function removePropertyOverride(
+ scene: SceneData,
+ entityId: number,
+ componentType: string,
+ propertyName: string
+): void {
+ const entity = scene.entities.find(e => e.id === entityId);
+ if (!entity?.prefab) return;
+
+ const root = findInstanceRoot(scene, entity.prefab.instanceId);
+ if (!root?.prefab) return;
+
+ root.prefab.overrides = root.prefab.overrides.filter(
+ o => !(o.prefabEntityId === entity.prefab!.prefabEntityId &&
+ o.type === 'property' &&
+ o.componentType === componentType &&
+ o.propertyName === propertyName)
+ );
+}
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+function findInstanceRoot(scene: SceneData, instanceId: string): EntityData | undefined {
+ return scene.entities.find(
+ e => e.prefab?.instanceId === instanceId && e.prefab?.isRoot
+ );
+}
diff --git a/editor/src/prefab/PrefabSerializer.ts b/editor/src/prefab/PrefabSerializer.ts
new file mode 100644
index 000000000..04c1b3007
--- /dev/null
+++ b/editor/src/prefab/PrefabSerializer.ts
@@ -0,0 +1,197 @@
+/**
+ * @file PrefabSerializer.ts
+ * @brief .esprefab file read/write and entity tree → prefab conversion
+ */
+
+import type { EntityData, ComponentData, SceneData } from '../types/SceneTypes';
+import type { PrefabData, PrefabEntityData } from '../types/PrefabTypes';
+import { getEditorContext } from '../context/EditorContext';
+import type { NativeFS } from '../types/NativeFS';
+import { getGlobalPathResolver } from '../asset';
+
+// =============================================================================
+// Serialization
+// =============================================================================
+
+export function serializePrefab(prefab: PrefabData): string {
+ return JSON.stringify(prefab, null, 2);
+}
+
+export function deserializePrefab(json: string): PrefabData {
+ const data = JSON.parse(json) as PrefabData;
+ validatePrefab(data);
+ return data;
+}
+
+function validatePrefab(prefab: PrefabData): void {
+ if (!prefab.version) {
+ prefab.version = '1.0';
+ }
+ if (!prefab.name) {
+ prefab.name = 'Unnamed';
+ }
+ if (typeof prefab.rootEntityId !== 'number') {
+ prefab.rootEntityId = 1;
+ }
+ if (!Array.isArray(prefab.entities)) {
+ prefab.entities = [];
+ }
+ for (const entity of prefab.entities) {
+ validatePrefabEntity(entity);
+ }
+}
+
+function validatePrefabEntity(entity: PrefabEntityData): void {
+ if (typeof entity.prefabEntityId !== 'number') {
+ throw new Error('PrefabEntity must have numeric prefabEntityId');
+ }
+ if (!entity.name) {
+ entity.name = `Entity_${entity.prefabEntityId}`;
+ }
+ if (!Array.isArray(entity.children)) {
+ entity.children = [];
+ }
+ if (!Array.isArray(entity.components)) {
+ entity.components = [];
+ }
+ if (entity.visible === undefined) {
+ entity.visible = true;
+ }
+}
+
+// =============================================================================
+// Entity Tree → PrefabData Conversion
+// =============================================================================
+
+export interface EntityTreeToPrefabResult {
+ prefab: PrefabData;
+ idMapping: Map<number, number>;
+}
+
+export function entityTreeToPrefab(
+ name: string,
+ rootEntityId: number,
+ entities: EntityData[]
+): EntityTreeToPrefabResult {
+ const idMapping = new Map<number, number>();
+ let nextPrefabId = 1;
+
+ const collectIds = (entityId: number) => {
+ idMapping.set(entityId, nextPrefabId++);
+ const entity = entities.find(e => e.id === entityId);
+ if (entity) {
+ for (const childId of entity.children) {
+ collectIds(childId);
+ }
+ }
+ };
+ collectIds(rootEntityId);
+
+ const prefabEntities: PrefabEntityData[] = [];
+ for (const [sceneId, prefabId] of idMapping) {
+ const entity = entities.find(e => e.id === sceneId);
+ if (!entity) continue;
+
+ const parentPrefabId = entity.parent !== null ? idMapping.get(entity.parent) ?? null : null;
+ const childPrefabIds = entity.children
+ .map(cid => idMapping.get(cid))
+ .filter((id): id is number => id !== undefined);
+
+ const prefabEntity: PrefabEntityData = {
+ prefabEntityId: prefabId,
+ name: entity.name,
+ parent: sceneId === rootEntityId ? null : parentPrefabId,
+ children: childPrefabIds,
+ components: deepCloneComponents(entity.components),
+ visible: entity.visible,
+ };
+
+ if (entity.prefab?.prefabPath) {
+ prefabEntity.nestedPrefab = {
+ prefabPath: entity.prefab.prefabPath,
+ overrides: [...(entity.prefab.overrides ?? [])],
+ };
+ }
+
+ prefabEntities.push(prefabEntity);
+ }
+
+ return {
+ prefab: {
+ version: '1.0',
+ name,
+ rootEntityId: 1,
+ entities: prefabEntities,
+ },
+ idMapping,
+ };
+}
+
+// =============================================================================
+// PrefabData ↔ SceneData Conversion
+// =============================================================================
+
+export function prefabToSceneData(prefab: PrefabData): SceneData {
+ const entities: EntityData[] = prefab.entities.map(pe => ({
+ id: pe.prefabEntityId,
+ name: pe.name,
+ parent: pe.parent,
+ children: [...pe.children],
+ components: deepCloneComponents(pe.components),
+ visible: pe.visible,
+ }));
+
+ return {
+ version: '2.0',
+ name: prefab.name,
+ entities,
+ };
+}
+
+export function sceneDataToPrefab(scene: SceneData): PrefabData {
+ const roots = scene.entities.filter(e => e.parent === null);
+ const rootId = roots.length > 0 ? roots[0].id : (scene.entities[0]?.id ?? 1);
+
+ const { prefab } = entityTreeToPrefab(scene.name, rootId, scene.entities);
+ return prefab;
+}
+
+function deepCloneComponents(components: ComponentData[]): ComponentData[] {
+ return components.map(c => ({
+ type: c.type,
+ data: JSON.parse(JSON.stringify(c.data)),
+ }));
+}
+
+// =============================================================================
+// File I/O
+// =============================================================================
+
+function getNativeFS(): NativeFS | null {
+ return getEditorContext().fs ?? null;
+}
+
+export async function savePrefabToPath(prefab: PrefabData, filePath: string): Promise<boolean> {
+ const fs = getNativeFS();
+ if (!fs) return false;
+
+ const absolutePath = getGlobalPathResolver().toAbsolutePath(filePath);
+ const json = serializePrefab(prefab);
+ return fs.writeFile(absolutePath, json);
+}
+
+export async function loadPrefabFromPath(filePath: string): Promise<PrefabData | null> {
+ const fs = getNativeFS();
+ if (!fs) return null;
+
+ const absolutePath = getGlobalPathResolver().toAbsolutePath(filePath);
+
+ try {
+ const content = await fs.readFile(absolutePath);
+ if (!content) return null;
+ return deserializePrefab(content);
+ } catch (err) {
+ console.error('Failed to load prefab:', absolutePath, err);
+ return null;
+ }
+}
diff --git a/editor/src/prefab/index.ts b/editor/src/prefab/index.ts
new file mode 100644
index 000000000..5fb365043
--- /dev/null
+++ b/editor/src/prefab/index.ts
@@ -0,0 +1,32 @@
+/**
+ * @file index.ts
+ * @brief Prefab system exports
+ */
+
+export {
+ serializePrefab,
+ deserializePrefab,
+ entityTreeToPrefab,
+ prefabToSceneData,
+ sceneDataToPrefab,
+ savePrefabToPath,
+ loadPrefabFromPath,
+ type EntityTreeToPrefabResult,
+} from './PrefabSerializer';
+
+export {
+ instantiatePrefab,
+ instantiatePrefabRecursive,
+ computeNextEntityId,
+ type InstantiateResult,
+} from './PrefabInstantiator';
+
+export {
+ isPropertyOverridden,
+ getOverridesForEntity,
+ hasAnyOverrides,
+ recordPropertyOverride,
+ recordNameOverride,
+ recordVisibilityOverride,
+ removePropertyOverride,
+} from './PrefabOverrideTracker';
diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.ts
index ec7889621..fa2dbcb95 100644
--- a/editor/src/scene/EditorSceneManager.ts
+++ b/editor/src/scene/EditorSceneManager.ts
@@ -51,6 +51,7 @@ export class EditorSceneManager {
private sceneData_: SceneData | null = null;
private syncing_ = false;
private pendingScene_: SceneData | null = null;
+ private syncCompleteResolvers_: (() => void)[] = [];
private spineController_: SpineModuleController | null = null;
private spineInstances_ = new Map<number, number>();
private spineSkeletons_ = new Map<string, number>();
@@ -100,7 +101,9 @@ export class EditorSceneManager {
async loadScene(scene: SceneData): Promise<void> {
if (this.syncing_) {
this.pendingScene_ = scene;
- return;
+ return new Promise<void>(resolve => {
+ this.syncCompleteResolvers_.push(resolve);
+ });
}
this.syncing_ = true;
@@ -108,13 +111,17 @@ export class EditorSceneManager {
try {
await this.loadSceneInternal(scene);
- if (this.pendingScene_) {
+ while (this.pendingScene_) {
const latest = this.pendingScene_;
this.pendingScene_ = null;
await this.loadSceneInternal(latest);
}
} finally {
this.syncing_ = false;
+ const resolvers = this.syncCompleteResolvers_.splice(0);
+ for (const resolve of resolvers) {
+ resolve();
+ }
}
}
@@ -183,6 +190,14 @@ export class EditorSceneManager {
await this.syncSpineAnimation(entity, comp.data, entityId);
break;
+ case 'UIRect':
+ case 'Interactable':
+ case 'Button':
+ case 'ScreenSpace':
+ case 'UIMask':
+ case 'TextInput':
+ break;
+
default:
loadComponent(this.world_, entity, comp as SceneComponentData);
}
@@ -246,7 +261,11 @@ export class EditorSceneManager {
if (entity) {
this.destroySpineInstance(entityId);
getDependencyGraph().clearEntity(entityId);
- this.world_.despawn(entity);
+ try {
+ this.world_.despawn(entity);
+ } catch (e) {
+ console.warn(`[EditorSceneManager] despawn failed for entity ${entityId}`, e);
+ }
this.entityMap_.delete(entityId);
this.entityDataMap_.delete(entityId);
}
@@ -259,7 +278,11 @@ export class EditorSceneManager {
if (parentId !== null) {
const parentEntity = this.entityMap_.get(parentId);
if (parentEntity !== undefined) {
- this.world_.setParent(entity, parentEntity);
+ try {
+ this.world_.setParent(entity, parentEntity);
+ } catch (e) {
+ console.warn(`[EditorSceneManager] setParent failed for entity ${entityId} -> ${parentId}`, e);
+ }
}
}
}
@@ -514,8 +537,9 @@ export class EditorSceneManager {
getDependencyGraph().clearEntity(entityId);
this.assetServer_.releaseMaterialInstance(entityId);
- const textureRef = data.texture;
- if (textureRef && typeof textureRef === 'string') {
+ const rawTexture = data.texture;
+ const textureRef = typeof rawTexture === 'string' ? rawTexture : '';
+ if (textureRef) {
const texturePath = this.resolveAssetRef(textureRef);
const info = await this.assetServer_.loadTexture(texturePath);
textureHandle = info.handle;
@@ -609,6 +633,10 @@ export class EditorSceneManager {
}
}
+ if (fontHandle === (INVALID_FONT as number)) {
+ return;
+ }
+
if (this.world_.has(entity, BitmapText)) {
this.world_.remove(entity, BitmapText);
}
diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.ts
index e4372fdf2..8cce2ad78 100644
--- a/editor/src/store/EditorStore.ts
+++ b/editor/src/store/EditorStore.ts
@@ -16,7 +16,24 @@ import {
MoveEntityCommand,
AddComponentCommand,
RemoveComponentCommand,
+ InstantiatePrefabCommand,
+ UnpackPrefabCommand,
+ RevertPrefabInstanceCommand,
+ ApplyPrefabOverridesCommand,
} from '../commands';
+import type { PrefabData, PrefabInstanceData } from '../types/PrefabTypes';
+import {
+ entityTreeToPrefab,
+ savePrefabToPath,
+ loadPrefabFromPath,
+ prefabToSceneData,
+ sceneDataToPrefab,
+ instantiatePrefabRecursive,
+ recordPropertyOverride,
+ recordNameOverride,
+ recordVisibilityOverride,
+} from '../prefab';
+import { getGlobalPathResolver } from '../asset';
import { WorldTransformCache } from '../transform/WorldTransformCache';
import type { Transform } from '../math/Transform';
import { isComponentRemovable } from '../schemas/ComponentSchemas';
@@ -104,6 +121,13 @@ export class EditorStore {
private worldTransforms_ = new WorldTransformCache();
private entityMap_ = new Map<number, EntityData>();
+ private prefabEditingPath_: string | null = null;
+ private savedSceneState_: {
+ scene: SceneData;
+ filePath: string | null;
+ isDirty: boolean;
+ } | null = null;
+
constructor() {
const scene = createEmptyScene();
this.state_ = {
@@ -152,6 +176,14 @@ export class EditorStore {
return this.state_.selectedAsset;
}
+ get prefabEditingPath(): string | null {
+ return this.prefabEditingPath_;
+ }
+
+ get isEditingPrefab(): boolean {
+ return this.prefabEditingPath_ !== null;
+ }
+
get canUndo(): boolean {
return this.history_.canUndo();
}
@@ -266,6 +298,11 @@ export class EditorStore {
} else {
this.hideEntityTree(entityId);
}
+
+ if (entityData.prefab) {
+ recordVisibilityOverride(this.state_.scene, entityId, entityData.visible);
+ }
+
this.state_.isDirty = true;
this.notify();
}
@@ -392,6 +429,9 @@ export class EditorStore {
const entityData = this.entityMap_.get(entity as number);
if (entityData) {
entityData.name = name;
+ if (entityData.prefab) {
+ recordNameOverride(this.state_.scene, entity as number, name);
+ }
this.state_.isDirty = true;
this.notify();
}
@@ -430,6 +470,17 @@ export class EditorStore {
newValue
);
this.executeCommand(cmd);
+
+ if (this.isPrefabInstance(entity as number)) {
+ recordPropertyOverride(
+ this.state_.scene,
+ entity as number,
+ componentType,
+ propertyName,
+ newValue
+ );
+ }
+
this.notifyPropertyChange({
entity: entity as number,
componentType,
@@ -519,6 +570,236 @@ export class EditorStore {
this.worldTransforms_.invalidateAll();
}
+ // =========================================================================
+ // Prefab Operations
+ // =========================================================================
+
+ async instantiatePrefab(
+ prefabPath: string,
+ parentEntity: Entity | null = null
+ ): Promise<Entity | null> {
+ const hasNested = await this.prefabHasNested(prefabPath);
+
+ if (hasNested) {
+ return this.instantiatePrefabNested(prefabPath, parentEntity);
+ }
+
+ const prefab = await loadPrefabFromPath(prefabPath);
+ if (!prefab) return null;
+
+ const cmd = new InstantiatePrefabCommand(
+ this.state_.scene,
+ prefab,
+ prefabPath,
+ parentEntity as number | null,
+ this.nextEntityId_
+ );
+ this.executeCommand(cmd);
+
+ const createdIds = cmd.createdEntityIds;
+ this.nextEntityId_ = Math.max(this.nextEntityId_, ...createdIds.map(id => id + 1));
+
+ for (const id of createdIds) {
+ this.notifyEntityLifecycle({ entity: id, type: 'created', parent: null });
+ }
+
+ const rootId = cmd.rootEntityId;
+ if (rootId !== -1) {
+ this.selectEntity(rootId as Entity);
+ }
+
+ return rootId as Entity;
+ }
+
+ private async instantiatePrefabNested(
+ prefabPath: string,
+ parentEntity: Entity | null
+ ): Promise<Entity | null> {
+ const result = await instantiatePrefabRecursive(
+ prefabPath,
+ this.state_.scene,
+ parentEntity as number | null,
+ this.nextEntityId_
+ );
+ if (!result) return null;
+
+ const snapshot = result.createdEntities.map(e => ({ ...e }));
+
+ for (const entity of result.createdEntities) {
+ this.state_.scene.entities.push(entity);
+ }
+
+ if (parentEntity !== null) {
+ const parent = this.entityMap_.get(parentEntity as number);
+ if (parent && !parent.children.includes(result.rootEntityId)) {
+ parent.children.push(result.rootEntityId);
+ }
+ }
+
+ this.nextEntityId_ = Math.max(
+ this.nextEntityId_,
+ ...result.createdEntities.map(e => e.id + 1)
+ );
+
+ this.state_.isDirty = true;
+ this.rebuildEntityMap();
+ this.worldTransforms_.invalidateAll();
+
+ for (const entity of result.createdEntities) {
+ this.notifyEntityLifecycle({ entity: entity.id, type: 'created', parent: entity.parent });
+ }
+
+ this.selectEntity(result.rootEntityId as Entity);
+ this.notify();
+
+ return result.rootEntityId as Entity;
+ }
+
+ private async prefabHasNested(prefabPath: string): Promise<boolean> {
+ const prefab = await loadPrefabFromPath(prefabPath);
+ if (!prefab) return false;
+ return prefab.entities.some(e => e.nestedPrefab !== undefined);
+ }
+
+ async saveAsPrefab(entityId: number, filePath: string): Promise<boolean> {
+ const entityData = this.entityMap_.get(entityId);
+ if (!entityData) return false;
+
+ const name = filePath.split('/').pop()?.replace('.esprefab', '') ?? entityData.name;
+ const entities = this.collectEntityTree(entityId);
+ const { prefab, idMapping } = entityTreeToPrefab(name, entityId, entities);
+
+ const saved = await savePrefabToPath(prefab, filePath);
+ if (!saved) return false;
+
+ const relativePath = getGlobalPathResolver().toRelativePath(filePath);
+ const instanceId = `prefab_${Date.now()}_${entityId}`;
+
+ for (const [sceneId, prefabEntityId] of idMapping) {
+ const entity = this.entityMap_.get(sceneId);
+ if (!entity) continue;
+
+ entity.prefab = {
+ prefabPath: relativePath,
+ prefabEntityId,
+ isRoot: sceneId === entityId,
+ instanceId,
+ overrides: [],
+ };
+ }
+
+ this.state_.isDirty = true;
+ this.notify();
+ return true;
+ }
+
+ async revertPrefabInstance(instanceId: string, prefabPath: string): Promise<void> {
+ const prefab = await loadPrefabFromPath(prefabPath);
+ if (!prefab) return;
+
+ const cmd = new RevertPrefabInstanceCommand(
+ this.state_.scene,
+ instanceId,
+ prefab,
+ prefabPath
+ );
+ this.executeCommand(cmd);
+ }
+
+ async applyPrefabOverrides(instanceId: string, prefabPath: string): Promise<void> {
+ const prefab = await loadPrefabFromPath(prefabPath);
+ if (!prefab) return;
+
+ const cmd = new ApplyPrefabOverridesCommand(
+ this.state_.scene,
+ instanceId,
+ prefab,
+ prefabPath,
+ async (p, path) => { await savePrefabToPath(p, path); }
+ );
+ this.executeCommand(cmd);
+ }
+
+ unpackPrefab(instanceId: string): void {
+ const cmd = new UnpackPrefabCommand(this.state_.scene, instanceId);
+ this.executeCommand(cmd);
+ }
+
+ isPrefabInstance(entityId: number): boolean {
+ const entity = this.entityMap_.get(entityId);
+ return entity?.prefab !== undefined;
+ }
+
+ isPrefabRoot(entityId: number): boolean {
+ const entity = this.entityMap_.get(entityId);
+ return entity?.prefab?.isRoot === true;
+ }
+
+ getPrefabInstanceId(entityId: number): string | undefined {
+ return this.entityMap_.get(entityId)?.prefab?.instanceId;
+ }
+
+ getPrefabPath(entityId: number): string | undefined {
+ return this.entityMap_.get(entityId)?.prefab?.prefabPath;
+ }
+
+ async enterPrefabEditMode(prefabPath: string): Promise<boolean> {
+ const prefab = await loadPrefabFromPath(prefabPath);
+ if (!prefab) return false;
+
+ this.savedSceneState_ = {
+ scene: JSON.parse(JSON.stringify(this.state_.scene)),
+ filePath: this.state_.filePath,
+ isDirty: this.state_.isDirty,
+ };
+
+ this.prefabEditingPath_ = prefabPath;
+ const scene = prefabToSceneData(prefab);
+ this.loadScene(scene, null);
+
+ return true;
+ }
+
+ async exitPrefabEditMode(): Promise<void> {
+ if (!this.savedSceneState_) return;
+
+ if (this.state_.isDirty) {
+ await this.savePrefabEditing();
+ }
+
+ const saved = this.savedSceneState_;
+ this.prefabEditingPath_ = null;
+ this.savedSceneState_ = null;
+
+ this.loadScene(saved.scene, saved.filePath);
+ this.state_.isDirty = saved.isDirty;
+ this.notify();
+ }
+
+ async savePrefabEditing(): Promise<boolean> {
+ if (!this.prefabEditingPath_) return false;
+
+ const prefab = sceneDataToPrefab(this.state_.scene);
+ const saved = await savePrefabToPath(prefab, this.prefabEditingPath_);
+ if (saved) {
+ this.state_.isDirty = false;
+ this.notify();
+ }
+ return saved;
+ }
+
+ private collectEntityTree(rootId: number): import('../types/SceneTypes').EntityData[] {
+ const result: import('../types/SceneTypes').EntityData[] = [];
+ const entity = this.entityMap_.get(rootId);
+ if (!entity) return result;
+
+ result.push(entity);
+ for (const childId of entity.children) {
+ result.push(...this.collectEntityTree(childId));
+ }
+ return result;
+ }
+
// =========================================================================
// Undo/Redo
// =========================================================================
@@ -527,7 +808,7 @@ export class EditorStore {
if (this.history_.undo()) {
this.state_.isDirty = true;
this.rebuildEntityMap();
- this.worldTransforms_.invalidateAll();
+ this.worldTransforms_.setScene(this.state_.scene);
this.sceneLoadVersion_++;
this.notify();
}
@@ -537,7 +818,7 @@ export class EditorStore {
if (this.history_.redo()) {
this.state_.isDirty = true;
this.rebuildEntityMap();
- this.worldTransforms_.invalidateAll();
+ this.worldTransforms_.setScene(this.state_.scene);
this.sceneLoadVersion_++;
this.notify();
}
@@ -584,7 +865,7 @@ export class EditorStore {
this.history_.execute(cmd);
this.state_.isDirty = true;
this.rebuildEntityMap();
- this.worldTransforms_.invalidateAll();
+ this.worldTransforms_.setScene(this.state_.scene);
this.notify();
}
diff --git a/editor/src/styles/editor.css b/editor/src/styles/editor.css
index 76e91a814..e96ef47f3 100644
--- a/editor/src/styles/editor.css
+++ b/editor/src/styles/editor.css
@@ -542,6 +542,62 @@ svg {
opacity: 0.4;
}
+.es-prefab-edit-bar {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 8px;
+ background: rgba(79, 193, 255, 0.1);
+ border-bottom: 1px solid rgba(79, 193, 255, 0.25);
+ font-size: 11px;
+ color: #4fc1ff;
+}
+
+.es-prefab-back-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 2px 8px;
+ font-size: 11px;
+ color: var(--es-text-primary);
+ background: var(--es-bg-secondary);
+ border: 1px solid var(--es-border);
+ border-radius: 3px;
+ cursor: pointer;
+}
+
+.es-prefab-back-btn:hover {
+ background: var(--es-bg-hover);
+}
+
+.es-prefab-back-btn svg {
+ transform: rotate(180deg);
+}
+
+.es-prefab-edit-name {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ font-weight: 600;
+}
+
+.es-prefab-edit-name svg {
+ stroke: #4fc1ff;
+}
+
+.es-hierarchy-item.es-prefab-root > .es-hierarchy-row .es-hierarchy-name {
+ color: #4fc1ff;
+ font-weight: 600;
+}
+
+.es-hierarchy-item.es-prefab-root > .es-hierarchy-row .es-hierarchy-icon svg {
+ stroke: #4fc1ff;
+}
+
+.es-hierarchy-item.es-prefab-child > .es-hierarchy-row .es-hierarchy-name {
+ color: #87d7ff;
+}
+
.es-hierarchy-footer {
padding: 6px 12px;
font-size: 11px;
@@ -653,6 +709,73 @@ svg {
border-color: var(--es-accent);
}
+.es-prefab-info-bar {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 8px;
+ margin-bottom: 4px;
+ background: rgba(79, 193, 255, 0.08);
+ border: 1px solid rgba(79, 193, 255, 0.25);
+ border-radius: 3px;
+ font-size: 11px;
+ color: #4fc1ff;
+}
+
+.es-prefab-info-bar svg {
+ stroke: #4fc1ff;
+ flex-shrink: 0;
+}
+
+.es-prefab-info-path {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.es-prefab-info-link {
+ cursor: pointer;
+ text-decoration: underline;
+ text-decoration-color: transparent;
+ transition: text-decoration-color 0.15s;
+}
+
+.es-prefab-info-link:hover {
+ text-decoration-color: #4fc1ff;
+}
+
+.es-prefab-info-bar .es-btn {
+ font-size: 10px;
+ padding: 1px 6px;
+ border: 1px solid rgba(79, 193, 255, 0.3);
+ color: #4fc1ff;
+ background: transparent;
+ cursor: pointer;
+ border-radius: 3px;
+}
+
+.es-prefab-info-bar .es-btn:hover {
+ background: rgba(79, 193, 255, 0.15);
+}
+
+.es-property-row.es-overridden .es-property-label {
+ font-weight: 700;
+ color: #4fc1ff;
+}
+
+.es-property-row.es-overridden .es-property-label::before {
+ content: '';
+ display: inline-block;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: #4fc1ff;
+ margin-right: 4px;
+ vertical-align: middle;
+}
+
.es-component-section {
background: var(--es-bg-secondary);
margin-bottom: 4px;
diff --git a/editor/src/types/PrefabTypes.ts b/editor/src/types/PrefabTypes.ts
new file mode 100644
index 000000000..0329dcb2a
--- /dev/null
+++ b/editor/src/types/PrefabTypes.ts
@@ -0,0 +1,53 @@
+/**
+ * @file PrefabTypes.ts
+ * @brief Prefab system type definitions
+ */
+
+import type { ComponentData } from './SceneTypes';
+
+// =============================================================================
+// Prefab File Data (.esprefab)
+// =============================================================================
+
+export interface PrefabData {
+ version: string;
+ name: string;
+ rootEntityId: number;
+ entities: PrefabEntityData[];
+}
+
+export interface PrefabEntityData {
+ prefabEntityId: number;
+ name: string;
+ parent: number | null;
+ children: number[];
+ components: ComponentData[];
+ visible: boolean;
+ nestedPrefab?: NestedPrefabRef;
+}
+
+export interface NestedPrefabRef {
+ prefabPath: string;
+ overrides: PrefabOverride[];
+}
+
+// =============================================================================
+// Prefab Instance Data (stored in scene EntityData.prefab)
+// =============================================================================
+
+export interface PrefabInstanceData {
+ prefabPath: string;
+ prefabEntityId: number;
+ isRoot: boolean;
+ instanceId: string;
+ overrides: PrefabOverride[];
+}
+
+export interface PrefabOverride {
+ prefabEntityId: number;
+ type: 'property' | 'component_added' | 'component_removed' | 'name' | 'visibility';
+ componentType?: string;
+ propertyName?: string;
+ value?: unknown;
+ componentData?: ComponentData;
+}
diff --git a/editor/src/types/SceneTypes.ts b/editor/src/types/SceneTypes.ts
index e24bd83a6..b4b6002c2 100644
--- a/editor/src/types/SceneTypes.ts
+++ b/editor/src/types/SceneTypes.ts
@@ -5,6 +5,7 @@
import type { Entity } from 'esengine';
import type { TextureMetadata } from './TextureMetadata';
+import type { PrefabInstanceData } from './PrefabTypes';
// =============================================================================
// Scene Data Types
@@ -24,6 +25,7 @@ export interface EntityData {
children: number[];
components: ComponentData[];
visible: boolean;
+ prefab?: PrefabInstanceData;
}
export interface ComponentData {
diff --git a/editor/src/utils/icons.ts b/editor/src/utils/icons.ts
index bae62f40c..e8eec9399 100644
--- a/editor/src/utils/icons.ts
+++ b/editor/src/utils/icons.ts
@@ -51,6 +51,7 @@ import {
Bone,
EyeOff,
Pencil,
+ Package2,
} from 'lucide';
// =============================================================================
@@ -158,6 +159,7 @@ export const icons = {
template: (size?: number) => renderIcon(LayoutTemplate as IconNode, size),
bone: (size?: number) => renderIcon(Bone as IconNode, size),
pencil: (size?: number) => renderIcon(Pencil as IconNode, size),
+ package: (size?: number) => renderIcon(Package2 as IconNode, size),
};
export type IconName = keyof typeof icons;