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.

fix(prefab): an override aimed at nobody is refused, and no id means the root

yhh8e075d0ed65c
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index c8d1919e5..3a8f057b1 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1442 stable · 17 beta · 1 deprecated
+Symbols: 1443 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -5413,7 +5413,7 @@ value: unknown
## PrefabServer — class
```
-instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: PrefabOverride[]; }) => Promise<InstantiatePrefabResult>
+instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; }) => Promise<InstantiatePrefabResult>
static new (world: World, getAssets: () => AssetsClass): PrefabServer
static prototype: PrefabServer
```
@@ -6542,6 +6542,11 @@ refDistance: number
rolloff: number
```
+## SpawnOverride — type
+```
+Omit<PrefabOverride, 'prefabEntityId'> & { prefabEntityId?: string }
+```
+
## Spine — const
```
ResourceDef<SpineManager>
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 0ca8e559c..14598791b 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1461 stable · 22 beta · 1 deprecated
+Symbols: 1462 stable · 22 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -5573,7 +5573,7 @@ value: unknown
## PrefabServer — class
```
-instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: PrefabOverride[]; }) => Promise<InstantiatePrefabResult>
+instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; }) => Promise<InstantiatePrefabResult>
static new (world: World, getAssets: () => AssetsClass): PrefabServer
static prototype: PrefabServer
```
@@ -6712,6 +6712,11 @@ refDistance: number
rolloff: number
```
+## SpawnOverride — type
+```
+Omit<PrefabOverride, 'prefabEntityId'> & { prefabEntityId?: string }
+```
+
## Spine — const
```
ResourceDef<SpineManager>
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index dfed16f4e..779411b40 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1441 stable · 19 beta · 1 deprecated
+Symbols: 1442 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -5408,7 +5408,7 @@ value: unknown
## PrefabServer — class
```
-instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: PrefabOverride[]; }) => Promise<InstantiatePrefabResult>
+instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; }) => Promise<InstantiatePrefabResult>
static new (world: World, getAssets: () => AssetsClass): PrefabServer
static prototype: PrefabServer
```
@@ -6537,6 +6537,11 @@ refDistance: number
rolloff: number
```
+## SpawnOverride — type
+```
+Omit<PrefabOverride, 'prefabEntityId'> & { prefabEntityId?: string }
+```
+
## Spine — const
```
ResourceDef<SpineManager>
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 8448145cc..659ddd156 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1462 stable · 17 beta · 1 deprecated
+Symbols: 1463 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -5653,7 +5653,7 @@ value: unknown
## PrefabServer — class
```
-instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: PrefabOverride[]; }) => Promise<InstantiatePrefabResult>
+instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; }) => Promise<InstantiatePrefabResult>
static new (world: World, getAssets: () => AssetsClass): PrefabServer
static prototype: PrefabServer
```
@@ -6782,6 +6782,11 @@ refDistance: number
rolloff: number
```
+## SpawnOverride — type
+```
+Omit<PrefabOverride, 'prefabEntityId'> & { prefabEntityId?: string }
+```
+
## Spine — const
```
ResourceDef<SpineManager>
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index f55ca6243..aeb01e0e4 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1452 stable · 17 beta · 1 deprecated
+Symbols: 1453 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -5415,7 +5415,7 @@ value: unknown
## PrefabServer — class
```
-instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: PrefabOverride[]; }) => Promise<InstantiatePrefabResult>
+instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; }) => Promise<InstantiatePrefabResult>
static new (world: World, getAssets: () => AssetsClass): PrefabServer
static prototype: PrefabServer
```
@@ -6544,6 +6544,11 @@ refDistance: number
rolloff: number
```
+## SpawnOverride — type
+```
+Omit<PrefabOverride, 'prefabEntityId'> & { prefabEntityId?: string }
+```
+
## Spine — const
```
ResourceDef<SpineManager>
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index b15e92981..390d895cf 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -226,7 +226,7 @@ export {
type ExternalEntityRef,
} from './prefab/index';
-export { Prefabs, PrefabServer, PrefabsPlugin, prefabsPlugin } from './prefab/prefabServer';
+export { Prefabs, PrefabServer, PrefabsPlugin, prefabsPlugin, type SpawnOverride } from './prefab/prefabServer';
// =============================================================================
// Runtime Loader
diff --git a/sdk/src/prefab/prefabServer.ts b/sdk/src/prefab/prefabServer.ts
index 3acc88265..c59c27b90 100644
--- a/sdk/src/prefab/prefabServer.ts
+++ b/sdk/src/prefab/prefabServer.ts
@@ -13,6 +13,12 @@ import {
type InstantiatePrefabResult,
} from '../prefab';
+/**
+ * An override as written at a SPAWN: the entity id may be left out, and then it
+ * is the prefab's root — which is the entity a one-sprite prefab has.
+ */
+export type SpawnOverride = Omit<PrefabOverride, 'prefabEntityId'> & { prefabEntityId?: string };
+
export class PrefabServer {
private readonly world_: World;
private readonly getAssets_: () => AssetsClass;
@@ -28,7 +34,7 @@ export class PrefabServer {
async instantiate(pathOrAddress: string, options?: {
baseUrl?: string;
parent?: Entity;
- overrides?: PrefabOverride[];
+ overrides?: SpawnOverride[];
}): Promise<InstantiatePrefabResult> {
const assets = this.getAssets_();
const prefabResult = await assets.loadPrefab(pathOrAddress);
@@ -37,11 +43,50 @@ export class PrefabServer {
assets,
assetBaseUrl: options?.baseUrl,
parent: options?.parent,
- overrides: options?.overrides,
+ overrides: resolveSpawnOverrides(prefab, pathOrAddress, options?.overrides),
});
}
}
+/**
+ * Aim each override at an entity this prefab actually has — and say so when one
+ * does not.
+ *
+ * `prefabEntityId` is a STABLE ADDRESS inside the prefab, and an override
+ * carrying one nobody answers to is dropped without a word: the bullet spawns,
+ * at the position the prefab was authored with, and the only symptom is that
+ * every one of them appears in the same place. Two things make that easy to
+ * write. `'0'` is the id every prefab had before stable ids, so it is what every
+ * older example still shows — and a prefab saved since gets a uuid instead. And
+ * the common case, spawning one sprite, has exactly one entity to aim at, so
+ * naming it at all is ceremony: an omitted id means the root.
+ *
+ * The editor's own instance path deliberately does NOT do this — an override
+ * left over from a since-deleted child is a normal thing to carry there. This is
+ * the RUNTIME spawn door, where the override was written moments ago by someone
+ * who can still fix it.
+ */
+function resolveSpawnOverrides(
+ prefab: PrefabData,
+ path: string,
+ overrides: SpawnOverride[] | undefined,
+): PrefabOverride[] | undefined {
+ if (!overrides?.length) return undefined;
+ const known = new Set(prefab.entities.map((e) => e.prefabEntityId));
+ return overrides.map((o): PrefabOverride => {
+ if (!o.prefabEntityId) return { ...o, prefabEntityId: prefab.rootEntityId };
+ if (!known.has(o.prefabEntityId)) {
+ throw new Error(
+ `prefab "${path}" has no entity "${o.prefabEntityId}" for this override `
+ + `(${o.type}${o.componentType ? ` ${o.componentType}.${o.propertyName}` : ''}). `
+ + `Its root is "${prefab.rootEntityId}" — or leave prefabEntityId out and the root is used. `
+ + `Entities: ${[...known].join(', ')}`,
+ );
+ }
+ return o as PrefabOverride;
+ });
+}
+
export const Prefabs = defineResource<PrefabServer>(null!, 'Prefabs');
export class PrefabsPlugin implements Plugin {
diff --git a/sdk/tests/prefab-spawn-overrides.test.ts b/sdk/tests/prefab-spawn-overrides.test.ts
new file mode 100644
index 000000000..5e1afe341
--- /dev/null
+++ b/sdk/tests/prefab-spawn-overrides.test.ts
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The runtime spawn door's overrides: aimed at an entity the prefab has.
+ *
+ * `prefabEntityId` is a stable address inside the prefab, and an override that
+ * names one nobody answers to used to be dropped in silence — every bullet then
+ * spawns at the position the prefab was authored with, and nothing says why.
+ * `'0'` is the id every prefab had before stable ids, so it is what the older
+ * examples still show; a prefab saved since gets a uuid.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import type { PrefabData } from '../src/prefab';
+
+const instantiateSpy = vi.fn(async () => ({ root: 1 as never, entities: new Map() }));
+vi.mock('../src/prefab', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../src/prefab')>()),
+ instantiatePrefab: (...args: unknown[]) => instantiateSpy(...(args as [])),
+}));
+
+const { PrefabServer } = await import('../src/prefab/prefabServer');
+
+const PREFAB: PrefabData = {
+ version: '2',
+ name: 'Bullet',
+ rootEntityId: 'aaaa-bbbb',
+ entities: [
+ { prefabEntityId: 'aaaa-bbbb', name: 'Bullet', parent: null, children: ['cccc-dddd'], components: {}, visible: true },
+ { prefabEntityId: 'cccc-dddd', name: 'Trail', parent: 'aaaa-bbbb', children: [], components: {}, visible: true },
+ ],
+} as unknown as PrefabData;
+
+const positionAt = (x: number, prefabEntityId?: string) => ({
+ ...(prefabEntityId ? { prefabEntityId } : {}),
+ type: 'property' as const,
+ componentType: 'Transform',
+ propertyName: 'position',
+ value: { x, y: 0, z: 0 },
+});
+
+function server(): InstanceType<typeof PrefabServer> {
+ const assets = { loadPrefab: async () => ({ data: PREFAB }) };
+ return new PrefabServer({} as never, () => assets as never);
+}
+
+const overridesPassed = (): unknown[] => {
+ const opts = instantiateSpy.mock.calls.at(-1)?.[2] as { overrides?: unknown[] };
+ return opts.overrides ?? [];
+};
+
+describe('PrefabServer.instantiate overrides', () => {
+ it('aims an override with no entity id at the root', async () => {
+ instantiateSpy.mockClear();
+ await server().instantiate('assets/prefabs/Bullet.esprefab', { overrides: [positionAt(7)] });
+ expect(overridesPassed()).toEqual([{ ...positionAt(7), prefabEntityId: 'aaaa-bbbb' }]);
+ });
+
+ it('passes an id the prefab has through untouched', async () => {
+ instantiateSpy.mockClear();
+ await server().instantiate('assets/prefabs/Bullet.esprefab', { overrides: [positionAt(7, 'cccc-dddd')] });
+ expect(overridesPassed()).toEqual([positionAt(7, 'cccc-dddd')]);
+ });
+
+ it('refuses an id nobody answers to, naming the root and the alternatives', async () => {
+ // The `'0'` every pre-stable-id example still shows.
+ await expect(server().instantiate('assets/prefabs/Bullet.esprefab', { overrides: [positionAt(7, '0')] }))
+ .rejects.toThrow(/no entity "0"/);
+ await expect(server().instantiate('assets/prefabs/Bullet.esprefab', { overrides: [positionAt(7, '0')] }))
+ .rejects.toThrow(/aaaa-bbbb/);
+ });
+});