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.

feat(assets): a live binding follows the asset, whatever kind it is

esenginef75d6e965777
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 7d3fd6409..aba451e7a 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -767,6 +767,7 @@ ResourceDef<AssetsClass>
@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]
@internal dependentsOf: (ref: string) => AssetIdentity[]
@internal entityScopes: EntityAssetScopes
+@internal handleBoundTypes: () => string[]
@internal publishedRegistryAssets: <T>(type: string) => T[]
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index fca7120ea..a89c760ff 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -767,6 +767,7 @@ ResourceDef<AssetsClass>
@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]
@internal dependentsOf: (ref: string) => AssetIdentity[]
@internal entityScopes: EntityAssetScopes
+@internal handleBoundTypes: () => string[]
@internal publishedRegistryAssets: <T>(type: string) => T[]
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 72120faba..d62728af4 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -762,6 +762,7 @@ ResourceDef<AssetsClass>
@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]
@internal dependentsOf: (ref: string) => AssetIdentity[]
@internal entityScopes: EntityAssetScopes
+@internal handleBoundTypes: () => string[]
@internal publishedRegistryAssets: <T>(type: string) => T[]
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index f01a6ab4d..f12ce4f79 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -762,6 +762,7 @@ ResourceDef<AssetsClass>
@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]
@internal dependentsOf: (ref: string) => AssetIdentity[]
@internal entityScopes: EntityAssetScopes
+@internal handleBoundTypes: () => string[]
@internal publishedRegistryAssets: <T>(type: string) => T[]
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 77b5e65a5..bab938dfe 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -762,6 +762,7 @@ ResourceDef<AssetsClass>
@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]
@internal dependentsOf: (ref: string) => AssetIdentity[]
@internal entityScopes: EntityAssetScopes
+@internal handleBoundTypes: () => string[]
@internal publishedRegistryAssets: <T>(type: string) => T[]
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index c5c5d7460..4e2d6cb9e 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -2110,6 +2110,21 @@ export class Assets {
return this.genericCache_.get(type)?.get(path)?.edges ?? [];
}
+ /**
+ * The asset types a component holds BY HANDLE — the loaders with a `load`
+ * door. What a live rebind can migrate: a ref-bound asset's slot swaps
+ * under the name a field already holds, so there is nothing to move.
+ *
+ * @internal
+ */
+ handleBoundTypes(): string[] {
+ const types: string[] = [];
+ for (const [type, loader] of this.loaders_) {
+ if (loader.load) types.push(type);
+ }
+ return types;
+ }
+
/**
* Every asset of this realm whose CURRENT era took `ref` — the reverse of
* {@link dependenciesOf}, walked from the eras so there is no table to keep.
diff --git a/sdk/src/asset/liveAssetBindings.ts b/sdk/src/asset/liveAssetBindings.ts
index 04fdc126a..6a77c5ddd 100644
--- a/sdk/src/asset/liveAssetBindings.ts
+++ b/sdk/src/asset/liveAssetBindings.ts
@@ -27,12 +27,12 @@ export interface LiveAssetBinding {
readonly field: string;
}
-/** Component names carrying at least one field of this asset type — what a
- * system walking those bindings reaches for, from the same declaration. */
-export function componentsBindingAssetType(type: AssetFieldType): string[] {
+/** Component names carrying at least one field of any of these asset types —
+ * what a system walking those bindings reaches for, from the same declaration. */
+export function componentsBindingAssetTypes(types: readonly string[]): string[] {
const names: string[] = [];
for (const [name, component] of getComponentRegistry()) {
- if (component.assetFields.some((f) => f.type === type)) names.push(name);
+ if (component.assetFields.some((f) => types.includes(f.type))) names.push(name);
}
return names;
}
diff --git a/sdk/src/asset/liveAssetRebind.ts b/sdk/src/asset/liveAssetRebind.ts
index e072d2cac..398d8f127 100644
--- a/sdk/src/asset/liveAssetRebind.ts
+++ b/sdk/src/asset/liveAssetRebind.ts
@@ -31,14 +31,21 @@ import { log } from '../util/logger';
export type OwnerScopeResolver = (entity: Entity) => AssetScope;
/**
- * The value a bound field holds for this lease — a texture's handle.
+ * What a bound field holds for this asset value — a handle.
*
- * Undefined for an asset a field names by ref rather than by value. Those go
- * unmatched rather than matched through a path, which after an invalidate names
- * a different instance than the field is bound to.
+ * One rule for both ends of a replacement: the outgoing value an invalidation
+ * reports, and the incoming lease. Undefined for an asset a field names by REF
+ * rather than by value, which is not migrated at all — its slot swaps under the
+ * name the field already holds.
*/
+export function boundValueIn(value: unknown): unknown {
+ if (typeof value === 'number') return value;
+ return (value as { handle?: number } | null)?.handle;
+}
+
+/** {@link boundValueIn} for what a receipt names. */
export function boundValueOf(lease: AssetLease): unknown {
- return (lease.value as { handle?: number } | null)?.handle;
+ return boundValueIn(lease.value);
}
/** The receipt in `scope` that a bound value names, if the scope holds one. */
@@ -62,7 +69,7 @@ export function slotLeaseNamed(scope: AssetScope, ref: unknown): AssetLease | un
}
/** One acquisition of the replacement, and how to read the value a bound field
- * holds for a lease — a texture's handle, for the only kind rebound today. */
+ * holds for it. */
export interface LiveAssetReplacement {
readonly lease: AssetLease;
readonly boundValue: (lease: AssetLease) => unknown;
diff --git a/sdk/src/hotUpdateRebind.ts b/sdk/src/hotUpdateRebind.ts
index e34350750..0a2f1f119 100644
--- a/sdk/src/hotUpdateRebind.ts
+++ b/sdk/src/hotUpdateRebind.ts
@@ -2,11 +2,20 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file hotUpdateRebind.ts
- * @brief Built-in hot-update rebinder — makes a hot update transparent to game
- * code. When applyUpdate / invalidate ends an asset's era this reloads
- * the ref (now resolved to the fresh content) and moves every live
- * binding of it onto the new one, so a scene that references an asset
- * by @uuid updates on screen with ZERO game code.
+ * @brief Built-in live-binding coordinator — makes a new generation transparent
+ * to game code. When applyUpdate / invalidate ends an asset's era this
+ * reloads the ref (now resolved to the fresh content) and moves every
+ * live binding of it onto the new one, so a scene that references an
+ * asset by @uuid updates on screen with ZERO game code.
+ *
+ * A RECEIPT never changes generation: whoever holds one keeps the era
+ * they acquired until they release it. A live BINDING is the other
+ * thing — a field that names an asset and follows what that name means
+ * now — and it is the only thing migrated here.
+ *
+ * Which types are migrated is read, not listed: an asset a component
+ * holds by handle has a `load` door, and one it holds by ref has a slot
+ * that swaps under the name the field already carries.
*
* It is a transaction coordinator, not an owner: which fields hold the
* asset comes from `component.assetFields` (liveAssetBindings.ts), and
@@ -23,22 +32,33 @@ import { assetScopeForEntity } from './scene/sceneManager';
import type { Entity } from './types';
import type { Assets } from './asset/Assets';
import type { AssetScope, AssetLease } from './asset/AssetLease';
-import { componentsBindingAssetType } from './asset/liveAssetBindings';
-import { boundValueOf, migrateScopeBindings, ownerScopesOf } from './asset/liveAssetRebind';
+import type { AssetFieldType } from './scene/scene';
+import { componentsBindingAssetTypes } from './asset/liveAssetBindings';
+import { boundValueIn, boundValueOf, migrateScopeBindings, ownerScopesOf } from './asset/liveAssetRebind';
import { log } from './util/logger';
+/** Take the replacement out of the realm — by receipt, whatever its kind. */
+function acquire(assets: Assets, type: AssetFieldType, ref: string): Promise<AssetLease> {
+ return type === 'texture'
+ ? assets.acquireTexture(ref)
+ : assets.acquireTyped(type, ref);
+}
+
export function installHotUpdateRebind(app: App, assets: Assets): void {
- // Refs whose asset era ended (with the handle bound before the drop),
- // awaiting the reload; and replacements awaiting their owner's transaction.
- const pending: Array<{ ref: string; oldHandle: number }> = [];
- const ready: Array<{ oldHandle: number; scope: AssetScope; lease: AssetLease }> = [];
+ // Ended eras (with the value bound before the drop), awaiting the reload;
+ // and replacements awaiting their owner's transaction.
+ const pending: Array<{ ref: string; type: AssetFieldType; oldValue: unknown }> = [];
+ const ready: Array<{
+ type: AssetFieldType; oldValue: unknown; scope: AssetScope; lease: AssetLease;
+ }> = [];
assets.onInvalidate((event) => {
- // Textures only for now, said by reading the kind rather than by the event
- // being unable to describe anything else.
- if (event.type !== 'texture') return;
- const oldHandle = typeof event.oldValue === 'number' ? event.oldValue : 0;
- if (oldHandle) pending.push({ ref: event.ref, oldHandle });
+ // The type vocabulary is one: what a loader answers to is what a field
+ // declares. A ref-bound asset reports one too, and has nothing to move.
+ const type = event.type as AssetFieldType;
+ if (!assets.handleBoundTypes().includes(type)) return;
+ const oldValue = boundValueIn(event.oldValue);
+ if (oldValue !== undefined && oldValue !== 0) pending.push({ ref: event.ref, type, oldValue });
});
// Who owns what an entity holds is answered in ONE place, not here: a
@@ -53,10 +73,10 @@ export function installHotUpdateRebind(app: App, assets: Assets): void {
// One acquisition per owning scope; the async results land in
// `ready` a frame or two later, each with the scope it is for.
while (pending.length > 0) {
- const { ref, oldHandle } = pending.shift()!;
- for (const scope of ownerScopesOf(world, 'texture', oldHandle, ownerScopeOf)) {
- void assets.acquireTexture(ref).then(
- (lease) => { ready.push({ oldHandle, scope, lease }); },
+ const { ref, type, oldValue } = pending.shift()!;
+ for (const scope of ownerScopesOf(world, type, oldValue, ownerScopeOf)) {
+ void acquire(assets, type, ref).then(
+ (lease) => { ready.push({ type, oldValue, scope, lease }); },
(e: unknown) => {
log.warn('asset', `hot-update rebind: reloading "${ref}" failed; its holders keep the asset they have`, e);
},
@@ -64,19 +84,19 @@ export function installHotUpdateRebind(app: App, assets: Assets): void {
}
}
while (ready.length > 0) {
- const { oldHandle, scope, lease } = ready.shift()!;
+ const { type, oldValue, scope, lease } = ready.shift()!;
migrateScopeBindings(
- world, scope, 'texture', oldHandle,
+ world, scope, type, oldValue,
{ lease, boundValue: boundValueOf }, ownerScopeOf,
);
}
},
{
name: 'HotUpdateRebindSystem',
- // The reach is every component declaring a texture field, read from
- // the registry at access time — a project component registered after
- // this system was installed binds textures too.
- touches: () => ({ writes: componentsBindingAssetType('texture') }),
+ // The reach is every component declaring a handle-bound asset field,
+ // read from the registry at access time — a project component
+ // registered after this system was installed binds them too.
+ touches: () => ({ writes: componentsBindingAssetTypes(assets.handleBoundTypes()) }),
},
));
}
diff --git a/sdk/tests/hot-update-rebind.test.ts b/sdk/tests/hot-update-rebind.test.ts
index 73086b735..4744ea20c 100644
--- a/sdk/tests/hot-update-rebind.test.ts
+++ b/sdk/tests/hot-update-rebind.test.ts
@@ -80,11 +80,29 @@ const platformFactory = vi.hoisted(() => () => ({
vi.mock('../src/platform', platformFactory);
vi.mock('../src/platform/base', platformFactory);
-function buildAssets(): Assets {
+const materialFake = vi.hoisted(() => {
+ let next = 100;
+ return {
+ reset: () => { next = 100; },
+ Material: {
+ createFromAsset: vi.fn((): number => next++),
+ setUniform: vi.fn(),
+ tex: vi.fn((handle: number) => ({ kind: 'tex', handle })),
+ compileShader: vi.fn(() => 7),
+ release: vi.fn(),
+ },
+ };
+});
+vi.mock('../src/render/material', () => ({ Material: materialFake.Material }));
+
+function buildAssets(docs: Record<string, string> = {}): Assets {
return Assets.create({
backend: {
fetchBinary: vi.fn(async () => new ArrayBuffer(8)),
- fetchText: vi.fn(async () => '{}'),
+ fetchText: vi.fn(async (url: string) => {
+ const key = Object.keys(docs).find((k) => url.endsWith(k));
+ return key ? docs[key] : '{}';
+ }),
resolveUrl: (p: string) => `http://test/${p}`,
} as unknown as Backend,
module: { _malloc: vi.fn(() => 0), _free: vi.fn(), HEAPU8: new Uint8Array(1 << 16), GL: null, FS: null } as never,
@@ -390,3 +408,45 @@ describe('a scope migrates all of its bindings or none', () => {
expect(scope.leases()[0]).toBe(outgoing);
});
});
+
+describe('a live binding follows the asset, whatever kind it is', () => {
+ beforeEach(() => { pool = createPoolFake(); materialFake.reset(); });
+
+ /** A material on a built-in shader, binding no textures of its own. */
+ const MATERIAL = JSON.stringify({
+ type: 'material', shader: 'builtin:sprite-unlit', properties: {},
+ });
+
+ it('a material field moves to the new generation, like a texture field', async () => {
+ // Every handle-bound kind — material, font, mesh, environment — follows
+ // the same transaction a texture does; nothing about it is texture-shaped.
+ const app = App.new();
+ connectFakeCpp(app.world);
+ const assets = buildAssets({ 'hero.esmaterial': MATERIAL });
+ installHotUpdateRebind(app, assets);
+
+ const before = await assets.acquireTyped<{ handle: number }>('material', 'hero.esmaterial');
+ const entity = app.world.spawn();
+ app.world.insert(entity, MeshRenderer, { material: before.value.handle } as never);
+
+ assets.invalidate('hero.esmaterial');
+ await settle(app);
+
+ const after = (app.world.get(entity, MeshRenderer) as { material: number }).material;
+ expect(after, 'the field kept the handle from before the update')
+ .not.toBe(before.value.handle);
+ const fresh = await assets.acquireTyped<{ handle: number }>('material', 'hero.esmaterial');
+ expect(after, 'the field moved to something other than the published era')
+ .toBe(fresh.value.handle);
+ });
+
+ it('which kinds can be rebound is read from the loader doors', async () => {
+ // A ref-bound asset has nothing to move: the field holds the name, and
+ // what the name means is the slot's business.
+ const assets = buildAssets();
+
+ expect(assets.handleBoundTypes()).toContain('material');
+ expect(assets.handleBoundTypes()).not.toContain('anim-clip');
+ expect(assets.handleBoundTypes()).not.toContain('tilemap');
+ });
+});
diff --git a/tools/check-live-asset-rebind.mjs b/tools/check-live-asset-rebind.mjs
index 016b23237..c69f6c046 100644
--- a/tools/check-live-asset-rebind.mjs
+++ b/tools/check-live-asset-rebind.mjs
@@ -131,7 +131,7 @@ function functionBody(text, name) {
// Per function, not per file: the file kept the word `assetFields` in a
// neighbouring helper while the walk itself had been replaced by a literal.
const discovery = stripComments(readFileSync(path.join(ROOT, REBIND_PATH[0]), 'utf8'));
-for (const fn of ['findLiveAssetBindings', 'componentsBindingAssetType']) {
+for (const fn of ['findLiveAssetBindings', 'componentsBindingAssetTypes']) {
const body = functionBody(discovery, fn);
if (body === null) {
findings.push(`${REBIND_PATH[0]} ${fn}() is gone — the rebind path's only door to the declaration.`);