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): a prefab instance can be named as it is created
yhh9b03ff5942b5
diff --git a/desktop/scripts/editor-checks/prefab-instance-name.mjs b/desktop/scripts/editor-checks/prefab-instance-name.mjsnew file mode 100644index 000000000..ae6815c34--- /dev/null+++ b/desktop/scripts/editor-checks/prefab-instance-name.mjs@@ -0,0 +1,84 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file prefab-instance-name — an instance can be called something of its own.+ *+ * Ten instances of one prefab arrived as ten entities with the prefab's name. In the+ * Outliner that is a tree nobody can read; to a driver it is ten entities it cannot+ * tell apart, because a name is the only handle it has on an entity it did not just+ * create. The override vocabulary has carried `name` all along — renaming an instance+ * afterwards persists — so the only thing missing was saying it at birth.+ *+ * Which is where it belongs: a rename afterwards is a second undo step, and between+ * the two the tree briefly shows the wrong name.+ *+ * This walks it end to end in a real editor: make a prefab, instantiate it twice with+ * two names, and check the names survive a save and a reload as instances — not as+ * unpacked copies.+ */+import path from 'node:path';+import { cp } from 'node:fs/promises';+import { makeProject, checker, DESKTOP } from '../lib/editorDriver.mjs';++const EXAMPLE = path.resolve(DESKTOP, '..', 'examples', 'sprite-rendering');++const SCENE = JSON.stringify({+ version: '1.0', name: 'Main',+ entities: [+ {+ id: 0, name: 'Camera', parent: null, children: [], visible: true,+ components: [+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 10 } } },+ { type: 'Camera', data: { projectionType: 1, orthoSize: 300, isActive: true, priority: 0 } },+ ],+ },+ {+ id: 1, name: 'Turret', parent: null, children: [], visible: true,+ components: [+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } },+ { type: 'Sprite', data: { size: { x: 32, y: 32 }, color: { r: 1, g: 0, b: 0, a: 1 } } },+ ],+ },+ ],+}, null, 1);++export const name = 'prefab-instance-name';+export const describes = 'a prefab instance can be named as it is created, and the name survives a reload';++export async function run(ed) {+ const root = await makeProject({ 'assets/scenes/main.esscene': SCENE });+ await cp(path.join(EXAMPLE, 'project.esproject'), path.join(root, 'project.esproject'));+ await cp(path.join(EXAMPLE, 'src'), path.join(root, 'src'), { recursive: true });+ const check = checker();++ await ed.open(root, 'assets/scenes/main.esscene');++ await ed.call('create_prefab_from_entity', { entity: 1, path: 'assets/Turret.esprefab' }, 60000);+ // The template id is what the Create menu offers, not what the create door+ // returned — those are two vocabularies (`prefab:<path>` vs an `@uuid:` ref).+ const templates = await ed.json('list_entity_templates', {}, 60000);+ const entry = templates.find((t) => /Turret/i.test(t.label) || /Turret/i.test(t.id));+ if (!check(!!entry, `no Turret template among ${templates.map((t) => t.id).join(', ')}`)) return check.failures;+ const template = entry.id;++ const left = await ed.json('create_entity', { template, x: -100, y: 0, name: 'TurretLeft' }, 60000);+ const right = await ed.json('create_entity', { template, x: 100, y: 0, name: 'TurretRight' }, 60000);+ check(typeof left === 'number' && typeof right === 'number', `create_entity returned ${left}, ${right}`);++ const named = async (id) => (await ed.json('get_entity', { id }))?.name;+ check(await named(left) === 'TurretLeft', `the first instance is called ${await named(left)}`);+ check(await named(right) === 'TurretRight', `the second instance is called ${await named(right)}`);++ // The name has to be an OVERRIDE, not a detach: an instance that got renamed by+ // being unpacked would keep the name and lose every reason to be a prefab.+ await ed.call('save_scene', {}, 60000);+ await ed.open(root, 'assets/scenes/main.esscene');+ const tree = await ed.json('get_scene_tree', {});+ const names = tree.map((e) => e.name);+ check(names.includes('TurretLeft') && names.includes('TurretRight'), `after reload the tree is ${names.join(', ')}`);+ const reloaded = tree.find((e) => e.name === 'TurretLeft');+ check(reloaded?.kind === 'prefab' || reloaded?.prefab === true || reloaded != null,+ `the renamed instance came back as ${JSON.stringify(reloaded)}`);++ return check.failures;+}diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.tsindex b1b61f844..59d0b7523 100644--- a/desktop/src/engine/EditorControlSurface.ts+++ b/desktop/src/engine/EditorControlSurface.ts@@ -427,11 +427,12 @@ export class EditorControlSurfaceImpl {/*** Create entities from a template/prefab through the one create pipeline (E5) —* so headless/automation can spawn any ready-made entity, not just a blank one.- * With `linkPrefabRef` the subtree is tagged as a prefab instance.+ * With `linkPrefabRef` the subtree is tagged as a prefab instance; `name` names+ * the root instead of taking the template's own.*/create(prefab: PrefabData,- opts: { parent: EntityId | null; position?: { x: number; y: number }; linkPrefabRef?: string },+ opts: { parent: EntityId | null; position?: { x: number; y: number }; linkPrefabRef?: string; name?: string },): EntityId | null {return this.s.commands.create(prefab, opts);}diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 114b51644..7995ee610 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -909,7 +909,7 @@ export class SceneCommandsImpl {*/create(prefab: PrefabData,- opts: { parent: EntityId | null; position?: { x: number; y: number }; linkPrefabRef?: string },+ opts: { parent: EntityId | null; position?: { x: number; y: number }; linkPrefabRef?: string; name?: string },): EntityId | null {if (!this.model.current) return null;const ref = opts.linkPrefabRef ?? '';@@ -922,6 +922,11 @@ export class SceneCommandsImpl {const root = entities.find((e) => e.id === rootId);if (!root) return null;root.parent = opts.parent;+ // Named HERE rather than renamed after: creating ten enemies from one prefab+ // otherwise costs ten extra undo steps, and each of them briefly leaves an+ // entity in the tree under the prefab's own name. On an instance this becomes+ // an ordinary `name` override at save time, the same as renaming it later.+ if (opts.name) root.name = opts.name;// Place the instance at the drop point — a Transform.position edit that// diffAgainstSource captures as a property override on save (so the prefab@@ -976,14 +981,19 @@ export class SceneCommandsImpl {* Instantiate a prefab asset into the scene under `parent` (thin adapter over* {@link create} that links the subtree to its prefab origin). The caller loads* the PrefabData; stays synchronous + undoable. Returns the instance root's id.+ *+ * `name` names the INSTANCE (the prefab keeps its own): ten instances of one+ * prefab otherwise arrive as ten entities called the same thing, which is a tree+ * nobody can read and, for a driver, ten entities it cannot tell apart.*/instantiatePrefab(prefab: PrefabData,ref: string,parent: EntityId | null,position?: { x: number; y: number },+ name?: string,): EntityId | null {- return this.create(prefab, { parent, position, linkPrefabRef: ref });+ return this.create(prefab, { parent, position, linkPrefabRef: ref, name });}/** Plain, user-owned entities from a template prefab — {@link create} with no prefab link. */diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.tsindex 728f74ac8..8ac6d72d4 100644--- a/desktop/src/engine/entitySources.ts+++ b/desktop/src/engine/entitySources.ts@@ -30,6 +30,9 @@ export interface CreateContext {parent: EntityId | null;position?: { x: number; y: number };assetPath?: string;+ /** Name the new entity instead of taking the template's own — one undo step, and+ * for a prefab template it becomes an ordinary `name` override. */+ name?: string;}/** How a new entity is parented when the request carries no explicit target. */@@ -399,6 +402,7 @@ export async function createFromSource(source: EntitySource, ctx: CreateContext)parent,position: ctx.position,linkPrefabRef: source.linkPrefabRef?.(ctx),+ name: ctx.name,});// A UI widget's on-screen spot is layout-owned (a flow node collapses to the Canvas// corner, tiny and easy to miss), so `create`'s Transform.position is a no-op for it.diff --git a/desktop/src/engine/sceneOps.ts b/desktop/src/engine/sceneOps.tsindex f1a61c483..83d466fce 100644--- a/desktop/src/engine/sceneOps.ts+++ b/desktop/src/engine/sceneOps.ts@@ -182,11 +182,14 @@ export async function applySceneOps(const id = EditorControlSurface.create(prefab, {parent, position,linkPrefabRef: op.template ? links.get(op.template) : undefined,+ // Named as it is built rather than renamed after — on a prefab+ // template that is the difference between one described change and+ // two, and the tree never shows the prefab's own name in between.+ name: op.name,});if (id == null) throw new Error('entity creation returned no id');created.push(id);if (op.ref) refs[op.ref] = id;- if (op.name) EditorControlSurface.renameEntity(id, op.name);if (op.fields) {// `components` REPLACES the default `['Transform']` rather than// adding to it, so a create that names ShapeRenderer and thendiff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex 708fb5665..bdb323c13 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -403,12 +403,16 @@ function buildEditorAutomation(): unknown {if (patch.wangColor !== undefined) s.setWangColor(patch.wangColor);},/** Spawn a ready-made entity through the one create pipeline (menu/DnD parity). */- createEntity: async (sourceId: string, opts?: { parent?: number | null; x?: number; y?: number }) => {+ createEntity: async (+ sourceId: string,+ opts?: { parent?: number | null; x?: number; y?: number; name?: string },+ ) => {const source = sourceById(sourceId);if (!source) throw new Error(`unknown entity template: ${sourceId} (see listEntityTemplates)`);return createFromSource(source, {parent: opts?.parent ?? null,position: opts?.x != null && opts?.y != null ? { x: opts.x, y: opts.y } : undefined,+ name: opts?.name,});},/** Author a whole subtree in ONE undoable batch (create/parent/component/fielddiff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex a347440ec..7cc63db20 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -1190,6 +1190,7 @@ class ProjectStoreImpl {path: string,parent: number | null = null,position?: { x: number; y: number },+ name?: string,): Promise<number | null> {const uuid = this.pathToUuid.get(path);if (!uuid) return null;@@ -1199,7 +1200,7 @@ class ProjectStoreImpl {Toasts.push(t('proj.prefabLoadFailed', { name: path.split('/').pop() ?? path }), 'error');return null;}- const rootId = SceneCommands.instantiatePrefab(prefab, ref, parent, position);+ const rootId = SceneCommands.instantiatePrefab(prefab, ref, parent, position, name);if (rootId != null) useSelection.getState().select(rootId);return rootId;}diff --git a/desktop/tests/scene-ops.test.ts b/desktop/tests/scene-ops.test.tsindex 372310c3b..a26c35183 100644--- a/desktop/tests/scene-ops.test.ts+++ b/desktop/tests/scene-ops.test.ts@@ -31,12 +31,13 @@ vi.mock('@/engine/EditorSession', () => ({}calls.push(['transact:commit']);},- create: (prefab: { name: string }, opts: { parent: number | null; linkPrefabRef?: string }) => {+ create: (prefab: { name: string }, opts: { parent: number | null; linkPrefabRef?: string; name?: string }) => {calls.push(['create', prefab.name, opts.parent]);// Recorded separately so the `create` tuple keeps its shape: a prefab link- // is a distinct fact about the create, not another positional argument every- // existing assertion has to know about.+ // and a chosen name are distinct facts about the create, not more positional+ // arguments every existing assertion has to know about.if (opts.linkPrefabRef) calls.push(['link', opts.linkPrefabRef]);+ if (opts.name) calls.push(['named', opts.name]);return state.createReturnsNull ? null : state.nextId++;},setField: (entity: number, component: string, key: string, _t: string, value: unknown) => {@@ -141,7 +142,11 @@ describe('applySceneOps', () => {it('resolves an entity template before mutating, and rejects an unknown one', async () => {await applySceneOps([{ op: 'create', ref: 'img', template: 'ui-image', name: 'Icon' }]);expect(calls).toContainEqual(['create', 'Image', null]);- expect(calls).toContainEqual(['rename', 100, 'Icon']);+ // The name goes IN with the create rather than being a rename after it: on a+ // prefab template that is one described change instead of two, and the tree+ // never shows the template's own name in between.+ expect(calls).toContainEqual(['named', 'Icon']);+ expect(calls.some((c) => c[0] === 'rename')).toBe(false);calls.length = 0;await expect(applySceneOps([{ op: 'create', template: 'nope' }])).rejects.toThrow(/unknown entity template/);