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
feat(editor): lossless save via JSON-first dual-write (serialization L3+L4)
esengine054d248cfb72
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex 17bb8623d..a204228f8 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -33,8 +33,8 @@ export function App() {if (ok) store.select(null); // entity ids change on load — drop stale selection});} else if (mod && key === 's') {- // Save (E7-4): ⌘S overwrites the current scene; ⇧⌘S is Save-As. ⌘S- // falls back to Save-As when overwrite is blocked (lossy / no scene).+ // Save (E7-4): ⌘S overwrites the current scene (lossless, JSON-first);+ // ⇧⌘S is Save-As. ⌘S falls back to Save-As when there's no current scene.e.preventDefault();if (e.shiftKey) void ProjectStore.saveAsViaDialog();else void ProjectStore.save().catch(() => ProjectStore.saveAsViaDialog());diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 5ec38f6d4..5cf22b4a5 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -3,6 +3,7 @@ import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types'import { EngineHost } from './EngineHost';import { EditorHistory } from './EditorHistory';import { EntityHandles } from './EntityHandles';+import { SceneModel } from './SceneModel';import { SceneQuery } from './SceneQuery';import { componentByName, angleZToQuat, hexToRgb, prettyLabel, type WorldT } from './schema';@@ -122,6 +123,12 @@ function applyFieldWrite(}world.set(entity, def, next as unknown as Parameters<WorldT['set']>[2]);+ // Dual-write to the source-of-truth model (JSON-first L3). next[key] is the+ // SceneData-format value for this key; writing just the key preserves the+ // model component's other fields — including @uuid: asset refs and+ // schema-extra fields the World can't hold. Every field edit AND its undo/redo+ // route through here, so the model stays in sync for free.+ SceneModel.setField(entity, compName, key, next[key]);}export const SceneCommands = {@@ -202,6 +209,11 @@ export const SceneCommands = {// — Undoable entity lifecycle. Re-creating an entity changes its engine id,// so closures track a stable EntityHandle and resolve it live. —+ // Each lifecycle op dual-writes the source-of-truth model (JSON-first L3),+ // keyed by a stable source id so undo/redo (which re-create entities under new+ // runtime ids) keep the model in sync. The model holds the lossless record;+ // the World is the projection.+/** Spawn a new empty entity (with a Transform). Returns its id. */addEntity(): EntityId | null {const world = EngineHost.mutableWorld();@@ -210,12 +222,22 @@ export const SceneCommands = {world.insert(e, Transform, DEFAULT_TRANSFORM);const cap = captureEntity(world, e);const handle = EntityHandles.acquire(e);+ const sourceId = SceneModel.addEntity(e, 'Entity', [+ { type: 'Transform', data: structuredClone(DEFAULT_TRANSFORM) },+ ]);+ let modelCap: ReturnType<typeof SceneModel.removeEntityBySource>;EditorHistory.record('Add Entity',() => {- if (cap) EntityHandles.rebind(handle, recreateEntity(world, cap));+ if (!cap) return;+ const nw = recreateEntity(world, cap);+ EntityHandles.rebind(handle, nw);+ if (modelCap) SceneModel.restoreEntity(modelCap, nw);+ },+ () => {+ despawnHandle(world, handle);+ modelCap = SceneModel.removeEntityBySource(sourceId);},- () => despawnHandle(world, handle),);return e;},@@ -227,12 +249,22 @@ export const SceneCommands = {const cap = captureEntity(world, id);if (!cap) return;const handle = EntityHandles.acquire(id);+ const sourceId = SceneModel.sourceFor(id);+ // Capture the FULL model record (incl. unknown components) for lossless undo.+ const modelCap = sourceId !== undefined ? SceneModel.removeEntityBySource(sourceId) : undefined;world.despawn(id);EntityHandles.rebind(handle, null);EditorHistory.record(`Delete ${cap.name || 'Entity'}`,- () => despawnHandle(world, handle),- () => EntityHandles.rebind(handle, recreateEntity(world, cap)),+ () => {+ despawnHandle(world, handle);+ if (sourceId !== undefined) SceneModel.removeEntityBySource(sourceId);+ },+ () => {+ const nw = recreateEntity(world, cap);+ EntityHandles.rebind(handle, nw);+ if (modelCap) SceneModel.restoreEntity(modelCap, nw);+ },);},@@ -250,10 +282,38 @@ export const SceneCommands = {}const dup = recreateEntity(world, cap);const handle = EntityHandles.acquire(dup);+ // The model copy is from the SOURCE model entity (preserves unknown+ // components/fields the World cap can't carry), with the same offset.+ const srcId = SceneModel.sourceFor(id);+ const srcEntity = srcId !== undefined+ ? SceneModel.current?.entities.find((e) => e.id === srcId)+ : undefined;+ const dupComponents = srcEntity+ ? (structuredClone(srcEntity.components) as typeof srcEntity.components)+ : cap.comps.map((c) => ({+ type: c.name,+ data: structuredClone(c.data) as Record<string, unknown>,+ }));+ const mpos = (dupComponents.find((c) => c.type === 'Transform')?.data as+ | { position?: { x: number; y: number } }+ | undefined)?.position;+ if (mpos) {+ mpos.x += 24;+ mpos.y -= 24;+ }+ const newSourceId = SceneModel.addEntity(dup, srcEntity?.name ?? cap.name, dupComponents);+ let modelCap: ReturnType<typeof SceneModel.removeEntityBySource>;EditorHistory.record(`Duplicate ${cap.name || 'Entity'}`,- () => EntityHandles.rebind(handle, recreateEntity(world, cap)),- () => despawnHandle(world, handle),+ () => {+ const nw = recreateEntity(world, cap);+ EntityHandles.rebind(handle, nw);+ if (modelCap) SceneModel.restoreEntity(modelCap, nw);+ },+ () => {+ despawnHandle(world, handle);+ modelCap = SceneModel.removeEntityBySource(newSourceId);+ },);return dup;},@@ -267,7 +327,10 @@ export const SceneCommands = {const handle = EntityHandles.acquire(id);const setName = (value: string) => {const live = EntityHandles.liveId(handle);- if (live != null && world.valid(live)) world.insert(live, Name, { value });+ if (live != null && world.valid(live)) {+ world.insert(live, Name, { value });+ SceneModel.setName(live, value);+ }};setName(name);EditorHistory.record(`Rename ${name || 'Entity'}`, () => setName(name), () => setName(before));diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.tsindex 88299efef..5ddec2e36 100644--- a/desktop/src/engine/SceneModel.ts+++ b/desktop/src/engine/SceneModel.ts@@ -2,6 +2,7 @@ import type { SceneData } from 'esengine';import type { EntityId } from '@/types';type SceneEntity = SceneData['entities'][number];+type SceneComponent = SceneEntity['components'][number];/*** The editor's source-of-truth scene data model — JSON-first (REARCH_SERIALIZATION.md, L1).@@ -22,6 +23,8 @@ class SceneModelImpl {private readonly runtimeToSource = new Map<EntityId, number>();/** source entity id → runtime World entity (absent for visible:false / unspawned). */private readonly sourceToRuntime = new Map<number, EntityId>();+ /** Allocator for source ids of entities created after load (added/duplicated). */+ private nextSourceId = 1;/*** Adopt a freshly-loaded scene as the editor truth.@@ -32,6 +35,9 @@ class SceneModelImpl {this.data = loaded;this.runtimeToSource.clear();this.sourceToRuntime.clear();+ let maxId = 0;+ for (const e of loaded.entities) if (e.id > maxId) maxId = e.id;+ this.nextSourceId = maxId + 1;for (const [sourceId, runtime] of entityMap) {this.sourceToRuntime.set(sourceId, runtime);this.runtimeToSource.set(runtime, sourceId);@@ -42,6 +48,66 @@ class SceneModelImpl {this.data = null;this.runtimeToSource.clear();this.sourceToRuntime.clear();+ this.nextSourceId = 1;+ }++ // ── Mutations (JSON-first L3) ────────────────────────────────────────────+ // SceneCommands dual-writes here alongside the World so the model stays the+ // lossless truth. Field edits address the live runtime entity; entity+ // lifecycle addresses the stable source id (survives undo/redo recreates,+ // where the runtime id changes). All are no-ops if no scene is loaded.++ /**+ * Update one field of a component on a runtime entity's source record.+ * Preserves every other field — including `@uuid:` asset refs and schema-extra+ * fields the World can't hold — so the model stays lossless. Mirrors the+ * per-key value SceneCommands writes to the World.+ */+ setField(runtime: EntityId, compType: string, key: string, value: unknown): void {+ const e = this.sourceEntity(runtime);+ if (!e) return;+ let comp = e.components.find((c) => c.type === compType);+ if (!comp) {+ comp = { type: compType, data: {} } as SceneComponent;+ e.components.push(comp);+ }+ (comp.data as Record<string, unknown>)[key] = value;+ }++ /** Set a runtime entity's name (stored top-level in SceneData, not as a component). */+ setName(runtime: EntityId, name: string): void {+ const e = this.sourceEntity(runtime);+ if (e) e.name = name;+ }++ /** Add a new source entity (for a freshly-spawned runtime entity). Returns its source id. */+ addEntity(runtime: EntityId, name: string, components: SceneComponent[]): number {+ const id = this.nextSourceId++;+ if (this.data) this.data.entities.push({ id, name, parent: null, children: [], components });+ this.bindRuntime(id, runtime);+ return id;+ }++ /** Remove + return a source entity by id (kept by undo closures to restore later). */+ removeEntityBySource(sourceId: number): SceneEntity | undefined {+ const rt = this.sourceToRuntime.get(sourceId);+ if (rt !== undefined) this.runtimeToSource.delete(rt);+ this.sourceToRuntime.delete(sourceId);+ if (!this.data) return undefined;+ const idx = this.data.entities.findIndex((e) => e.id === sourceId);+ return idx >= 0 ? this.data.entities.splice(idx, 1)[0] : undefined;+ }++ /** Re-insert a previously-removed source entity, bound to a (re-created) runtime entity. */+ restoreEntity(entity: SceneEntity, runtime: EntityId): void {+ if (this.data) this.data.entities.push(entity);+ this.bindRuntime(entity.id, runtime);+ }++ /** Point a source id at its current runtime entity (call after a recreate). */+ bindRuntime(sourceId: number, runtime: EntityId): void {+ this.sourceToRuntime.set(sourceId, runtime);+ this.runtimeToSource.set(runtime, sourceId);}/** The current scene truth, or null if none loaded. */@@ -49,6 +115,11 @@ class SceneModelImpl {return this.data;}+ /** A deep clone of the scene truth, for lossless save (JSON-first L4). */+ serialize(): SceneData | null {+ return this.data ? (JSON.parse(JSON.stringify(this.data)) as SceneData) : null;+ }+/** The source entity record backing a runtime World entity, if tracked. */sourceEntity(runtime: EntityId): SceneEntity | undefined {const sourceId = this.runtimeToSource.get(runtime);diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 1138f4966..5b5282223 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -1,4 +1,4 @@-import { resetWorldTo, serializeScene, getComponent, getComponentAssetFields, Assets } from 'esengine';+import { resetWorldTo, getComponent, Assets } from 'esengine';import type { SceneData } from 'esengine';import { EngineHost } from '@/engine/EngineHost';import { SceneModel } from '@/engine/SceneModel';@@ -32,13 +32,6 @@ interface ProjectState {defaultScene?: string;/** The scene currently loaded into the world (project-relative path). */currentScene: string | null;- /**- * True if the loaded scene carried component types this editor's engine has- * not registered (its `src/` code isn't loaded) — they were dropped on load,- * so overwriting the source file would lose them. Blocks overwrite-save until- * project code loading lands; Save-As to a new file stays available.- */- lossy: boolean;}/** Component types in `data` that the engine doesn't know — dropped on load. */@@ -84,8 +77,6 @@ function mapAssetRefs(value: unknown, resolve: (uuid: string) => number): unknowclass ProjectStoreImpl {private state: ProjectState | null = null;private readonly listeners = new Set<() => void>();- /** Texture GL handle → asset uuid for the loaded scene; reverses refs on save. */- private handleToUuid = new Map<number, string>();subscribe = (fn: () => void): (() => void) => {this.listeners.add(fn);@@ -147,7 +138,6 @@ class ProjectStoreImpl {workspace: opened.workspace,defaultScene: opened.manifest.defaultScene,currentScene: null,- lossy: false,};this.emit();}@@ -167,9 +157,9 @@ class ProjectStoreImpl {const dropped = unknownComponentTypes(raw);if (dropped.length > 0) {console.warn(- `[project] scene "${rel}" uses components this editor hasn't loaded ` +- `(${dropped.join(', ')}); they are dropped on load — overwrite-save is ` +- `blocked until project code loading lands. Use Save As.`,+ `[project] scene "${rel}" uses components this editor's engine hasn't ` ++ `loaded (${dropped.join(', ')}); they don't render in the viewport, but ` ++ `are preserved verbatim in the source-of-truth model and on save (JSON-first).`,);}const data = await this.resolveTextures(raw);@@ -178,11 +168,11 @@ class ProjectStoreImpl {// resetWorldTo returns source-id → runtime entity. Adopt the raw scene// (with @uuid: refs + any components/fields/invisible entities the World// drops) as the editor's source of truth (REARCH_SERIALIZATION.md L1).- // The World is a lossy projection; the model is what L4 will save.+ // The World is a lossy projection; the model is what save() serializes.const entityMap = resetWorldTo(world, data);SceneModel.adopt(raw, entityMap);}- this.state = { ...st, currentScene: rel, lossy: dropped.length > 0 };+ this.state = { ...st, currentScene: rel };this.emit();}@@ -195,7 +185,6 @@ class ProjectStoreImpl {private async resolveTextures(raw: SceneData): Promise<SceneData> {const st = this.state;const bridge = window.estella;- this.handleToUuid = new Map();if (!st) return raw;const referenced = new Set<string>();@@ -229,7 +218,6 @@ class ProjectStoreImpl {try {const { handle } = await assets.loadTexture(`estella://project/${rel}`);uuidToHandle.set(uuid, handle);- this.handleToUuid.set(handle, uuid);} catch (err) {console.warn('[project] texture load failed', rel, err);}@@ -238,28 +226,16 @@ class ProjectStoreImpl {return mapAssetRefs(raw, (uuid) => uuidToHandle.get(uuid) ?? 0) as SceneData;}- /** Serialize the live world; map texture handles back to `@uuid:` (portable). */+ /**+ * Serialize the editor's source-of-truth model — lossless (JSON-first L4).+ * The model retains everything the World drops (unknown components/fields,+ * invisible entities, `@uuid:` asset refs), so this no longer reads from the+ * World and needs no handle→uuid restoration.+ */private serializeCurrent(): SceneData {- const world = EngineHost.mutableWorld();- if (!world) throw new Error('engine not ready');- return this.restoreAssetRefs(serializeScene(world, this.state?.name ?? 'scene'));- }-- /** Replace texture-handle values in asset fields with their `@uuid:` refs. */- private restoreAssetRefs(data: SceneData): SceneData {- if (this.handleToUuid.size === 0) return data;- for (const entity of data.entities ?? []) {- for (const comp of entity.components ?? []) {- const cdata = comp.data as Record<string, unknown>;- for (const field of getComponentAssetFields(comp.type)) {- const v = cdata[field];- if (typeof v === 'number' && this.handleToUuid.has(v)) {- cdata[field] = `${UUID_PREFIX}${this.handleToUuid.get(v)}`;- }- }- }- }- return data;+ const model = SceneModel.serialize();+ if (!model) throw new Error('no scene loaded');+ return { ...model, name: this.state?.name ?? model.name };}private async writeScene(relPath: string, data: SceneData): Promise<void> {@@ -276,19 +252,13 @@ class ProjectStoreImpl {}/**- * Overwrite the current scene file. Refuses when the load was lossy (would- * clobber components this editor dropped) — the caller should fall back to- * {@link saveAsViaDialog}.+ * Overwrite the current scene file — now lossless (JSON-first L4): the saved+ * data comes from the source-of-truth model, which preserves components this+ * editor's engine never loaded. The old lossy overwrite-block is gone.*/async save(): Promise<void> {const st = this.state;if (!st || !st.currentScene) throw new Error('no scene to save');- if (st.lossy) {- throw new Error(- 'overwrite-save blocked: the scene has components this editor did not ' +- 'load (they would be lost). Use Save As to write a new file.',- );- }await this.writeScene(st.currentScene, this.serializeCurrent());await this.persistLastScene(st.currentScene);}diff --git a/desktop/tests/engine-model-sync.test.ts b/desktop/tests/engine-model-sync.test.tsnew file mode 100644index 000000000..f1f83e220--- /dev/null+++ b/desktop/tests/engine-model-sync.test.ts@@ -0,0 +1,119 @@+/**+ * @file JSON-first L3/L4 payoff: SceneCommands dual-write keeps the source-of-+ * truth model in sync with the World, and the model serializes LOSSLESSLY+ * — unknown components/fields the World drops survive an edit→save round+ * trip (the case the old `lossy` flag refused to save).+ */+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';+import { App, Transform, resetWorldTo } from 'esengine';+import type { ESEngineModule, SceneData } from 'esengine';+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';++const host = vi.hoisted(() => ({ world: null as unknown as App['world'] }));+vi.mock('@/engine/EngineHost', () => ({+ EngineHost: {+ mutableWorld: () => host.world,+ get world() {+ return host.world;+ },+ getResource: () => undefined,+ },+}));++import { SceneCommands } from '@/engine/SceneCommands';+import { SceneModel } from '@/engine/SceneModel';+import { EditorHistory } from '@/engine/EditorHistory';++function sceneWithUnknown(): SceneData {+ return {+ version: '1.0',+ name: 'lossless',+ entities: [+ {+ id: 1,+ name: 'Hero',+ parent: null,+ children: [],+ components: [+ {+ type: 'Transform',+ data: {+ position: { x: 0, y: 0, z: 0 },+ rotation: { w: 1, x: 0, y: 0, z: 0 },+ scale: { x: 1, y: 1, z: 1 },+ },+ },+ { type: 'WaveMotion', data: { amplitude: 5, phase: 1.5 } }, // unknown to the engine+ ],+ },+ ],+ } as unknown as SceneData;+}++describe.skipIf(!HAS_WASM)('JSON-first dual-write + lossless save (L3/L4)', () => {+ let module: ESEngineModule;+ let runtime1: number;+ beforeAll(async () => {+ module = await loadWasmModule();+ });+ beforeEach(() => {+ const app = App.new();+ app.connectCpp(new module.Registry() as never, module);+ host.world = app.world;+ EditorHistory.clear();+ SceneModel.clear();+ // Project the scene into the World (lossy) and adopt it as the model (lossless).+ const map = resetWorldTo(host.world, structuredClone(sceneWithUnknown()) as never);+ SceneModel.adopt(structuredClone(sceneWithUnknown()), map as Map<number, number>);+ runtime1 = map.get(1)!;+ // The World dropped the unknown component; the model kept it.+ expect(host.world.has(runtime1, Transform)).toBe(true);+ });++ it('setField edits the World AND the model, preserving the unknown component', () => {+ SceneCommands.setField(runtime1, 'Transform', 'position', 'vec3', [9, 8, 7]);++ // World reflects the edit:+ expect(host.world.get(runtime1, Transform).position).toMatchObject({ x: 9, y: 8, z: 7 });++ // Model (the save truth) reflects the edit AND still has the unknown component:+ const saved = SceneModel.serialize()!;+ const hero = saved.entities.find((e) => e.id === 1)!;+ const t = hero.components.find((c) => c.type === 'Transform')!.data as {+ position: { x: number };+ };+ expect(t.position.x).toBe(9);+ const wave = hero.components.find((c) => c.type === 'WaveMotion');+ expect(wave).toBeDefined();+ expect((wave!.data as { amplitude: number }).amplitude).toBe(5);+ });++ it('undo of a field edit reverts the model too', () => {+ SceneCommands.setField(runtime1, 'Transform', 'position', 'vec3', [9, 0, 0]);+ EditorHistory.undo();+ const hero = SceneModel.serialize()!.entities.find((e) => e.id === 1)!;+ const t = hero.components.find((c) => c.type === 'Transform')!.data as {+ position: { x: number };+ };+ expect(t.position.x).toBe(0);+ });++ it('addEntity / undo is reflected in the model', () => {+ const before = SceneModel.serialize()!.entities.length;+ SceneCommands.addEntity();+ expect(SceneModel.serialize()!.entities.length).toBe(before + 1);+ EditorHistory.undo();+ expect(SceneModel.serialize()!.entities.length).toBe(before);+ });++ it('delete then undo preserves the unknown component (lossless undo)', () => {+ SceneCommands.deleteEntity(runtime1);+ expect(SceneModel.serialize()!.entities.length).toBe(0);++ EditorHistory.undo();+ const saved = SceneModel.serialize()!;+ expect(saved.entities.length).toBe(1);+ // the restored entity still carries the unknown component:+ expect(saved.entities[0].components.some((c) => c.type === 'WaveMotion')).toBe(true);+ });+});diff --git a/docs/REARCH_SERIALIZATION.md b/docs/REARCH_SERIALIZATION.mdindex a83327186..12a51ccc9 100644--- a/docs/REARCH_SERIALIZATION.md+++ b/docs/REARCH_SERIALIZATION.md@@ -90,13 +90,15 @@ JSON-first 是**编辑器核心的较大改造**:`SceneCommands`(~13 个写方## 4. 迁移序(可拆、每步可验证)- **L0(引擎侧,独立可先做,低风险)**:asset 反向映射下沉 SDK(`Assets` 建 `handle→ref`,`serializeScene` 加 `refResolver` 注入)。即便不上 JSON-first,也立刻让 `serializeScene` 不再丢 material/font 的 uuid;编辑器删 `restoreAssetRefs` 私补。验证:含 texture/material/font 引用的场景 world→JSON 往返,asset 字段为 `@uuid:` 而非裸数字。-- **L1(数据模型持有)**:`ProjectStore` load 后**保留** SceneData(连同未知组件/字段/visible/textureMetadata),不再投影即弃;加稳定 editor id。验证:load 一个含未知组件的场景,数据模型完整(未知组件在)。-- **L2(增量投影层)**:数据模型 → world 的投影 + 增量 patch(改一个字段/增删实体 → 局部更新 world 预览,不全量 resetWorldTo)。验证:编辑数据模型 → 视口即时反映、不闪、play 状态不丢、id 不漂。-- **L3(命令改道)**:`SceneCommands` 写数据模型(承接 E2 边界)+ 触发 L2 投影;`SceneQuery`/inspector 读数据模型。验证:所有编辑路径行为不变(回归)+ 未知组件/字段在编辑期始终保留。-- **L4(无损保存)**:`save` = 序列化数据模型(非 `serializeScene(world)`);删 `lossy` 标志 + 拒绝逻辑 + `restoreAssetRefs`。验证:**golden 往返**——load→save **逐字段一致**(含未知组件、未知字段、visible、asset `@uuid:`、textureMetadata、double 精度)。-- **L5(play 快照取数据模型)**:`EngineHost.setRunMode` 快照数据模型而非 `serializeScene(world)`;Stop 恢复数据模型。验证:play→编辑大量改动→stop,场景逐字段还原;接 play==ship。+- **L1(数据模型持有,已做)**:`SceneModel` 在 load 后保留完整 SceneData 为真相(未知组件/字段/visible/`@uuid:`)+ 模型⇄运行时 id 映射(取自 `resetWorldTo` 的返回 map)。`ProjectStore.loadCurrentScene` adopt。+- **~~L2(独立增量投影层)~~ → 被双写吸收**:没有单独的投影层;改为 **L3 的命令双写**(命令在改 world 的同时改模型)。world 仍是预览,模型仍是单一保存真相;省掉一个组件,代价是命令需维护两侧(由测试钉住一致性)。后续若要"模型为唯一真相、world 纯派生"再上独立投影。+- **L3(命令双写,已做)**:`SceneCommands` 的写原语(`applyFieldWrite`)与生命周期命令(add/delete/duplicate/rename)在改 world 的同时改 `SceneModel`(字段按 runtime,生命周期按稳定 source id 跟随 undo/redo recreate)。承接 E2 边界,undo/redo 闭包经同一原语自动同步。+- **L4(无损保存,已做)**:`ProjectStore.serializeCurrent` = `SceneModel.serialize()`(深拷贝模型,无损);`save` 删 lossy 拒绝逻辑;`serializeScene(world)` + `restoreAssetRefs` + 死的 `handleToUuid` 已移除。验证:golden——adopt 含未知组件场景 → 编辑/增删 → 序列化保留未知组件 + 反映编辑 + delete-undo 不丢未知组件。+- **L5(play 快照取数据模型,待做)**:`EngineHost.setRunMode` 快照数据模型而非 `serializeScene(world)`;Stop 恢复。接 play==ship。- **(可选)L6**:引擎给非编辑器消费者加未知组件 passthrough(防御纵深);prefab 借 `metadata` 范式同样无损。+> **现状(L1+L3+L4 已落地)**:编辑器**已能无损保存**——开含未知组件的场景、编辑已知字段/增删实体、覆盖保存,未知组件/字段/`@uuid:` 原样保留。`lossy` 拒绝保存已退役。`engine-model-sync.test.ts` 钉住。剩 L5(play 快照)是 play==ship 的收尾。+---## 5. 验证机制