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 entity-ref field holding a list is translated too

esenginee8069c5c0847
diff --git a/sdk/src/prefab/diff.ts b/sdk/src/prefab/diff.ts
index e4de93e82..2aaa16428 100644
--- a/sdk/src/prefab/diff.ts
+++ b/sdk/src/prefab/diff.ts
@@ -8,6 +8,7 @@ import type {
ProcessedEntity,
} from './types';
import { getComponent } from '../ecs/component';
+import { mapEntityRefField } from './entityRef';
/**
* An entity-typed field on an instance holds a numeric runtime id; the source
@@ -18,11 +19,13 @@ import { getComponent } from '../ecs/component';
* that points outside the instance (unmapped) stays numeric, best-effort.
*/
function normalizeEntityRef(value: unknown, runtimeToPrefabId: Map<number, PrefabEntityId>): unknown {
- if (typeof value === 'number') {
- const prefabId = runtimeToPrefabId.get(value);
- if (prefabId !== undefined) return prefabId;
- }
- return value;
+ return mapEntityRefField(value, (ref) => {
+ if (typeof ref === 'number') {
+ const prefabId = runtimeToPrefabId.get(ref);
+ if (prefabId !== undefined) return prefabId;
+ }
+ return ref;
+ });
}
export interface DiffOptions {
diff --git a/sdk/src/prefab/entityRef.ts b/sdk/src/prefab/entityRef.ts
index abfad414e..649738754 100644
--- a/sdk/src/prefab/entityRef.ts
+++ b/sdk/src/prefab/entityRef.ts
@@ -4,6 +4,15 @@ import type { ComponentData, PrefabEntityId } from './types';
import { getComponent } from '../ecs/component';
import { INVALID_ENTITY } from '../types';
+/**
+ * Apply @p one to an entity-ref field, which holds one ref or a LIST of them —
+ * `MeshSkin.joints` is a list, and a bare `typeof` test leaves those untouched.
+ * All three translation directions come through here, so none can disagree.
+ */
+export function mapEntityRefField(value: unknown, one: (ref: unknown) => unknown): unknown {
+ return Array.isArray(value) ? value.map(one) : one(value);
+}
+
/**
* Remap entity-typed component fields from prefab-local ids to runtime ids.
*
@@ -17,28 +26,28 @@ export function remapComponentEntityRefs(
components: ComponentData[],
idMapping: Map<PrefabEntityId, number>,
): void {
+ const one = (value: unknown): unknown => {
+ if (typeof value === 'string') {
+ const mapped = idMapping.get(value);
+ // A DANGLING prefab-local ref (target deleted, or a stale Apply).
+ // Cleared rather than leaked as a string into a field the World reads
+ // as a number — an ABI fault on spawn. So does captureEntityRefs.
+ return mapped !== undefined ? mapped : INVALID_ENTITY;
+ }
+ if (typeof value === 'number' && value !== INVALID_ENTITY) {
+ // Already a numeric id; if a caller authored components with
+ // numeric refs, fall back to numeric→numeric mapping for
+ // legacy compatibility (no-op when the id isn't in the map).
+ const mapped = (idMapping as Map<unknown, number>).get(value);
+ if (mapped !== undefined) return mapped;
+ }
+ return value;
+ };
for (const comp of components) {
const def = getComponent(comp.type);
if (!def || def.entityFields.length === 0) continue;
for (const field of def.entityFields) {
- const value = comp.data[field];
- if (typeof value === 'string') {
- const mapped = idMapping.get(value);
- // An unresolved string is a DANGLING prefab-local ref (its target
- // was deleted, or a stale Apply left it behind). Clear it to
- // INVALID_ENTITY rather than leaking a string into a field the
- // runtime/World reads as a numeric entity id (an ABI/type fault on
- // spawn). Mirrors captureEntityRefs, which clears external refs.
- comp.data[field] = mapped !== undefined ? mapped : INVALID_ENTITY;
- } else if (typeof value === 'number' && value !== INVALID_ENTITY) {
- // Already a numeric id; if a caller authored components with
- // numeric refs, fall back to numeric→numeric mapping for
- // legacy compatibility (no-op when the id isn't in the map).
- const mapped = (idMapping as Map<unknown, number>).get(value);
- if (mapped !== undefined) {
- comp.data[field] = mapped;
- }
- }
+ comp.data[field] = mapEntityRefField(comp.data[field], one);
}
}
}
diff --git a/sdk/src/prefab/sceneInstance.ts b/sdk/src/prefab/sceneInstance.ts
index 75e15d240..89f8d4e74 100644
--- a/sdk/src/prefab/sceneInstance.ts
+++ b/sdk/src/prefab/sceneInstance.ts
@@ -33,6 +33,7 @@ import { cloneComponents } from './clone';
import { applyOverridesToSource } from './override';
import { getComponent } from '../ecs/component';
import { INVALID_ENTITY } from '../types';
+import { mapEntityRefField } from './entityRef';
import { PREFAB_FORMAT_VERSION } from './migrate';
import type {
PrefabData,
@@ -532,17 +533,16 @@ function captureEntityRefs(
components: ComponentData[],
idMap: Map<number, string>,
): ComponentData[] {
+ const one = (value: unknown): unknown => {
+ if (typeof value !== 'number') return value;
+ if (idMap.has(value)) return idMap.get(value)!; // in-subtree → stable prefab-local id
+ return value !== INVALID_ENTITY ? INVALID_ENTITY : value; // external → cleared (never dangle)
+ };
for (const comp of components) {
const def = getComponent(comp.type);
if (!def || def.entityFields.length === 0) continue;
for (const field of def.entityFields) {
- const value = comp.data[field];
- if (typeof value !== 'number') continue;
- if (idMap.has(value)) {
- comp.data[field] = idMap.get(value)!; // in-subtree → stable prefab-local id
- } else if (value !== INVALID_ENTITY) {
- comp.data[field] = INVALID_ENTITY; // external → cleared (never dangle)
- }
+ comp.data[field] = mapEntityRefField(comp.data[field], one);
}
}
return components;
diff --git a/sdk/tests/prefab-entity-ref-list.test.ts b/sdk/tests/prefab-entity-ref-list.test.ts
new file mode 100644
index 000000000..749f76955
--- /dev/null
+++ b/sdk/tests/prefab-entity-ref-list.test.ts
@@ -0,0 +1,83 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Regression: an entity-ref field holding a LIST is translated like a
+ * scalar one. `MeshSkin.joints` is that field — a glTF import writes one
+ * per skinned mesh — and while only scalars were handled, the prefab-local
+ * strings survived into the World's numeric entity vector: the model drew
+ * in its bind pose, which looks like a model that simply does not animate.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { defineComponent, clearUserComponents } from '../src/ecs/component';
+import { remapComponentEntityRefs } from '../src/prefab/entityRef';
+import { expandInstance } from '../src/prefab/sceneInstance';
+import { diffAgainstSource } from '../src/prefab/diff';
+import { PREFAB_FORMAT_VERSION } from '../src/prefab/migrate';
+import { INVALID_ENTITY } from '../src/types';
+import type { PrefabData } from '../src/prefab/types';
+
+const LIST_META = { entityFields: ['joints'] };
+
+/** A rig: the mesh names two joints by their prefab-local ids. */
+function rig(): PrefabData {
+ return {
+ version: PREFAB_FORMAT_VERSION,
+ name: 'Rig',
+ rootEntityId: 'root',
+ entities: [
+ { prefabEntityId: 'root', name: 'Rig', parent: null, children: ['mesh', 'bone0', 'bone1'], components: [], visible: true },
+ {
+ prefabEntityId: 'mesh', name: 'Mesh', parent: 'root', children: [], visible: true,
+ components: [{ type: 'SkinRef', data: { joints: ['bone0', 'bone1'] } }],
+ },
+ { prefabEntityId: 'bone0', name: 'Bone0', parent: 'root', children: [], components: [], visible: true },
+ { prefabEntityId: 'bone1', name: 'Bone1', parent: 'root', children: [], components: [], visible: true },
+ ],
+ };
+}
+
+beforeEach(() => {
+ clearUserComponents();
+ defineComponent('SkinRef', { joints: [] }, LIST_META);
+});
+
+describe('a list-valued entity-ref field', () => {
+ it('remaps every element to a runtime id', () => {
+ const comps = [{ type: 'SkinRef', data: { joints: ['a', 'b'] } as Record<string, unknown> }];
+ remapComponentEntityRefs(comps, new Map([['a', 11], ['b', 22]]));
+ expect(comps[0].data.joints).toEqual([11, 22]);
+ });
+
+ it('clears a dangling element instead of leaking the string into the World', () => {
+ const comps = [{ type: 'SkinRef', data: { joints: ['a', 'ghost'] } as Record<string, unknown> }];
+ remapComponentEntityRefs(comps, new Map([['a', 11]]));
+ expect(comps[0].data.joints).toEqual([11, INVALID_ENTITY]);
+ });
+
+ it('instantiating the prefab points the list at the joints it created', () => {
+ let n = 100;
+ const { entities } = expandInstance(rig(), { prefab: '@uuid:r', overrides: [], added: [], removed: [] }, () => n++);
+ const idOf = (pid: string): number => entities.find((e) => e.prefabEntityId === pid)!.id;
+ const mesh = entities.find((e) => e.prefabEntityId === 'mesh')!;
+ expect(mesh.components[0].data.joints).toEqual([idOf('bone0'), idOf('bone1')]);
+ });
+
+ // The other half: an unchanged list must diff EQUAL. Comparing runtime numbers
+ // against prefab-local strings makes every save write an override full of
+ // session-specific ids, which dangle onto unrelated entities on reload.
+ it('an untouched list produces no override', () => {
+ let n = 200;
+ const { entities } = expandInstance(rig(), { prefab: '@uuid:r', overrides: [], added: [], removed: [] }, () => n++);
+ const { overrides } = diffAgainstSource(rig(), entities);
+ expect(overrides.filter((o) => o.type === 'property' && o.propertyName === 'joints')).toEqual([]);
+ });
+
+ it('a reordered list still produces one', () => {
+ let n = 300;
+ const { entities } = expandInstance(rig(), { prefab: '@uuid:r', overrides: [], added: [], removed: [] }, () => n++);
+ const mesh = entities.find((e) => e.prefabEntityId === 'mesh')!;
+ mesh.components[0].data.joints = [...(mesh.components[0].data.joints as number[])].reverse();
+ const { overrides } = diffAgainstSource(rig(), entities);
+ expect(overrides.some((o) => o.type === 'property' && o.propertyName === 'joints')).toBe(true);
+ });
+});
diff --git a/sdk/tests/prefab-rigor.test.ts b/sdk/tests/prefab-rigor.test.ts
index e481cff7f..19b3dd1a2 100644
--- a/sdk/tests/prefab-rigor.test.ts
+++ b/sdk/tests/prefab-rigor.test.ts
@@ -708,10 +708,9 @@ describe('migration visible to callers', () => {
});
describe('diffAgainstSource — entity-ref fields', () => {
- // The real case is a USER component with a SCALAR entity ref (a script that
- // targets another entity); builtins only have Children.entities (an ARRAY the
- // structural parent/children path owns). Registered per-test — the setup
- // clears user components between tests.
+ // A USER component with a SCALAR entity ref. The list-valued shape
+ // (MeshSkin.joints) is covered by prefab-entity-ref-list. Registered
+ // per-test — the setup clears user components between tests.
const FOLLOW_META = { entityFields: ['target'] };
function squad(): PrefabData {