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
feat(assets): built-in hot-update rebinder — transparent @uuid updates
yhh9360234b199c
diff --git a/examples/hot-update-demo/README.md b/examples/hot-update-demo/README.mdindex cffb2d82d..7d98ae280 100644--- a/examples/hot-update-demo/README.md+++ b/examples/hot-update-demo/README.md@@ -32,10 +32,11 @@ Nothing is ever overwritten, so a cache can never go stale.- **`assets/scenes/main.esscene`** — the Display sprite references the texture byan ordinary `@uuid`. The asset lives in a `remote` group, so the runtime routesthat `@uuid` to the CDN automatically — the scene author does nothing special.-- **`src/systems/hotUpdate.ts`** — subscribes to `Assets.onInvalidate`, so when an- update lands the changed asset is reloaded (now resolved to the CDN) and the- sprite follows. (A game can also `Assets.loadGroup(name)` to pull a whole remote- group on demand — the DLC pattern.)+- **No game code.** `src/main.ts` is empty. When an update is applied the runtime's+ built-in rebinder reloads the changed asset (now resolved to the CDN) and swaps+ it into the live sprite, so the picture changes on screen on its own. (A game can+ still call `Assets.loadGroup(name)` to pull a whole remote group on demand — the+ DLC pattern — or `Assets.onInvalidate` for custom rebinding.)- **The update** — call `Assets.checkForUpdate({ manifestUrl, remoteRoot })` todiff the CDN's manifest against the running one, then `Assets.applyUpdate()` todownload the changed assets and swap the manifest. Existing handles bound to adiff --git a/examples/hot-update-demo/assets/scenes/main.esscene b/examples/hot-update-demo/assets/scenes/main.essceneindex 4abc0126d..ae852b9cf 100644--- a/examples/hot-update-demo/assets/scenes/main.esscene+++ b/examples/hot-update-demo/assets/scenes/main.esscene@@ -21,8 +21,7 @@"visible": true,"components": [{ "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },- { "type": "Sprite", "data": { "size": { "x": 4000, "y": 4000 }, "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "texture": "@uuid:a1b2c3d4-0002-4002-8002-000000000002" } },- { "type": "HotDisplay", "data": {} }+ { "type": "Sprite", "data": { "size": { "x": 4000, "y": 4000 }, "color": { "r": 1, "g": 1, "b": 1, "a": 1 }, "texture": "@uuid:a1b2c3d4-0002-4002-8002-000000000002" } }]}]diff --git a/examples/hot-update-demo/src/components.ts b/examples/hot-update-demo/src/components.tsdeleted file mode 100644index d62d29633..000000000--- a/examples/hot-update-demo/src/components.ts+++ /dev/null@@ -1,7 +0,0 @@-import { defineComponent } from 'esengine';--/** Tag for the entity whose Sprite shows the CDN-delivered texture. `updates`- * counts how many hot updates have been applied (handy to read back in tests). */-export const HotDisplay = defineComponent('HotDisplay', {- updates: 0,-});diff --git a/examples/hot-update-demo/src/main.ts b/examples/hot-update-demo/src/main.tsindex 3bf3e6685..111c4c8f1 100644--- a/examples/hot-update-demo/src/main.ts+++ b/examples/hot-update-demo/src/main.ts@@ -1,6 +1,4 @@-import { addSystemToSchedule, Schedule } from 'esengine';--import './components';-import { hotDisplaySystem } from './systems/hotUpdate';--addSystemToSchedule(Schedule.Update, hotDisplaySystem);+// This demo needs no game code. The Display sprite references the CDN texture by+// @uuid in the scene; the runtime's built-in hot-update rebinder swaps in the new+// art automatically when an update is applied. See the README.+export {};diff --git a/examples/hot-update-demo/src/systems/hotUpdate.ts b/examples/hot-update-demo/src/systems/hotUpdate.tsdeleted file mode 100644index d981755ec..000000000--- a/examples/hot-update-demo/src/systems/hotUpdate.ts+++ /dev/null@@ -1,27 +0,0 @@-import { defineSystem, Query, Mut, Res, Assets, Sprite } from 'esengine';-import { HotDisplay } from '../components';--// The texture handle to stamp onto the display sprite after a hot update.-let handle = 0;-let started = false;--export const hotDisplaySystem = defineSystem(- [Query(Mut(Sprite), HotDisplay), Res(Assets)],- (query, assets) => {- if (!started) {- started = true;- // The Display sprite references its texture by @uuid in the scene, so it- // shows the shipped (green) art immediately — the texture lives in a- // `remote` group but the reference is an ordinary @uuid. On a hot update,- // applyUpdate invalidates the changed asset by that ref; reload it — now- // the manifest routes the @uuid to the CDN — and the sprite follows.- assets.onInvalidate((ref) => {- void assets.loadTexture(ref).then((tex) => { handle = tex.handle; });- });- }- if (handle !== 0) {- for (const [, sprite] of query) sprite.texture = handle;- }- },- { name: 'HotDisplaySystem' },-);diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 08152c6de..d37c1c4a9 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -42,8 +42,10 @@ import type { AssetRegistry } from './AssetRegistry';import type { AssetRefCounter } from './AssetRefCounter';import { log } from '../logger';-/** Callback fired when `Assets.invalidate(ref)` actually dropped cache entries. */-export type InvalidateListener = (ref: string) => void;+/** Callback fired when `Assets.invalidate(ref)` actually dropped cache entries.+ * `oldTextureHandle` is the texture handle that was bound before the drop (0 when+ * none / not a texture) — the built-in rebinder swaps it to the reloaded handle. */+export type InvalidateListener = (ref: string, oldTextureHandle?: number) => void;/** Input to {@link Assets.checkForUpdate}. */export interface CheckForUpdateOptions {@@ -663,12 +665,18 @@ export class Assets {return { ok: false, updated: 0, failed };}- // Phase 2 — commit atomically: swap root + manifest, rebind, persist. Renderers- // holding a stale handle for a changed asset re-resolve against the now-active- // manifest (the freshly-fetched content); old handles orphan + release by refcount.+ // Phase 2 — commit atomically. Capture the texture handle bound to each+ // changed asset BEFORE the swap (it resolves to the OLD path), then swap+ // root + manifest and notify with that handle so the built-in rebinder+ // swaps it to the freshly-fetched content in live components.+ const oldHandles = new Map<string, number>();+ for (const c of changed) {+ const tex = this.getTexture(c.key);+ if (tex) oldHandles.set(c.key, tex.handle);+ }if (pending.remoteRoot != null) this.setRemoteRoot(pending.remoteRoot);this.setManifest(pending.model);- for (const c of changed) this.fireInvalidate_(c.key);+ for (const c of changed) this.fireInvalidate_(c.key, oldHandles.get(c.key) ?? 0);this.persistActiveManifest_(pending.manifestJson);this.pendingUpdate_ = null;return { ok: true, updated: changed.length, failed: [] };@@ -1185,6 +1193,9 @@ export class Assets {*/invalidate(ref: string): boolean {const path = this.resolveRef(ref) ?? ref;+ // The texture handle bound to this path, captured BEFORE the caches drop+ // it, so a rebind listener can swap it in live components (hot update).+ const oldTextureHandle = this.textureCache_.get(this.textureCacheKey_(path, true))?.handle ?? 0;let hit = false;// Textures: cache_key has a flip flag suffix, so check both. The C++@@ -1219,18 +1230,18 @@ export class Assets {if (p === path) this.handleToPath_.delete(key);}- if (hit) this.fireInvalidate_(ref);+ if (hit) this.fireInvalidate_(ref, oldTextureHandle);return hit;}- /** Fire every onInvalidate listener with `ref`, isolating throws. Shared by- * {@link invalidate} (cache drop) and {@link applyUpdate} (rebind to updated- * content), so both notify subscribers through one path. */- private fireInvalidate_(ref: string): void {+ /** Fire every onInvalidate listener with `ref` (and the pre-drop texture+ * handle, when known, so a rebinder can swap it in live components). Isolates+ * throws. Shared by {@link invalidate} and {@link applyUpdate}. */+ private fireInvalidate_(ref: string, oldTextureHandle = 0): void {for (const listener of this.invalidateListeners_) {try {- listener(ref);+ listener(ref, oldTextureHandle);} catch (e) {log.warn('asset', 'onInvalidate listener threw', e);}diff --git a/sdk/src/hotUpdateRebind.ts b/sdk/src/hotUpdateRebind.tsnew file mode 100644index 000000000..5e3847203--- /dev/null+++ b/sdk/src/hotUpdateRebind.ts@@ -0,0 +1,56 @@+// SPDX-License-Identifier: Apache-2.0+// 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 drops an asset it reports the+ * texture handle that was bound; this reloads the ref (now resolved to+ * the fresh content) and swaps old→new in every live texture-bearing+ * component, so a scene that references an asset by @uuid updates on+ * screen with ZERO game code.+ *+ * Registered once per App (initRuntime). State lives in this closure —+ * per install, not module-global — so realms don't share queues.+ */+import type { App } from './app';+import { Schedule, defineSystem } from './system';+import { Query, Mut } from './query';+import { Sprite, Mesh2D } from './component';+import type { Assets } from './asset/Assets';++export function installHotUpdateRebind(app: App, assets: Assets): void {+ // Refs whose asset was invalidated (with the handle bound before the drop),+ // awaiting a reload; and resolved old→new handle swaps awaiting application.+ const pending: Array<{ ref: string; oldHandle: number }> = [];+ const swaps: Array<{ oldHandle: number; newHandle: number }> = [];++ assets.onInvalidate((ref, oldTextureHandle) => {+ if (oldTextureHandle) pending.push({ ref, oldHandle: oldTextureHandle });+ });++ app.addSystemToSchedule(Schedule.Update, defineSystem(+ [Query(Mut(Sprite)), Query(Mut(Mesh2D))],+ (sprites, meshes) => {+ // Kick a reload for each newly-invalidated ref; the async result (the+ // new handle) lands in `swaps` a frame or two later.+ while (pending.length > 0) {+ const { ref, oldHandle } = pending.shift()!;+ void assets.loadTexture(ref).then((tex) => {+ if (tex.handle !== oldHandle) swaps.push({ oldHandle, newHandle: tex.handle });+ });+ }+ if (swaps.length === 0) return;+ // Swap old→new in every live sprite / mesh (each query iterated once).+ for (const [, sprite] of sprites) {+ const s = swaps.find((x) => x.oldHandle === sprite.texture);+ if (s) sprite.texture = s.newHandle;+ }+ for (const [, mesh] of meshes) {+ const s = swaps.find((x) => x.oldHandle === mesh.texture);+ if (s) mesh.texture = s.newHandle;+ }+ swaps.length = 0;+ },+ { name: 'HotUpdateRebindSystem' },+ ));+}diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex 58e95b0be..0e4e2fc55 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -30,6 +30,7 @@ import { Localization, matchLocale } from './i18n/Localization';import { LocalizationPlugin } from './i18n/LocalizationPlugin';import { platformLanguage } from './platform';import { flushPendingSystems } from './app';+import { installHotUpdateRebind } from './hotUpdateRebind';import { requireResourceManager } from './resourceManager';import { log } from './logger';import { type RuntimeAssetSource, type TextureParams } from './runtimeAssets';@@ -445,6 +446,9 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {// A persisted update (from a prior applyUpdate) supersedes the shipped manifest// + root, so a returning player boots straight onto the already-updated content.if (config.persistUpdateKey) assets.restorePersistedUpdate(config.persistUpdateKey);+ // Built-in rebinder: on a hot update, swap the changed texture into live+ // sprites/meshes automatically — a scene @uuid ref updates with no game code.+ installHotUpdateRebind(app, assets);if (config.audioConfig && app.hasResource(Audio)) {applyAudioProjectConfig(app.getResource(Audio), config.audioConfig);diff --git a/sdk/tests/assets-invalidate-event.test.ts b/sdk/tests/assets-invalidate-event.test.tsindex 28297222a..585c7a9b9 100644--- a/sdk/tests/assets-invalidate-event.test.ts+++ b/sdk/tests/assets-invalidate-event.test.ts@@ -53,7 +53,9 @@ describe('Assets.onInvalidate', () => {const hit = assets.invalidate('tex/hot.png');expect(hit).toBe(true);- expect(listener).toHaveBeenCalledWith('tex/hot.png');+ // Fires with the original ref + the pre-drop texture handle (0 here — the+ // seeded entry is the unflipped variant; the rebinder reads flip=true).+ expect(listener).toHaveBeenCalledWith('tex/hot.png', expect.any(Number));});it('unsubscribe function prevents further notifications', () => {@@ -122,8 +124,8 @@ describe('Assets.onInvalidate', () => {assets.onInvalidate(c);assets.invalidate('tex/a.png');- expect(a).toHaveBeenCalledWith('tex/a.png');- expect(b).toHaveBeenCalledWith('tex/a.png');- expect(c).toHaveBeenCalledWith('tex/a.png');+ expect(a).toHaveBeenCalledWith('tex/a.png', expect.any(Number));+ expect(b).toHaveBeenCalledWith('tex/a.png', expect.any(Number));+ expect(c).toHaveBeenCalledWith('tex/a.png', expect.any(Number));});});