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 instance sync, recursive instantiation, and revert command

esenginebc21da21393b
diff --git a/editor/src/commands/PrefabCommands.ts b/editor/src/commands/PrefabCommands.ts
index 76a0bbecc..d441610f5 100644
--- a/editor/src/commands/PrefabCommands.ts
+++ b/editor/src/commands/PrefabCommands.ts
@@ -16,7 +16,6 @@ export class InstantiatePrefabCommand extends BaseCommand {
readonly type = 'instantiate_prefab';
readonly description: string;
private createdEntityIds_: number[] = [];
- private nextEntityIdBefore_: number;
constructor(
private scene_: SceneData,
@@ -27,7 +26,6 @@ export class InstantiatePrefabCommand extends BaseCommand {
) {
super();
this.description = `Instantiate prefab "${prefab_.name}"`;
- this.nextEntityIdBefore_ = nextEntityId_;
}
execute(): void {
@@ -119,7 +117,9 @@ export class UnpackPrefabCommand extends BaseCommand {
export class RevertPrefabInstanceCommand extends BaseCommand {
readonly type = 'revert_prefab';
readonly description: string;
- private savedEntities_: Map<number, EntityData> = new Map();
+ private savedSnapshot_: EntityData[] = [];
+ private savedIndices_: Map<number, number> = new Map();
+ private addedEntityIds_: number[] = [];
constructor(
private scene_: SceneData,
@@ -132,36 +132,96 @@ export class RevertPrefabInstanceCommand extends BaseCommand {
}
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,
- });
+ this.savedIndices_.clear();
+ for (const e of instanceEntities) {
+ this.savedIndices_.set(e.id, this.scene_.entities.indexOf(e));
}
+ this.savedSnapshot_ = instanceEntities.map(e => ({
+ ...e,
+ children: [...e.children],
+ components: e.components.map(c => ({ type: c.type, data: JSON.parse(JSON.stringify(c.data)) })),
+ prefab: e.prefab ? { ...e.prefab, overrides: [...e.prefab.overrides] } : undefined,
+ }));
+
const rootEntity = instanceEntities.find(e => e.prefab?.isRoot);
if (!rootEntity) return;
+ const rootParent = rootEntity.parent;
- const idMapping = new Map<number, number>();
+ const existingByPrefabId = new Map<number, EntityData>();
for (const entity of instanceEntities) {
if (entity.prefab) {
- idMapping.set(entity.prefab.prefabEntityId, entity.id);
+ existingByPrefabId.set(entity.prefab.prefabEntityId, entity);
}
}
- for (const pe of this.prefab_.entities) {
- const sceneId = idMapping.get(pe.prefabEntityId);
- if (sceneId === undefined) continue;
+ const prefabEntityIds = new Set(this.prefab_.entities.map(pe => pe.prefabEntityId));
+
+ const removedEntities = instanceEntities.filter(
+ e => !prefabEntityIds.has(e.prefab!.prefabEntityId)
+ );
+ for (const removed of removedEntities) {
+ const idx = this.scene_.entities.indexOf(removed);
+ if (idx !== -1) this.scene_.entities.splice(idx, 1);
+ existingByPrefabId.delete(removed.prefab!.prefabEntityId);
+ }
+
+ let nextId = computeNextEntityId(this.scene_);
+ const newIdMapping = new Map<number, number>();
+ this.addedEntityIds_ = [];
+
+ const missingEntities = this.prefab_.entities.filter(
+ pe => !existingByPrefabId.has(pe.prefabEntityId)
+ );
+ for (const pe of missingEntities) {
+ newIdMapping.set(pe.prefabEntityId, nextId++);
+ }
+
+ for (const pe of missingEntities) {
+ const sceneId = newIdMapping.get(pe.prefabEntityId)!;
+ const isRoot = pe.prefabEntityId === this.prefab_.rootEntityId;
+
+ let parent: number | null;
+ if (isRoot) {
+ parent = rootParent;
+ } else if (pe.parent !== null) {
+ parent = existingByPrefabId.get(pe.parent)?.id
+ ?? newIdMapping.get(pe.parent) ?? null;
+ } else {
+ parent = null;
+ }
+
+ const entity: EntityData = {
+ id: sceneId,
+ name: pe.name,
+ parent,
+ children: [],
+ components: pe.components.map(c => ({
+ type: c.type,
+ data: JSON.parse(JSON.stringify(c.data)),
+ })),
+ visible: pe.visible,
+ prefab: {
+ prefabPath: this.prefabPath_,
+ prefabEntityId: pe.prefabEntityId,
+ isRoot: false,
+ instanceId: this.instanceId_,
+ overrides: [],
+ },
+ };
- const entity = this.scene_.entities.find(e => e.id === sceneId);
+ this.scene_.entities.push(entity);
+ existingByPrefabId.set(pe.prefabEntityId, entity);
+ this.addedEntityIds_.push(sceneId);
+ }
+
+ for (const pe of this.prefab_.entities) {
+ const entity = existingByPrefabId.get(pe.prefabEntityId);
if (!entity) continue;
entity.name = pe.name;
@@ -171,22 +231,59 @@ export class RevertPrefabInstanceCommand extends BaseCommand {
data: JSON.parse(JSON.stringify(c.data)),
}));
+ entity.children = pe.children
+ .map(cid => existingByPrefabId.get(cid)?.id)
+ .filter((id): id is number => id !== undefined);
+
if (entity.prefab) {
entity.prefab.overrides = [];
}
}
+
+ if (rootParent !== null) {
+ const parentEntity = this.scene_.entities.find(e => e.id === rootParent);
+ if (parentEntity) {
+ for (const removed of removedEntities) {
+ parentEntity.children = parentEntity.children.filter(c => c !== removed.id);
+ }
+ }
+ }
}
undo(): void {
- for (const [entityId, saved] of this.savedEntities_) {
- const entity = this.scene_.entities.find(e => e.id === entityId);
- if (!entity) continue;
+ for (const id of this.addedEntityIds_) {
+ const idx = this.scene_.entities.findIndex(e => e.id === id);
+ if (idx !== -1) this.scene_.entities.splice(idx, 1);
+ }
+
+ const instanceEntities = this.scene_.entities.filter(
+ e => e.prefab?.instanceId === this.instanceId_
+ );
+ for (const entity of instanceEntities) {
+ const idx = this.scene_.entities.indexOf(entity);
+ if (idx !== -1) this.scene_.entities.splice(idx, 1);
+ }
+
+ const sorted = [...this.savedSnapshot_].sort(
+ (a, b) => (this.savedIndices_.get(a.id) ?? 0) - (this.savedIndices_.get(b.id) ?? 0)
+ );
+ for (const saved of sorted) {
+ const idx = this.savedIndices_.get(saved.id) ?? this.scene_.entities.length;
+ this.scene_.entities.splice(Math.min(idx, this.scene_.entities.length), 0, saved);
+ }
- entity.name = saved.name;
- entity.visible = saved.visible;
- entity.components = saved.components;
- if (saved.prefab) {
- entity.prefab = saved.prefab;
+ if (this.savedSnapshot_.length > 0) {
+ const root = this.savedSnapshot_.find(e => e.prefab?.isRoot);
+ if (root?.parent !== null && root?.parent !== undefined) {
+ const parentEntity = this.scene_.entities.find(e => e.id === root.parent);
+ if (parentEntity) {
+ const childIds = this.savedSnapshot_.filter(e => e.parent === root.parent).map(e => e.id);
+ for (const cid of childIds) {
+ if (!parentEntity.children.includes(cid)) {
+ parentEntity.children.push(cid);
+ }
+ }
+ }
}
}
}
@@ -261,7 +358,7 @@ export class ApplyPrefabOverridesCommand extends BaseCommand {
}
}
- private updateOtherInstances(sourceEntities: EntityData[]): void {
+ private updateOtherInstances(_sourceEntities: EntityData[]): void {
const otherInstanceIds = new Set<string>();
for (const entity of this.scene_.entities) {
if (entity.prefab?.prefabPath === this.prefabPath_ &&
@@ -333,3 +430,56 @@ export class ApplyPrefabOverridesCommand extends BaseCommand {
}
}
}
+
+// =============================================================================
+// InstantiateNestedPrefabCommand
+// =============================================================================
+
+export class InstantiateNestedPrefabCommand extends BaseCommand {
+ readonly type = 'instantiate_nested_prefab';
+ readonly description: string;
+
+ constructor(
+ private scene_: SceneData,
+ private createdEntities_: EntityData[],
+ private rootEntityId_: number,
+ private parentEntityId_: number | null
+ ) {
+ super();
+ this.description = 'Instantiate nested prefab';
+ }
+
+ execute(): void {
+ for (const entity of this.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(this.rootEntityId_)) {
+ parent.children.push(this.rootEntityId_);
+ }
+ }
+ }
+
+ undo(): void {
+ const idsToRemove = new Set(this.createdEntities_.map(e => e.id));
+
+ 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.rootEntityId_;
+ }
+
+ get createdEntityIds(): number[] {
+ return this.createdEntities_.map(e => e.id);
+ }
+}
diff --git a/editor/src/commands/index.ts b/editor/src/commands/index.ts
index becbd6a86..759bfa7fa 100644
--- a/editor/src/commands/index.ts
+++ b/editor/src/commands/index.ts
@@ -15,6 +15,7 @@ export {
} from './EntityCommands';
export {
InstantiatePrefabCommand,
+ InstantiateNestedPrefabCommand,
UnpackPrefabCommand,
RevertPrefabInstanceCommand,
ApplyPrefabOverridesCommand,
diff --git a/editor/src/prefab/PrefabInstantiator.ts b/editor/src/prefab/PrefabInstantiator.ts
index ef3a12284..6606f60c9 100644
--- a/editor/src/prefab/PrefabInstantiator.ts
+++ b/editor/src/prefab/PrefabInstantiator.ts
@@ -41,7 +41,7 @@ function generateInstanceId(): string {
export function instantiatePrefab(
prefab: PrefabData,
prefabPath: string,
- scene: SceneData,
+ _scene: SceneData,
parentEntityId: number | null,
nextEntityIdStart: number,
overrides: PrefabOverride[] = []
@@ -105,11 +105,19 @@ export function instantiatePrefab(
export async function instantiatePrefabRecursive(
prefabPath: string,
- scene: SceneData,
+ _scene: SceneData,
parentEntityId: number | null,
nextEntityIdStart: number,
- overrides: PrefabOverride[] = []
+ overrides: PrefabOverride[] = [],
+ visitedPaths?: Set<string>
): Promise<InstantiateResult | null> {
+ const visited = visitedPaths ?? new Set<string>();
+ if (visited.has(prefabPath)) {
+ console.warn(`Circular prefab dependency detected: ${prefabPath}`);
+ return null;
+ }
+ visited.add(prefabPath);
+
const prefab = await loadPrefabFromPath(prefabPath);
if (!prefab) return null;
@@ -136,10 +144,11 @@ export async function instantiatePrefabRecursive(
const nestedResult = await instantiatePrefabRecursive(
pe.nestedPrefab.prefabPath,
- scene,
+ _scene,
nestedParentSceneId,
nextId,
- pe.nestedPrefab.overrides
+ pe.nestedPrefab.overrides,
+ visited
);
if (nestedResult) {
@@ -244,6 +253,116 @@ function applyOverrides(entity: EntityData, overrides: PrefabOverride[]): void {
}
}
+// =============================================================================
+// Prefab Instance Sync
+// =============================================================================
+
+export async function syncPrefabInstances(scene: SceneData, prefabPath: string): Promise<boolean> {
+ let changed = false;
+
+ const prefab = await loadPrefabFromPath(prefabPath);
+ if (!prefab) return false;
+
+ const instanceGroups = new Map<string, EntityData[]>();
+ for (const entity of scene.entities) {
+ if (!entity.prefab || entity.prefab.prefabPath !== prefabPath) continue;
+ const group = instanceGroups.get(entity.prefab.instanceId) ?? [];
+ group.push(entity);
+ instanceGroups.set(entity.prefab.instanceId, group);
+ }
+
+ for (const [instanceId, instanceEntities] of instanceGroups) {
+ const root = instanceEntities.find(e => e.prefab?.isRoot);
+ if (!root) continue;
+
+ const existingByPrefabId = new Map<number, EntityData>();
+ for (const e of instanceEntities) {
+ existingByPrefabId.set(e.prefab!.prefabEntityId, e);
+ }
+
+ const prefabEntityIds = new Set(prefab.entities.map(pe => pe.prefabEntityId));
+ const newPrefabEntities = prefab.entities.filter(
+ pe => !existingByPrefabId.has(pe.prefabEntityId)
+ );
+ const removedEntities = instanceEntities.filter(
+ e => !prefabEntityIds.has(e.prefab!.prefabEntityId)
+ );
+
+ if (newPrefabEntities.length === 0 && removedEntities.length === 0) continue;
+ changed = true;
+
+ let nextId = computeNextEntityId(scene);
+ const newIdMapping = new Map<number, number>();
+ for (const pe of newPrefabEntities) {
+ newIdMapping.set(pe.prefabEntityId, nextId++);
+ }
+
+ for (const pe of newPrefabEntities) {
+ const sceneId = newIdMapping.get(pe.prefabEntityId)!;
+
+ let parent: number | null;
+ if (pe.parent !== null) {
+ parent = existingByPrefabId.get(pe.parent)?.id
+ ?? newIdMapping.get(pe.parent) ?? null;
+ } else {
+ parent = null;
+ }
+
+ const children = pe.children
+ .map(cid => existingByPrefabId.get(cid)?.id ?? newIdMapping.get(cid))
+ .filter((id): id is number => id !== undefined);
+
+ const entity: EntityData = {
+ id: sceneId,
+ name: pe.name,
+ parent,
+ children,
+ components: deepCloneComponents(pe.components),
+ visible: pe.visible,
+ prefab: {
+ prefabPath,
+ prefabEntityId: pe.prefabEntityId,
+ isRoot: false,
+ instanceId,
+ overrides: [],
+ },
+ };
+
+ applyOverrides(entity, root.prefab!.overrides);
+ scene.entities.push(entity);
+ existingByPrefabId.set(pe.prefabEntityId, entity);
+ }
+
+ for (const pe of prefab.entities) {
+ const existing = existingByPrefabId.get(pe.prefabEntityId);
+ if (!existing) continue;
+
+ const expectedChildren = pe.children
+ .map(cid => existingByPrefabId.get(cid)?.id ?? newIdMapping.get(cid))
+ .filter((id): id is number => id !== undefined);
+
+ for (const childId of expectedChildren) {
+ if (!existing.children.includes(childId)) {
+ existing.children.push(childId);
+ }
+ }
+ }
+
+ for (const removed of removedEntities) {
+ const idx = scene.entities.indexOf(removed);
+ if (idx !== -1) scene.entities.splice(idx, 1);
+
+ if (removed.parent !== null) {
+ const parent = scene.entities.find(e => e.id === removed.parent);
+ if (parent) {
+ parent.children = parent.children.filter(c => c !== removed.id);
+ }
+ }
+ }
+ }
+ return changed;
+}
+
// =============================================================================
// Helpers
// =============================================================================
diff --git a/editor/src/prefab/PrefabOverrideTracker.ts b/editor/src/prefab/PrefabOverrideTracker.ts
index 40df56809..67f8e855c 100644
--- a/editor/src/prefab/PrefabOverrideTracker.ts
+++ b/editor/src/prefab/PrefabOverrideTracker.ts
@@ -145,6 +145,63 @@ export function recordVisibilityOverride(
}
}
+export function recordComponentAddedOverride(
+ scene: SceneData,
+ entityId: number,
+ componentType: string,
+ componentData: Record<string, 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 === 'component_added' &&
+ o.componentData?.type === componentType
+ );
+
+ const override: PrefabOverride = {
+ prefabEntityId: entity.prefab.prefabEntityId,
+ type: 'component_added',
+ componentData: { type: componentType, data: JSON.parse(JSON.stringify(componentData)) },
+ };
+
+ if (existing !== -1) {
+ root.prefab.overrides[existing] = override;
+ } else {
+ root.prefab.overrides.push(override);
+ }
+}
+
+export function recordComponentRemovedOverride(
+ scene: SceneData,
+ entityId: number,
+ componentType: 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 === 'component_removed' &&
+ o.componentType === componentType
+ );
+
+ if (existing !== -1) return;
+
+ root.prefab.overrides.push({
+ prefabEntityId: entity.prefab.prefabEntityId,
+ type: 'component_removed',
+ componentType,
+ });
+}
+
export function removePropertyOverride(
scene: SceneData,
entityId: number,
diff --git a/editor/src/prefab/PrefabSerializer.ts b/editor/src/prefab/PrefabSerializer.ts
index 04c1b3007..23d44b1f5 100644
--- a/editor/src/prefab/PrefabSerializer.ts
+++ b/editor/src/prefab/PrefabSerializer.ts
@@ -7,7 +7,7 @@ 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';
+import { getGlobalPathResolver, getAssetDatabase, isUUID, getComponentRefFields } from '../asset';
// =============================================================================
// Serialization
@@ -163,6 +163,52 @@ function deepCloneComponents(components: ComponentData[]): ComponentData[] {
}));
}
+// =============================================================================
+// Asset Reference Conversion (UUID ↔ Path)
+// =============================================================================
+
+type AssetRefConverter = (value: string) => string;
+
+function convertAssetRefsInComponents(
+ components: ComponentData[],
+ converter: AssetRefConverter
+): ComponentData[] {
+ return components.map(c => {
+ const fields = getComponentRefFields(c.type);
+ if (!fields || !c.data) return { type: c.type, data: { ...c.data } };
+
+ const data = { ...c.data };
+ for (const field of fields) {
+ const value = data[field];
+ if (typeof value === 'string' && value) {
+ data[field] = converter(value);
+ }
+ }
+ return { type: c.type, data };
+ });
+}
+
+export function convertPrefabAssetRefs(
+ prefab: PrefabData,
+ converter: AssetRefConverter
+): PrefabData {
+ const entities: PrefabEntityData[] = prefab.entities.map(entity => {
+ const converted: PrefabEntityData = {
+ ...entity,
+ components: convertAssetRefsInComponents(entity.components, converter),
+ };
+ if (entity.nestedPrefab) {
+ converted.nestedPrefab = {
+ ...entity.nestedPrefab,
+ prefabPath: converter(entity.nestedPrefab.prefabPath),
+ };
+ }
+ return converted;
+ });
+
+ return { ...prefab, entities };
+}
+
// =============================================================================
// File I/O
// =============================================================================
@@ -171,12 +217,27 @@ function getNativeFS(): NativeFS | null {
return getEditorContext().fs ?? null;
}
+function resolvePathOrUuid(filePathOrUuid: string): string {
+ if (isUUID(filePathOrUuid)) {
+ return getAssetDatabase().getPath(filePathOrUuid) ?? filePathOrUuid;
+ }
+ return filePathOrUuid;
+}
+
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);
+ const resolved = resolvePathOrUuid(filePath);
+ const absolutePath = getGlobalPathResolver().toAbsolutePath(resolved);
+ const db = getAssetDatabase();
+ const converted = convertPrefabAssetRefs(prefab, (value) => {
+ if (isUUID(value)) {
+ return db.getPath(value) ?? value;
+ }
+ return value;
+ });
+ const json = serializePrefab(converted);
return fs.writeFile(absolutePath, json);
}
@@ -184,12 +245,20 @@ export async function loadPrefabFromPath(filePath: string): Promise<PrefabData |
const fs = getNativeFS();
if (!fs) return null;
- const absolutePath = getGlobalPathResolver().toAbsolutePath(filePath);
+ const resolved = resolvePathOrUuid(filePath);
+ const absolutePath = getGlobalPathResolver().toAbsolutePath(resolved);
try {
const content = await fs.readFile(absolutePath);
if (!content) return null;
- return deserializePrefab(content);
+ const prefab = deserializePrefab(content);
+ const db = getAssetDatabase();
+ return convertPrefabAssetRefs(prefab, (value) => {
+ if (!isUUID(value)) {
+ return db.getUuid(value) ?? value;
+ }
+ return value;
+ });
} 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
index 5fb365043..2959bcc93 100644
--- a/editor/src/prefab/index.ts
+++ b/editor/src/prefab/index.ts
@@ -11,12 +11,14 @@ export {
sceneDataToPrefab,
savePrefabToPath,
loadPrefabFromPath,
+ convertPrefabAssetRefs,
type EntityTreeToPrefabResult,
} from './PrefabSerializer';
export {
instantiatePrefab,
instantiatePrefabRecursive,
+ syncPrefabInstances,
computeNextEntityId,
type InstantiateResult,
} from './PrefabInstantiator';
@@ -28,5 +30,7 @@ export {
recordPropertyOverride,
recordNameOverride,
recordVisibilityOverride,
+ recordComponentAddedOverride,
+ recordComponentRemovedOverride,
removePropertyOverride,
} from './PrefabOverrideTracker';