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(editor): recursive delete + robust tree + unify SceneLoader (review pass)
esengine34d53979877b
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex d80a91e58..5494fd373 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -207,18 +207,31 @@ export class SceneCommandsImpl {return sourceId;}- /** Delete an entity (undo re-creates it, losslessly, from the model record). */+ /**+ * Delete an entity AND its descendants (the World despawns children with their+ * parent, so the model removes the whole subtree to stay consistent). Undo+ * re-creates the subtree losslessly, parent-before-child. Records are kept+ * parent-first so restore re-links each child to its (already-restored) parent.+ */deleteEntity(sourceId: EntityId): void {- const name = this.model.entityBySource(sourceId)?.name || 'Entity';- let record = this.model.removeEntityBySource(sourceId);- if (!record) return;+ const entity = this.model.entityBySource(sourceId);+ if (!entity) return;+ const name = entity.name || 'Entity';+ const remove = (): SceneEntity[] =>+ this.model+ .collectSubtree(sourceId)+ .map((id) => this.model.removeEntityBySource(id))+ .filter((r): r is SceneEntity => r !== undefined);++ let records = remove();+ if (records.length === 0) return;this.history.record(`Delete ${name}`,() => {- record = this.model.removeEntityBySource(record!.id) ?? record;+ records = remove(); // redo},() => {- this.model.restoreEntity(record!);+ for (const r of records) this.model.restoreEntity(r); // parent-first},);}diff --git a/desktop/src/engine/SceneLoader.ts b/desktop/src/engine/SceneLoader.tsindex a271539ae..cb4255833 100644--- a/desktop/src/engine/SceneLoader.ts+++ b/desktop/src/engine/SceneLoader.ts@@ -6,98 +6,64 @@ import { EditorHistory } from './EditorHistory';type SceneDataArg = Parameters<typeof loadSceneData>[1];-// Minimal structural view of the engine Assets resource we use.-interface AssetsLike {- loadTexture(ref: string): Promise<{ handle: number }>;-}-const UUID_PREFIX = '@uuid:';-// Walk every string in the SceneData; `fn` may return a replacement value.-function mapStrings(value: unknown, fn: (s: string) => unknown): unknown {- if (typeof value === 'string') return fn(value);- if (Array.isArray(value)) return value.map((v) => mapStrings(v, fn));- if (value && typeof value === 'object') {- const out: Record<string, unknown> = {};- for (const [k, v] of Object.entries(value as Record<string, unknown>)) {- out[k] = mapStrings(v, fn);- }- return out;- }- return value;-}--function collectUuids(sceneData: unknown): Set<string> {- const uuids = new Set<string>();- mapStrings(sceneData, (s) => {- if (s.startsWith(UUID_PREFIX)) uuids.add(s.slice(UUID_PREFIX.length));- return s;- });- return uuids;-}-export const SceneLoader = {/**- * Fetch an `.esscene` (SceneData JSON), resolve its `@uuid:` texture refs to- * live texture handles via the engine Assets system + a uuid→url manifest,- * spawn it into the world, and adopt the RAW scene as the editor model (the- * source of truth). Returns the entity count. Refs without a manifest entry- * (or a failed load) blank to 0 (solid-color sprite).+ * Fetch an `.esscene` (SceneData JSON) and load it through the engine's own+ * asset system — the ONE asset-resolution path (REARCH_ASSETS.md). A uuid→url+ * manifest feeds the ref resolver; `Assets.preloadSceneAssets` loads every+ * referenced type (not just textures), and a resolved copy builds the World.+ * The raw scene (with `@uuid:` refs + components/fields the World drops) is+ * adopted as the editor model (the source of truth). Returns the entity count.*- * Model-authoritative (REARCH_EDITOR_MODEL.md): the World is built directly- * here (the bulk projection), and the raw scene — with `@uuid:` refs + any- * components/fields the World drops — becomes the model. SceneModel.adopt- * emits `reset`; the Reconciler ignores it (the World is already built), while- * SceneStore bumps and panels re-read from the model.+ * This is the dev-fallback / automation transport (a manifest of absolute+ * URLs); the editor's project transport (estella:// + .meta) lives in+ * ProjectStore. Both now go through the same engine `Assets` loader.+ *+ * Model-authoritative (REARCH_EDITOR_MODEL.md): SceneModel.adopt emits `reset`;+ * the Reconciler ignores it (the World is already built here) while SceneStore+ * bumps and panels re-read from the model.*/async loadInto(app: App, sceneUrl: string, manifestUrl?: string): Promise<number> {const res = await fetch(sceneUrl);if (!res.ok) throw new Error(`scene fetch failed: ${res.status} ${sceneUrl}`);const raw = (await res.json()) as SceneData;- const uuidToHandle = await loadTextures(app, raw, manifestUrl);-- const sceneData = mapStrings(raw, (s) =>- s.startsWith(UUID_PREFIX) ? (uuidToHandle.get(s.slice(UUID_PREFIX.length)) ?? 0) : s,- ) as SceneDataArg;+ const uuidToUrl = await fetchManifest(manifestUrl);+ const assets = app.getResource(Assets);+ let resolved: SceneData = raw;+ if (assets) {+ assets.baseUrl = ''; // manifest URLs are absolute / root-relative+ assets.setAssetRefResolver((ref) =>+ ref.startsWith(UUID_PREFIX) ? (uuidToUrl.get(ref.slice(UUID_PREFIX.length)) ?? null) : ref,+ );+ const result = await assets.preloadSceneAssets(raw);+ resolved = JSON.parse(JSON.stringify(raw)) as SceneData; // resolveSceneAssetPaths mutates+ assets.resolveSceneAssetPaths(resolved, result);+ // Incremental recreate (duplicate / undo) re-resolves textures from the+ // engine's live cache (just loaded above).+ Reconciler.setAssetResolver((uuid) => assets.getTexture(UUID_PREFIX + uuid)?.handle ?? 0);+ }- const map = loadSceneData(app.world, sceneData);+ const map = loadSceneData(app.world, resolved as SceneDataArg);EditorHistory.clear();- Reconciler.setAssetResolver((uuid) => uuidToHandle.get(uuid) ?? 0);SceneModel.adopt(raw, map as Map<number, number>);return map.size;},};-async function loadTextures(- app: App,- sceneData: unknown,- manifestUrl?: string,-): Promise<Map<string, number>> {- const handles = new Map<string, number>();- if (!manifestUrl) return handles;-- let manifest: Record<string, string>;+/** Fetch a uuid→url asset manifest (the dev/automation transport). Empty if absent. */+async function fetchManifest(manifestUrl?: string): Promise<Map<string, string>> {+ const out = new Map<string, string>();+ if (!manifestUrl) return out;try {const res = await fetch(manifestUrl);- if (!res.ok) return handles;- manifest = await res.json();+ if (!res.ok) return out;+ const json = (await res.json()) as Record<string, string>;+ for (const [uuid, url] of Object.entries(json)) out.set(uuid, url);} catch {- return handles;- }-- const assets = app.getResource(Assets) as unknown as AssetsLike | undefined;- if (!assets) return handles;-- for (const uuid of collectUuids(sceneData)) {- const url = manifest[uuid];- if (!url) continue;- try {- const { handle } = await assets.loadTexture(url);- handles.set(uuid, handle);- } catch (err) {- console.warn('[engine] texture load failed', url, err);- }+ // no manifest — refs blank to 0}- return handles;+ return out;}diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.tsindex adbcd751a..60c6f6026 100644--- a/desktop/src/engine/SceneModel.ts+++ b/desktop/src/engine/SceneModel.ts@@ -257,6 +257,23 @@ export class SceneModelImpl {return this.data?.entities.find((e) => e.id === sourceId);}+ /**+ * A source id + all its descendants, **parent-before-child** — for recursive+ * delete (the World despawns a parent's children too, so the model must remove+ * the whole subtree to stay consistent) and ordered restore on undo.+ */+ collectSubtree(sourceId: number): number[] {+ const out: number[] = [];+ const visit = (id: number): void => {+ const e = this.entityBySource(id);+ if (!e) return;+ out.push(id);+ for (const child of e.children) visit(child);+ };+ visit(sourceId);+ return out;+ }+/** 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/engine/SceneQuery.ts b/desktop/src/engine/SceneQuery.tsindex 63f82f79c..83da48563 100644--- a/desktop/src/engine/SceneQuery.ts+++ b/desktop/src/engine/SceneQuery.ts@@ -33,30 +33,45 @@ export class SceneQueryImpl {return this.store.getStructureRevision();}- /** Build the outliner tree from the model, nesting via parent/children links. */+ /**+ * Build the outliner tree from the model. Nesting is derived from each entity's+ * `parent` field (the authoritative tree position) — grouped into a parent→+ * children index — so every entity appears exactly once: under its parent if it+ * exists, else as a root. This is robust to a `children[]` array that drifted+ * out of sync (e.g. a hand-edited / malformed scene), which a children-driven+ * walk would silently drop or double-count.+ */readSceneTree(): SceneNode[] {const data = this.model.current;if (!data) return [];- const byId = new Map(data.entities.map((e) => [e.id, e]));++ const ids = new Set(data.entities.map((e) => e.id));+ const childrenOf = new Map<number, Array<(typeof data.entities)[number]>>();+ const roots: Array<(typeof data.entities)[number]> = [];+ for (const e of data.entities) {+ if (e.parent != null && ids.has(e.parent)) {+ const arr = childrenOf.get(e.parent);+ if (arr) arr.push(e);+ else childrenOf.set(e.parent, [e]);+ } else {+ roots.push(e); // no parent, or a dangling parent → a scene root+ }+ }const build = (e: (typeof data.entities)[number]): SceneNode => {const kind = modelKindOf(e);- const kids = e.children- .map((cid) => byId.get(cid))- .filter((c): c is typeof e => c != null)- .map(build);+ const kids = childrenOf.get(e.id)?.map(build);return {id: e.id,name: modelNameOf(e, kind),kind,visible: modelIsVisible(e),locked: false,- children: kids.length ? kids : undefined,+ children: kids && kids.length ? kids : undefined,};};- // Roots = entities with no parent, or whose parent no longer exists.- return data.entities.filter((e) => e.parent == null || !byId.has(e.parent)).map(build);+ return roots.map(build);}/** Inspect a single source entity (name, kind, which components it carries). */diff --git a/desktop/tests/engine-model-sync.test.ts b/desktop/tests/engine-model-sync.test.tsindex fba23f78a..13ea31937 100644--- a/desktop/tests/engine-model-sync.test.ts+++ b/desktop/tests/engine-model-sync.test.ts@@ -121,6 +121,32 @@ describe.skipIf(!HAS_WASM)('Model-authoritative projection + lossless save', ()expect(saved.entities[0].components.some((c) => c.type === 'WaveMotion')).toBe(true);});+ it('delete of a parent cascades to its children (model + World); undo restores the subtree', () => {+ const childSrc = S.model.addEntity(+ 'Child',+ [{ type: 'WaveMotion', data: { amplitude: 3 } }] as never,+ 1,+ );+ const childRt = S.model.runtimeFor(childSrc)!;+ expect(host.world.valid(childRt)).toBe(true);++ S.commands.deleteEntity(1); // delete the PARENT (Hero) — the subtree goes+ expect(S.model.entityBySource(1)).toBeUndefined();+ expect(S.model.entityBySource(childSrc)).toBeUndefined();+ expect(host.world.valid(runtime1)).toBe(false);+ expect(host.world.valid(childRt)).toBe(false); // child despawned with its parent++ S.history.undo();+ // Model: both back, the child still parented to the restored parent.+ expect(S.model.entityBySource(1)).toBeDefined();+ expect(S.model.entityBySource(childSrc)?.parent).toBe(1);+ // World: both respawned, the child re-parented to the new parent runtime.+ const newParentRt = S.model.runtimeFor(1)!;+ const newChildRt = S.model.runtimeFor(childSrc)!;+ expect(host.world.has(newChildRt, Parent)).toBe(true);+ expect((host.world.get(newChildRt, Parent) as { entity: number }).entity).toBe(newParentRt);+ });+it('delete of a parented entity with an unknown component → undo restores model + World + parent link', () => {// Add a child of Hero (source 1) carrying an unknown component.const childSrc = S.model.addEntity(diff --git a/desktop/tests/scene-query.test.ts b/desktop/tests/scene-query.test.tsnew file mode 100644index 000000000..68619057d--- /dev/null+++ b/desktop/tests/scene-query.test.ts@@ -0,0 +1,60 @@+/**+ * @file SceneQuery.readSceneTree — the outliner tree is derived from the MODEL+ * (REARCH_EDITOR_MODEL.md §3.4), nested by each entity's `parent` field so+ * every entity appears exactly once and a drifted `children[]` array (a+ * hand-edited / malformed scene) can't drop or double-count nodes. Pure+ * model+query (readSceneTree reads the model only — no World needed).+ */+import { describe, it, expect, beforeEach } from 'vitest';+import type { SceneData } from 'esengine';+import type { SceneNode } from '@/types';+import { EditorSession } from '@/engine/EditorSession';++const ent = (id: number, parent: number | null, children: number[]) => ({+ id,+ name: `E${id}`,+ parent,+ children,+ components: [] as unknown[],+});++function scene(): SceneData {+ return {+ version: '1.0',+ name: 'tree',+ entities: [+ ent(1, null, [2]), // root with a child+ ent(2, 1, []), // child of 1+ ent(3, 999, []), // dangling parent → must read as a root+ ent(4, 1, []), // parent is 1, but 1.children DOESN'T list 4 (drift) → still under 1+ ],+ } as unknown as SceneData;+}++const ids = (nodes: SceneNode[] | undefined) => (nodes ?? []).map((n) => n.id).sort();++describe('SceneQuery.readSceneTree (model hierarchy)', () => {+ let S: EditorSession;+ beforeEach(() => {+ S = EditorSession.create();+ S.model.adopt(scene(), new Map());+ });++ it('roots = entities with no parent or a dangling parent', () => {+ const tree = S.query.readSceneTree();+ expect(ids(tree)).toEqual([1, 3]); // 1 (no parent) + 3 (parent 999 missing)+ });++ it('nests by the parent field, robust to a drifted children[] array', () => {+ const tree = S.query.readSceneTree();+ const root1 = tree.find((n) => n.id === 1)!;+ // Both 2 (listed in children[]) and 4 (NOT listed, but parent===1) nest under 1.+ expect(ids(root1.children)).toEqual([2, 4]);+ });++ it('a dangling-parent node has no phantom children', () => {+ const tree = S.query.readSceneTree();+ const node3 = tree.find((n) => n.id === 3)!;+ expect(node3.children).toBeUndefined();+ });+});