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): an override that names no entity of its prefab is reported
esenginec006f3b358c9
diff --git a/sdk/src/prefab/flatten.ts b/sdk/src/prefab/flatten.tsindex 1c600cfc0..1ab65ef2c 100644--- a/sdk/src/prefab/flatten.ts+++ b/sdk/src/prefab/flatten.ts@@ -52,6 +52,8 @@ export function flattenPrefab(const result: ProcessedEntity[] = [];const overrideBuckets = bucketOverridesByEntity(overrides);+ const unresolved: PrefabOverride[] = [];+ const slotPrefixes: string[] = [];for (const pe of prefab.entities) {if (pe.nestedPrefab) {@@ -78,6 +80,7 @@ export function flattenPrefab(// slot's authored overrides. This is what makes an instance override// on a nested entity survive the collapse→expand round trip.const slotPrefix = pe.prefabEntityId + PREFAB_ADDRESS_SEP;+ slotPrefixes.push(slotPrefix);const routed = overrides.filter(o => o.prefabEntityId.startsWith(slotPrefix)).map(o => ({ ...o, prefabEntityId: o.prefabEntityId.slice(slotPrefix.length) }));@@ -105,6 +108,9 @@ export function flattenPrefab(for (const ne of nested.entities) {ne.prefabEntityId = joinAddress(pe.prefabEntityId, ne.prefabEntityId);}+ for (const o of nested.unresolved) {+ unresolved.push({ ...o, prefabEntityId: joinAddress(pe.prefabEntityId, o.prefabEntityId) });+ }idMapping.set(pe.prefabEntityId, nested.rootId);@@ -146,6 +152,12 @@ export function flattenPrefab(result.push(entity);}+ for (const o of overrides) {+ if (idMapping.has(o.prefabEntityId)) continue;+ if (slotPrefixes.some((p) => o.prefabEntityId.startsWith(p))) continue;+ unresolved.push(o);+ }+const rootId = idMapping.get(prefab.rootEntityId);if (rootId === undefined) {throw new Error(@@ -179,7 +191,7 @@ export function flattenPrefab(}}- return { entities: result, rootId };+ return { entities: result, rootId, unresolved };}/**diff --git a/sdk/src/prefab/sceneInstance.ts b/sdk/src/prefab/sceneInstance.tsindex 89f8d4e74..8fe070892 100644--- a/sdk/src/prefab/sceneInstance.ts+++ b/sdk/src/prefab/sceneInstance.ts@@ -92,8 +92,8 @@ export function expandInstance(delta: PrefabInstanceDelta,allocateId: () => number,loadPrefab: SyncPrefabResolver = NO_NESTED,-): { entities: ProcessedEntity[]; rootId: number } {- const { entities, rootId } = flattenPrefab(prefab, delta.overrides, {+): { entities: ProcessedEntity[]; rootId: number; unresolved: PrefabOverride[] } {+ const { entities, rootId, unresolved } = flattenPrefab(prefab, delta.overrides, {allocateId,loadPrefab,});@@ -138,7 +138,7 @@ export function expandInstance(// added entity resolves and any still-unresolved target falls back to root.applyParentOverrides(all, delta.overrides, rootId, true);rebuildChildren(all);- return { entities: all, rootId };+ return { entities: all, rootId, unresolved };}/**@@ -290,8 +290,8 @@ export function expandEntry(entry: PrefabInstanceEntry,allocateId: () => number,loadPrefab: SyncPrefabResolver = NO_NESTED,-): { entities: ProcessedEntity[]; rootId: number } {- const { entities, rootId } = expandInstance(prefab, entry, allocateId, loadPrefab);+): { entities: ProcessedEntity[]; rootId: number; unresolved: PrefabOverride[] } {+ const { entities, rootId, unresolved } = expandInstance(prefab, entry, allocateId, loadPrefab);// Pin the root to the persisted scene id (external refs target it); internal// entities keep their fresh ids. Remap the root id + any parent pointing at it.for (const e of entities) {@@ -301,7 +301,7 @@ export function expandEntry(const root = entities.find((e) => e.id === entry.id);if (root) root.parent = entry.parent; // attach under the scene parentrebuildChildren(entities);- return { entities, rootId: entry.id };+ return { entities, rootId: entry.id, unresolved };}/**diff --git a/sdk/src/prefab/types.ts b/sdk/src/prefab/types.tsindex 305179b6a..9362f133f 100644--- a/sdk/src/prefab/types.ts+++ b/sdk/src/prefab/types.ts@@ -144,4 +144,7 @@ export interface FlattenContext {export interface FlattenResult {entities: ProcessedEntity[];rootId: number;+ /** Overrides whose target is no entity of the prefab — by the address they+ * name, which a caller reports: applied nowhere, they change nothing. */+ unresolved: PrefabOverride[];}diff --git a/sdk/src/scene/scene.ts b/sdk/src/scene/scene.tsindex 083a76772..cee4f00fc 100644--- a/sdk/src/scene/scene.ts+++ b/sdk/src/scene/scene.ts@@ -325,7 +325,13 @@ export async function expandScenePrefabs(log.warn('scene', `Prefab instance "${entry.prefab}" has an unresolved nested prefab; instance skipped (${e})`);continue;}- const { entities } = expandEntry(prefab, entry, allocateId, (ref) => cache.get(ref) ?? null);+ const { entities, unresolved } = expandEntry(prefab, entry, allocateId, (ref) => cache.get(ref) ?? null);+ if (unresolved.length > 0) {+ const targets = [...new Set(unresolved.map((o) => o.prefabEntityId))].join(', ');+ log.warn('scene', `Prefab instance "${entry.prefab}" (entity ${entry.id}) overrides `+ + `${unresolved.length} thing(s) on ${targets}, which the prefab has no entity for; `+ + 'those overrides change nothing');+ }for (const pe of entities) out.push(toSceneEntityData(pe));}return { ...scene, entities: out };diff --git a/sdk/tests/prefab-unresolved-overrides.test.ts b/sdk/tests/prefab-unresolved-overrides.test.tsnew file mode 100644index 000000000..0fcdb82cd--- /dev/null+++ b/sdk/tests/prefab-unresolved-overrides.test.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file An override is addressed to a prefab entity by id. One whose id names+ * no entity is applied nowhere, and flatten says which, by the address the+ * instance wrote — through a nested slot too.+ */+import { describe, it, expect } from 'vitest';+import { flattenPrefab } from '../src/prefab/flatten';+import type { PrefabData, PrefabOverride } from '../src/prefab/types';++const entity = (id: string, parent: string | null, children: string[] = [], extra = {}) => ({+ prefabEntityId: id, name: `E${id}`, parent, children, visible: true,+ components: [{ type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } }], ...extra,+});++const child: PrefabData = {+ version: '1.0', name: 'Child', rootEntityId: 'c0',+ entities: [entity('c0', null)],+};+const parent: PrefabData = {+ version: '1.0', name: 'Parent', rootEntityId: 'n24',+ entities: [+ entity('n24', null, ['slot']),+ { ...entity('slot', 'n24'), components: [], nestedPrefab: { prefabPath: 'child', overrides: [] } },+ ],+};++const move = (target: string): PrefabOverride => ({+ prefabEntityId: target, type: 'property', componentType: 'Transform', propertyName: 'position',+ value: { x: -70, y: 0, z: 0 },+});++const flatten = (overrides: PrefabOverride[]) => {+ let next = 0;+ return flattenPrefab(parent, overrides, {+ allocateId: () => next++,+ loadPrefab: (path) => (path === 'child' ? child : null),+ });+};++describe('an override that names no entity', () => {+ it('is reported, and one that does name an entity is applied', () => {+ const { entities, rootId, unresolved } = flatten([move('n54'), move('n24')]);+ expect(unresolved.map((o) => o.prefabEntityId)).toEqual(['n54']);+ const root = entities.find((e) => e.id === rootId)!;+ expect((root.components[0].data as { position: { x: number } }).position.x).toBe(-70);+ });++ it('inside a nested slot is reported by the address the instance wrote', () => {+ const { unresolved } = flatten([move('slot/c0'), move('slot/c9')]);+ expect(unresolved.map((o) => o.prefabEntityId)).toEqual(['slot/c9']);+ });++ it('is nothing to report when every override lands', () => {+ expect(flatten([move('n24'), move('slot/c0')]).unresolved).toEqual([]);+ });+});diff --git a/tools/check-prefab-overrides.mjs b/tools/check-prefab-overrides.mjsnew file mode 100644index 000000000..5a58a1ef9--- /dev/null+++ b/tools/check-prefab-overrides.mjs@@ -0,0 +1,96 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file check-prefab-overrides.mjs — every override a shipped scene writes on a+ * prefab instance names an entity that prefab has.+ *+ * An override is addressed by id, and one whose id names nothing is applied+ * nowhere: the engine warns at load, but a scene nobody opens warns nobody. The+ * character-rig example carried two such overrides — its hero's position and its+ * Animator — so the hero never stood where the scene put it and never moved.+ *+ * node tools/check-prefab-overrides.mjs+ */+import { readFileSync, readdirSync, existsSync, statSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const PROJECT_DIRS = ['examples', 'templates'].flatMap((d) =>+ readdirSync(path.join(ROOT, d)).map((p) => path.join(ROOT, d, p)).filter((p) => existsSync(path.join(p, 'project.esproject'))));++const walk = (dir, out = []) => {+ for (const e of readdirSync(dir, { withFileTypes: true })) {+ if (e.name === 'node_modules' || e.name.startsWith('.')) continue;+ const full = path.join(dir, e.name);+ if (e.isDirectory()) walk(full, out);+ else out.push(full);+ }+ return out;+};++const problems = [];+let instances = 0;+let overrides = 0;++for (const project of PROJECT_DIRS) {+ const files = walk(project);+ const byUuid = new Map();+ for (const f of files.filter((f) => f.endsWith('.meta'))) {+ try { byUuid.set(JSON.parse(readFileSync(f, 'utf8')).uuid, f.slice(0, -'.meta'.length)); } catch { /* not ours */ }+ }+ const resolve = (ref) => {+ if (typeof ref !== 'string') return null;+ if (ref.startsWith('@uuid:')) return byUuid.get(ref.slice('@uuid:'.length)) ?? null;+ const p = path.join(project, ref);+ return existsSync(p) && statSync(p).isFile() ? p : null;+ };++ /** Every address an override may name in the prefab at @p file: its own+ * entities, a nested slot's entities under `slot/`, and a variant's base. */+ const addressesOf = (file, seen = new Set()) => {+ if (seen.has(file)) return new Set();+ seen.add(file);+ const data = JSON.parse(readFileSync(file, 'utf8'));+ const out = new Set();+ if (data.basePrefab) {+ const base = resolve(data.basePrefab);+ if (base) for (const a of addressesOf(base, seen)) out.add(a);+ }+ for (const e of data.entities ?? []) {+ out.add(e.prefabEntityId);+ const nested = e.nestedPrefab && resolve(e.nestedPrefab.prefabPath);+ if (nested) for (const a of addressesOf(nested, new Set(seen))) out.add(`${e.prefabEntityId}/${a}`);+ }+ return out;+ };++ for (const scene of files.filter((f) => f.endsWith('.esscene'))) {+ let data;+ try { data = JSON.parse(readFileSync(scene, 'utf8')); } catch { continue; }+ for (const entry of data.entities ?? []) {+ if (!entry.prefab) continue;+ instances++;+ const where = `${path.relative(ROOT, scene)} (instance ${entry.id} of ${entry.prefab})`;+ const prefab = resolve(entry.prefab);+ if (!prefab) {+ problems.push(`${where}: the prefab it instances does not exist`);+ continue;+ }+ const addresses = addressesOf(prefab);+ for (const o of entry.overrides ?? []) {+ overrides++;+ if (!addresses.has(o.prefabEntityId)) {+ problems.push(`${where}: a ${o.type} override on "${o.prefabEntityId}"${o.componentType ? ` (${o.componentType})` : ''}, which the prefab has no entity for`);+ }+ }+ }+ }+}++if (problems.length) {+ for (const p of problems) console.error(` - ${p}`);+ console.error(`\ncheck-prefab-overrides: ${problems.length} override(s) change nothing.`);+ process.exit(1);+}+console.log(`check-prefab-overrides: ${overrides} override(s) on ${instances} prefab instance(s) in ${PROJECT_DIRS.length} project(s), each naming an entity its prefab has.`);diff --git a/tools/gates.mjs b/tools/gates.mjsindex 1e2e5cb9e..de18e1f13 100644--- a/tools/gates.mjs+++ b/tools/gates.mjs@@ -49,6 +49,7 @@ export const GATES = [{ id: 'sidemodule-gates', run: 'node tools/check-sidemodule-gates.mjs' },{ id: 'engine-exports', run: 'node tools/check-engine-exports.mjs' },{ id: 'fixture-scenes', run: 'node tools/check-fixture-scenes.mjs' },+ { id: 'prefab-overrides', run: 'node tools/check-prefab-overrides.mjs' },{ id: 'doc-imports', run: 'node tools/check-doc-imports.mjs' },{ id: 'architecture-doc', run: 'node tools/check-architecture-doc.mjs' },{ id: 'native-bindings', run: 'node tools/check-native-bindings.mjs' },