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(sdk): prefab diff keeps entity refs in prefab-local id space

esengine07e60208c3f8
diff --git a/sdk/src/prefab/diff.ts b/sdk/src/prefab/diff.ts
index b2ad07965..86bb26e52 100644
--- a/sdk/src/prefab/diff.ts
+++ b/sdk/src/prefab/diff.ts
@@ -8,6 +8,23 @@ import type {
PrefabOverride,
ProcessedEntity,
} from './types';
+import { getComponent } from '../component';
+
+/**
+ * An entity-typed field on an instance holds a numeric runtime id; the source
+ * prefab stores the prefab-local string id. Translate the runtime id back to its
+ * prefab-local id (inverse of {@link remapComponentEntityRefs}) so an UNCHANGED
+ * intra-instance ref diffs equal — otherwise every such field produces a spurious
+ * override carrying a session-specific number that dangles on save+reload. A ref
+ * 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;
+}
export interface DiffOptions {
/**
@@ -63,6 +80,11 @@ export function diffAgainstSource(
const instanceByPrefabId = new Map<PrefabEntityId, ProcessedEntity>();
for (const e of instance) instanceByPrefabId.set(e.prefabEntityId, e);
+ // Runtime entity id → its prefab-local id, so entity-ref fields can be diffed
+ // in the prefab's own id space instead of against volatile runtime numbers.
+ const runtimeToPrefabId = new Map<number, PrefabEntityId>();
+ for (const e of instance) runtimeToPrefabId.set(e.id, e.prefabEntityId);
+
const ignoredMeta = new Set(options?.ignoreMetadataKeys ?? []);
const ignoredNames = new Set(options?.ignoreEntityNames ?? []);
const eps = options?.floatEpsilon ?? 0;
@@ -95,7 +117,7 @@ export function diffAgainstSource(
}
diffMetadata(src.metadata, instEntity.metadata, ignoredMeta, instEntity.prefabEntityId, overrides);
- diffComponents(src.components, instEntity.components, instEntity.prefabEntityId, eps, overrides);
+ diffComponents(src.components, instEntity.components, instEntity.prefabEntityId, eps, overrides, runtimeToPrefabId);
}
for (const [id] of sourceById) {
@@ -135,6 +157,7 @@ function diffComponents(
entityId: PrefabEntityId,
eps: number,
out: PrefabOverride[],
+ runtimeToPrefabId: Map<number, PrefabEntityId>,
): void {
const srcByType = new Map<string, ComponentData>();
for (const c of srcComps) srcByType.set(c.type, c);
@@ -161,13 +184,18 @@ function diffComponents(
// Per-property diff keeps override list small and human-readable,
// and lets Inspector "revert this field" work without dragging the
// whole component along.
+ const entityFields = new Set(getComponent(type)?.entityFields ?? []);
const keys = new Set<string>([
...Object.keys(srcComp.data),
...Object.keys(instComp.data),
]);
for (const key of keys) {
const a = srcComp.data[key];
- const b = instComp.data[key];
+ // Entity refs diff (and store) in prefab-local id space so an
+ // unchanged sibling ref isn't logged as a dangling numeric override.
+ const b = entityFields.has(key)
+ ? normalizeEntityRef(instComp.data[key], runtimeToPrefabId)
+ : instComp.data[key];
if (!deepEqual(a, b, eps)) {
out.push({
prefabEntityId: entityId,
diff --git a/sdk/tests/prefab-rigor.test.ts b/sdk/tests/prefab-rigor.test.ts
index c8275f92e..04b82f345 100644
--- a/sdk/tests/prefab-rigor.test.ts
+++ b/sdk/tests/prefab-rigor.test.ts
@@ -28,6 +28,7 @@ import {
bucketOverridesByEntity,
} from '../src/prefab/index';
import type { FlattenContext } from '../src/prefab/index';
+import { defineComponent } from '../src/component';
function uuidPrefab(): PrefabData {
return {
@@ -646,6 +647,69 @@ 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.
+ const FOLLOW_META = { entityFields: ['target'] };
+
+ function squad(): PrefabData {
+ return {
+ version: PREFAB_FORMAT_VERSION,
+ name: 'Squad',
+ rootEntityId: 'leader',
+ entities: [
+ { prefabEntityId: 'leader', name: 'Leader', parent: null, children: ['ally', 'follower'], components: [], visible: true },
+ { prefabEntityId: 'ally', name: 'Ally', parent: 'leader', children: [], components: [], visible: true },
+ {
+ prefabEntityId: 'follower', name: 'Follower', parent: 'leader', children: [],
+ components: [{ type: 'FollowTarget', data: { target: 'leader' } }], visible: true,
+ },
+ ],
+ };
+ }
+
+ // Runtime ids assigned in entity order: leader=0, ally=1, follower=2.
+ function instance(prefab: PrefabData, followerTarget: number): ProcessedEntity[] {
+ let n = 0;
+ return prefab.entities.map((e) => ({
+ id: n++,
+ prefabEntityId: e.prefabEntityId,
+ name: e.name,
+ parent: null,
+ children: [],
+ components: e.components.map((c) => ({
+ type: c.type,
+ data: c.type === 'FollowTarget' ? { target: followerTarget } : { ...c.data },
+ })),
+ visible: e.visible,
+ }));
+ }
+
+ it('an unchanged sibling ref produces no override (runtime id normalises to its prefab-local id)', () => {
+ defineComponent('FollowTarget', { target: 0 }, FOLLOW_META);
+ const prefab = squad();
+ // follower.target = 0 = leader's runtime id → normalises to 'leader' === source.
+ const { overrides } = diffAgainstSource(prefab, instance(prefab, 0));
+ expect(overrides).toEqual([]);
+ });
+
+ it('a re-pointed ref stores the prefab-local id, not the volatile runtime number', () => {
+ defineComponent('FollowTarget', { target: 0 }, FOLLOW_META);
+ const prefab = squad();
+ // follower.target = 1 = ally's runtime id → a genuine re-point.
+ const { overrides } = diffAgainstSource(prefab, instance(prefab, 1));
+ expect(overrides).toContainEqual({
+ prefabEntityId: 'follower',
+ type: 'property',
+ componentType: 'FollowTarget',
+ propertyName: 'target',
+ value: 'ally', // prefab-local id — survives remapComponentEntityRefs on reload
+ });
+ });
+});
+
// ─── Self-smoke ──────────────────────────────────────────────
// Guard against accidentally removing the vi import when trimming.
vi.fn;