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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(prefab/editor): order-independent flatten + return-flow & ref polish
esengine0f7169690f71
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex ff9fd847a..aa414711a 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -6,6 +6,7 @@ import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types'import { EditorHistory, EditorHistoryImpl } from './EditorHistory';import { SceneModel, SceneModelImpl, type PrefabInstanceTag } from './SceneModel';import { SceneStore } from './SceneStore';+import { usePrefabConflicts } from '@/store/prefabConflicts';import { ViewportController } from './ViewportController';import { expandInstance } from './PrefabInstance';import { setEntityClipboard, getEntityClipboard, remapClipboardEntities } from './entityClipboard';@@ -863,12 +864,18 @@ export class SceneCommandsImpl {if (tag) saved.push([id as EntityId, tag]);}if (saved.length === 0) return;+ // A load-time stale-override diagnostic keyed by this instance root is moot once+ // the subtree is no longer an instance; clear it (and its count) on unpack, and+ // restore it on undo so the badge tracks the tree state accurately.+ const conflicts = usePrefabConflicts.getState().byInstance.get(instanceRoot);const unlink = (): void => {for (const [id] of saved) this.model.setPrefabTag(id, undefined);+ usePrefabConflicts.getState().clearInstance(instanceRoot);SceneStore.pokeStructure();};const relink = (): void => {for (const [id, tag] of saved) this.model.setPrefabTag(id, tag);+ if (conflicts) usePrefabConflicts.getState().setInstance(instanceRoot, conflicts);SceneStore.pokeStructure();};unlink();diff --git a/desktop/src/i18n/messages/details.ts b/desktop/src/i18n/messages/details.tsindex 5068aaffd..af539e4bc 100644--- a/desktop/src/i18n/messages/details.ts+++ b/desktop/src/i18n/messages/details.ts@@ -201,6 +201,8 @@ export const detailsMessages = defineMessages({'det.editingShared': { en: '{count} entities · shared components', zh: '{count} 个实体 · 共同组件' },'det.id': { en: 'ID', zh: 'ID' },'det.entityNone': { en: 'None', zh: '无' },+ 'det.entityMissing': { en: '#{id} (missing)', zh: '#{id}(已丢失)' },+ 'det.entityMissingTip': { en: 'The referenced entity no longer exists — pick a new target or clear it.', zh: '引用的实体已不存在——请重新选择目标或清除。' },'det.prefabEdit': { en: 'Edit', zh: '编辑' },'det.prefabEditTip': { en: 'Open this prefab in Prefab Mode', zh: '在预制体模式中打开此预制体' },'det.staleOverrides': {diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex b80421e70..d357b1a16 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -288,6 +288,9 @@ export function EntityControl({const pop = usePopover();const trigger = useRef<HTMLButtonElement>(null);const [q, setQ] = useState('');+ // Track scene-model changes so the trigger label reflects a bound target's+ // CURRENT name (rename elsewhere) — not just a stale snapshot from the last open.+ useSyncExternalStore(SceneStore.subscribe, SceneStore.getRevision);// The scene's entities (source id + name) — rebuilt each open so it's current.// Source id 0 (== INVALID_ENTITY) is excluded: a ref to it can't be told apart// from "unset", so it isn't a bindable target.@@ -298,8 +301,17 @@ export function EntityControl({// eslint-disable-next-line react-hooks/exhaustive-deps[pop.isOpen],);- const cur = options.find((o) => o.id === value);- const label = mixed ? '—' : isUnsetEntity(value) ? t('det.entityNone') : cur?.name ?? `#${value}`;+ // Resolve the bound target against the LIVE model each render, so a rename shows+ // immediately and a ref to a since-deleted entity reads as missing (not a bare #id).+ const cur = (SceneModel.current?.entities ?? []).find((e) => e.id === value && !isUnsetEntity(e.id));+ const isDangling = !mixed && !isUnsetEntity(value) && !cur;+ const label = mixed+ ? '—'+ : isUnsetEntity(value)+ ? t('det.entityNone')+ : cur+ ? cur.name || `#${cur.id}`+ : t('det.entityMissing', { id: value });const ql = q.trim().toLowerCase();const filtered = ql ? options.filter((o) => o.name.toLowerCase().includes(ql)) : options;const close = () => {@@ -318,8 +330,9 @@ export function EntityControl({};return (<span className="field dropdown">- <button ref={trigger} type="button" className="dd-trigger" onMouseDown={(e) => e.stopPropagation()} onClick={toggle}>- <span className={`dd-val${mixed || isUnsetEntity(value) ? ' dd-none' : ''}`}>{mixed ? '—' : label}</span>+ <button ref={trigger} type="button" className="dd-trigger" onMouseDown={(e) => e.stopPropagation()} onClick={toggle}+ title={isDangling ? t('det.entityMissingTip') : undefined}>+ <span className={`dd-val${mixed || isUnsetEntity(value) || isDangling ? ' dd-none' : ''}`}>{mixed ? '—' : label}</span><ChevronDown size={12} strokeWidth={2} /></button>{pop.anchor && (diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 1b99b34c3..c7c5e35e2 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -222,6 +222,9 @@ class ProjectStoreImpl {/** Editor camera at enter, restored on exit so "Back to Scene" returns the* user to the exact view they left instead of reframing to the scene camera. */returnView: { x: number; y: number; orthoSize: number } | null;+ /** Scene entity selected at enter (the instance you came from) — re-selected on+ * exit. Scene entity ids are stable across the reload, so this survives it. */+ returnSelection: number | null;/** When editing a VARIANT: its base asset + ref. Save collapses the edited* tree against this base into a variant delta (preserving basePrefab), rather* than extracting a flat prefab. Null for an ordinary (flat) prefab. */@@ -2006,6 +2009,9 @@ class ProjectStoreImpl {// session's — its currentScene is null), so "Back" always lands in the scene.const returnScene = this.prefabSession?.returnScene ?? st.currentScene;const returnView = this.prefabSession?.returnView ?? EngineHost.editorViewState();+ // The instance we entered from — captured before adopt clears selection, so+ // "Back to Scene" re-selects it (Unity/Godot behaviour).+ const returnSelection = this.prefabSession?.returnSelection ?? useSelection.getState().selectedId ?? null;// Flatten the asset into ordinary entities; remember each entity's stable id.// A variant resolves its base through the warm-cache resolver (loadPrefabAsset@@ -2036,7 +2042,7 @@ class ProjectStoreImpl {requestAnimationFrame(() => requestAnimationFrame(frameContent));const returnLeaf = returnScene ? (returnScene.split('/').pop() ?? returnScene) : null;const baseRef = prefab.basePrefab ?? null;- this.prefabSession = { ref, path, name: prefab.name, rootSource: rootId, idBySource, returnScene, returnView, base, baseRef };+ this.prefabSession = { ref, path, name: prefab.name, rootSource: rootId, idBySource, returnScene, returnView, returnSelection, base, baseRef };this.store.setState({ project: { ...st, currentScene: null, prefabEdit: { name: prefab.name, path, returnScene: returnLeaf, isVariant: !!baseRef } } });Toasts.push(t('proj.openedPrefab', { name: prefab.name }), 'info', 1600);}@@ -2136,7 +2142,7 @@ class ProjectStoreImpl {async exitPrefabMode(): Promise<void> {if (!this.prefabSession) return;if (!(await confirmDiscard(t('discard.exitPrefab')))) return;- const { returnScene: back, returnView } = this.prefabSession;+ const { returnScene: back, returnView, returnSelection } = this.prefabSession;this.prefabSession = null;const st = this.state;if (st) this.store.setState({ project: { ...st, prefabEdit: null } });@@ -2149,6 +2155,10 @@ class ProjectStoreImpl {// Reframe to where the user was before entering (openScene reseeds the view// from the scene camera; this puts their pan/zoom back).if (returnView) EngineHost.setEditorView(returnView);+ // Re-select the instance we came from — its scene id survived the reload.+ if (returnSelection != null && SceneModel.current?.entities.some((e) => e.id === returnSelection)) {+ useSelection.getState().select(returnSelection);+ }Toasts.push(t('proj.returnedScene', { name: back.split('/').pop() ?? back }), 'info', 1600);} catch {await this.newScene();diff --git a/desktop/src/store/prefabConflicts.ts b/desktop/src/store/prefabConflicts.tsindex ee3bccda0..e11e92655 100644--- a/desktop/src/store/prefabConflicts.ts+++ b/desktop/src/store/prefabConflicts.ts@@ -20,6 +20,8 @@ interface PrefabConflictState {setAll: (byInstance: Map<number, StaleOverride[]>) => void;/** Forget one instance's conflicts (after it's repaired / its subtree removed). */clearInstance: (rootId: number) => void;+ /** Restore one instance's conflicts (undo of the removal that cleared them). */+ setInstance: (rootId: number, overrides: StaleOverride[]) => void;clear: () => void;}@@ -40,5 +42,12 @@ export const usePrefabConflicts = create<PrefabConflictState>((set) => ({byInstance.delete(rootId);return { byInstance, total: countAll(byInstance) };}),+ setInstance: (rootId, overrides) =>+ set((s) => {+ if (overrides.length === 0) return s;+ const byInstance = new Map(s.byInstance);+ byInstance.set(rootId, overrides);+ return { byInstance, total: countAll(byInstance) };+ }),clear: () => set({ byInstance: new Map(), total: 0 }),}));diff --git a/sdk/src/prefab/flatten.ts b/sdk/src/prefab/flatten.tsindex 09a766723..1c600cfc0 100644--- a/sdk/src/prefab/flatten.ts+++ b/sdk/src/prefab/flatten.ts@@ -153,6 +153,32 @@ export function flattenPrefab();}+ // Second pass: heal top-level parent/child links now that idMapping is+ // complete. A nested SLOT's runtime id is only known after its own flatten, so+ // an entity parented to a slot that appears LATER in a non-tree-ordered+ // `entities` array resolved to null (and dropped from the slot's children) in+ // the loop above. Re-resolve every top-level link so flatten is order-independent;+ // for a tree-ordered file every link already matches and this is a no-op.+ const byRuntimeId = new Map(result.map((e) => [e.id, e]));+ for (const pe of prefab.entities) {+ if (pe.prefabEntityId === prefab.rootEntityId) continue;+ const childId = idMapping.get(pe.prefabEntityId);+ if (childId === undefined) continue;+ const entity = byRuntimeId.get(childId);+ if (!entity) continue;+ const wantParent = pe.parent !== null ? (idMapping.get(pe.parent) ?? null) : null;+ if (entity.parent === wantParent) continue;+ if (entity.parent != null) {+ const old = byRuntimeId.get(entity.parent);+ if (old) old.children = old.children.filter((c) => c !== childId);+ }+ entity.parent = wantParent;+ if (wantParent != null) {+ const np = byRuntimeId.get(wantParent);+ if (np && !np.children.includes(childId)) np.children.push(childId);+ }+ }+return { entities: result, rootId };}diff --git a/sdk/tests/prefab-rigor.test.ts b/sdk/tests/prefab-rigor.test.tsindex 45c4b9b85..61db65a9e 100644--- a/sdk/tests/prefab-rigor.test.ts+++ b/sdk/tests/prefab-rigor.test.ts@@ -870,6 +870,31 @@ describe('hierarchical addressing', () => {});});+// ─── flatten order-independence (outer child on a later nested slot) ───────++describe('flatten order-independence', () => {+ it('an outer entity parented to a LATER nested slot still resolves (not detached)', () => {+ const turret = leafPrefab('Turret');+ const prefab: PrefabData = {+ version: PREFAB_FORMAT_VERSION, name: 'Ship', rootEntityId: 'ship',+ entities: [+ { prefabEntityId: 'ship', name: 'Ship', parent: null, children: ['slot'], components: [], visible: true },+ // 'badge' is parented to the slot but appears BEFORE it in the array,+ // so the main loop can't resolve the slot's (not-yet-flattened) id.+ { prefabEntityId: 'badge', name: 'Badge', parent: 'slot', children: [], components: [], visible: true },+ { prefabEntityId: 'slot', name: 'Slot', parent: 'ship', children: ['badge'], components: [], visible: true,+ nestedPrefab: { prefabPath: 'turret', overrides: [] } },+ ],+ };+ const { entities } = flattenPrefab(prefab, [], ctxWith({ turret }));+ const byAddr = new Map(entities.map((e) => [e.prefabEntityId, e]));+ const badge = byAddr.get('badge')!;+ const slotRoot = byAddr.get('slot/0')!; // the nested turret's root = the slot's runtime id+ expect(badge.parent).toBe(slotRoot.id); // healed, not null+ expect(slotRoot.children).toContain(badge.id);+ });+});+// ─── Nested-instance delta round-trip (override on a nested entity) ─────────describe('nested-instance delta', () => {