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): an update has two barriers, and they are not the same one
esengine68f71b3a4a93
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 5f57d557f..9cb821f91 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -2,11 +2,11 @@"note": "Generated by tools/api-stability.mjs from sdk/etc/*.api.md — do not edit.","counts": {"public": 113,- "beta": 89,+ "beta": 91,"experimental": 1639,"deprecated": 3},- "total": 1841,+ "total": 1843,"subsystems": [{"id": "ecs",@@ -1968,6 +1968,30 @@"minigame"]},+ {+ "name": "LiveBindings",+ "kind": "const",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },+ {+ "name": "LiveBindingsData",+ "kind": "interface",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },{"name": "MaterialGraph","kind": "interface",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex aba451e7a..ec9ca84e3 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 82 beta · 1502 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1502 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -764,6 +764,7 @@ ResourceDef<AssetsClass>## AssetsData — type @beta```@internal appScope: AssetScope+@internal assetGraphSettled: () => Promise<void>@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]@internal dependentsOf: (ref: string) => AssetIdentity[]@internal entityScopes: EntityAssetScopes@@ -4234,6 +4235,16 @@ keyboard: boolean | undefinedmouse: boolean | undefined```+## LiveBindings — const @beta+```+ResourceDef<LiveBindingsData>+```++## LiveBindingsData — interface @beta+```+settled: () => Promise<void>+```+## LoadRuntimeSceneOptions — interface @experimental```app: Appdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex a89c760ff..3859119e8 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 87 beta · 1521 experimental · 3 deprecated+Symbols: 113 public · 89 beta · 1521 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -764,6 +764,7 @@ ResourceDef<AssetsClass>## AssetsData — type @beta```@internal appScope: AssetScope+@internal assetGraphSettled: () => Promise<void>@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]@internal dependentsOf: (ref: string) => AssetIdentity[]@internal entityScopes: EntityAssetScopes@@ -4242,6 +4243,16 @@ keyboard: boolean | undefinedmouse: boolean | undefined```+## LiveBindings — const @beta+```+ResourceDef<LiveBindingsData>+```++## LiveBindingsData — interface @beta+```+settled: () => Promise<void>+```+## LoadRuntimeSceneOptions — interface @experimental```app: Appdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex d62728af4..3f3487de5 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 84 beta · 1501 experimental · 3 deprecated+Symbols: 113 public · 86 beta · 1501 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -759,6 +759,7 @@ ResourceDef<AssetsClass>## AssetsData — type @beta```@internal appScope: AssetScope+@internal assetGraphSettled: () => Promise<void>@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]@internal dependentsOf: (ref: string) => AssetIdentity[]@internal entityScopes: EntityAssetScopes@@ -4229,6 +4230,16 @@ keyboard: boolean | undefinedmouse: boolean | undefined```+## LiveBindings — const @beta+```+ResourceDef<LiveBindingsData>+```++## LiveBindingsData — interface @beta+```+settled: () => Promise<void>+```+## LoadRuntimeSceneOptions — interface @experimental```app: Appdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex f12ce4f79..2348cb53e 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 82 beta · 1523 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1523 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -759,6 +759,7 @@ ResourceDef<AssetsClass>## AssetsData — type @beta```@internal appScope: AssetScope+@internal assetGraphSettled: () => Promise<void>@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]@internal dependentsOf: (ref: string) => AssetIdentity[]@internal entityScopes: EntityAssetScopes@@ -4229,6 +4230,16 @@ keyboard: boolean | undefinedmouse: boolean | undefined```+## LiveBindings — const @beta+```+ResourceDef<LiveBindingsData>+```++## LiveBindingsData — interface @beta+```+settled: () => Promise<void>+```+## LoadRuntimeSceneOptions — interface @experimental```app: Appdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex bab938dfe..b3ac0938e 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 82 beta · 1513 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1513 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -759,6 +759,7 @@ ResourceDef<AssetsClass>## AssetsData — type @beta```@internal appScope: AssetScope+@internal assetGraphSettled: () => Promise<void>@internal dependenciesOf: (type: string, ref: string) => readonly DependencyReceipt[]@internal dependentsOf: (ref: string) => AssetIdentity[]@internal entityScopes: EntityAssetScopes@@ -4236,6 +4237,16 @@ keyboard: boolean | undefinedmouse: boolean | undefined```+## LiveBindings — const @beta+```+ResourceDef<LiveBindingsData>+```++## LiveBindingsData — interface @beta+```+settled: () => Promise<void>+```+## LoadRuntimeSceneOptions — interface @experimental```app: Appdiff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 4e2d6cb9e..0dcb39909 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -381,6 +381,8 @@ export class Assets {/** Eras already given back, so N callers abandoning one shared load hand it* over once between them rather than unloading it N times. */private retired_ = new WeakSet<PreparedLoad<unknown>>();+ /** Propagations in flight — what {@link assetGraphSettled} waits on. */+ private settling_ = new Set<Promise<void>>();private loadContext_: LoadContext | null = null;private assetRefResolver_: AssetRefResolver | null = null;private assetRegistry_: AssetRegistry | null = null;@@ -949,7 +951,11 @@ export class Assets {// A changed asset is content-addressed, so its next load finds the update// on its own. An era already BUILT from one cannot: it holds what it read// at the revision it was prepared in, and only the walk ends it.- for (const c of changed) void this.rebuild_(this.rebuildPlan_(c.key));+ for (const c of changed) this.track_(this.rebuildAssetGraph_(this.rebuildPlan_(c.key)));+ // The update is applied when the asset graph agrees with the manifest —+ // not when the manifest was swapped. Bindings converge on a frame, which+ // an app that is not ticking would never reach from here.+ await this.assetGraphSettled();this.persistActiveManifest_(pending.manifestJson);this.pendingUpdate_ = null;return { ok: true, updated: changed.length, failed: [] };@@ -1653,10 +1659,29 @@ export class Assets {invalidate(ref: string): boolean {const plan = this.rebuildPlan_(ref);const { hit, rebuilt } = this.invalidateOne_(ref);- if (plan.length > 0) void rebuilt.then(() => this.rebuild_(plan));+ if (plan.length > 0) this.track_(rebuilt.then(() => this.rebuildAssetGraph_(plan)));return hit;}+ /**+ * Resolves when every propagation started so far has landed.+ *+ * The ASSET graph only. What reads it — a component bound to a handle — is+ * the second barrier, and it moves on a frame rather than here: see the+ * live-binding coordinator's `settled`.+ *+ * @internal+ */+ async assetGraphSettled(): Promise<void> {+ // A rebuild can start another (a group awaits the one before it), so+ // draining once is not the same as being settled.+ while (this.settling_.size > 0) {+ const inFlight = [...this.settling_];+ await Promise.all(inFlight);+ for (const work of inFlight) this.settling_.delete(work);+ }+ }+/** What a change to `ref` reaches, after `ref` itself. */private rebuildPlan_(ref: string): string[][] {const root = this.resolveLoadPath_(ref);@@ -1664,8 +1689,19 @@ export class Assets {return plan.map((group) => group.filter((p) => p !== root)).filter((g) => g.length > 0);}+ /** Count one propagation as in flight until it lands. It answers to nobody+ * in the ordinary case, so a failure is reported here rather than thrown at+ * whoever happens to be waiting. */+ private track_(work: Promise<void>): void {+ const settled = work.catch((e: unknown) => {+ log.warn('asset', 'propagating a change failed; what it reached keeps what it has', e);+ });+ this.settling_.add(settled);+ void settled.finally(() => this.settling_.delete(settled));+ }+/** Each group only once everything it was built from has landed. */- private async rebuild_(plan: string[][]): Promise<void> {+ private async rebuildAssetGraph_(plan: string[][]): Promise<void> {for (const group of plan) {await Promise.all(group.map((path) => this.invalidateOne_(path).rebuilt));}diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 8b43861bf..35dcb4792 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -94,6 +94,10 @@ export {type ParsedTextureImportSettings,} from './asset';+/** When the live bindings that READ the asset graph have caught up with it —+ * the second barrier of an update, the first being `Assets.applyUpdate`. */+export { LiveBindings, type LiveBindingsData } from './hotUpdateRebind';+// =============================================================================// Resource budget (VRAM)// =============================================================================diff --git a/sdk/src/hotUpdateRebind.ts b/sdk/src/hotUpdateRebind.tsindex 0a2f1f119..db4477611 100644--- a/sdk/src/hotUpdateRebind.ts+++ b/sdk/src/hotUpdateRebind.ts@@ -27,6 +27,7 @@* per install, not module-global — so realms don't share queues.*/import type { App } from './app/app';+import { defineResource } from './ecs/resource';import { Schedule, defineSystem, GetWorld } from './ecs/system';import { assetScopeForEntity } from './scene/sceneManager';import type { Entity } from './types';@@ -44,13 +45,39 @@ function acquire(assets: Assets, type: AssetFieldType, ref: string): Promise<Ass: assets.acquireTyped(type, ref);}-export function installHotUpdateRebind(app: App, assets: Assets): void {+/**+ * The second barrier of an update. `Assets.applyUpdate` resolves when the ASSET+ * graph has caught up; the bindings that read it move on a frame, so a paused+ * app converges when it resumes and this is how to wait for that.+ *+ * @beta+ */+export interface LiveBindingsData {+ /** Resolves once every ended era seen so far has been migrated onto its+ * replacement, or given up on. Needs the app to be ticking. */+ settled(): Promise<void>;+}++/** The per-App live-binding coordinator, for a game or host that has to know+ * when the world has caught up with an update.+ *+ * @beta+ */+export const LiveBindings = defineResource<LiveBindingsData>(null!, 'LiveBindings');++export function installHotUpdateRebind(app: App, assets: Assets): LiveBindingsData {// 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;}> = [];+ // Reloads started but not yet placed. Without them a caller can ask between+ // the queues and be told the world has caught up while an acquisition is in+ // the air.+ let reloading = 0;+ const waiting: Array<() => void> = [];+ const converged = (): boolean => pending.length === 0 && ready.length === 0 && reloading === 0;assets.onInvalidate((event) => {// The type vocabulary is one: what a loader answers to is what a field@@ -75,12 +102,13 @@ export function installHotUpdateRebind(app: App, assets: Assets): void {while (pending.length > 0) {const { ref, type, oldValue } = pending.shift()!;for (const scope of ownerScopesOf(world, type, oldValue, ownerScopeOf)) {+ reloading++;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);},- );+ ).finally(() => { reloading--; });}}while (ready.length > 0) {@@ -90,6 +118,7 @@ export function installHotUpdateRebind(app: App, assets: Assets): void {{ lease, boundValue: boundValueOf }, ownerScopeOf,);}+ if (converged()) for (const wake of waiting.splice(0)) wake();},{name: 'HotUpdateRebindSystem',@@ -99,4 +128,12 @@ export function installHotUpdateRebind(app: App, assets: Assets): void {touches: () => ({ writes: componentsBindingAssetTypes(assets.handleBoundTypes()) }),},));++ const coordinator: LiveBindingsData = {+ settled: () => (converged()+ ? Promise.resolve()+ : new Promise<void>((resolve) => { waiting.push(resolve); })),+ };+ app.insertResource(LiveBindings, coordinator);+ return coordinator;}diff --git a/sdk/tests/hot-update-rebind.test.ts b/sdk/tests/hot-update-rebind.test.tsindex 4744ea20c..04c62c667 100644--- a/sdk/tests/hot-update-rebind.test.ts+++ b/sdk/tests/hot-update-rebind.test.ts@@ -440,6 +440,33 @@ describe('a live binding follows the asset, whatever kind it is', () => {.toBe(fresh.value.handle);});+ it('converging is not done while a reload is still in the air', async () => {+ // The barrier a host asks about after `applyUpdate`: the asset graph has+ // caught up, and this says whether the world reading it has. Answering+ // between the queues would say yes with an acquisition in flight.+ const app = App.new();+ connectFakeCpp(app.world);+ const assets = buildAssets({ 'hero.esmaterial': MATERIAL });+ const bindings = 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');+ let converged = false;+ void bindings.settled().then(() => { converged = true; });++ await app.tick(1 / 60);+ await Promise.resolve();+ expect(converged, 'said the world had caught up with a reload in flight').toBe(false);++ await settle(app);+ expect(converged).toBe(true);+ expect((app.world.get(entity, MeshRenderer) as { material: number }).material)+ .not.toBe(before.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.diff --git a/sdk/tests/hot-update-runtime.test.ts b/sdk/tests/hot-update-runtime.test.tsindex 78e6af265..c00b6b5f3 100644--- a/sdk/tests/hot-update-runtime.test.ts+++ b/sdk/tests/hot-update-runtime.test.ts@@ -132,8 +132,10 @@ describe('a hot update reaches what was built from what it changed', () => {await assets.checkForUpdate({ manifestUrl: 'asset-manifest.json', remoteRoot: 'https://cdn/v2' });await assets.applyUpdate();- for (let i = 0; i < 4; i++) await new Promise((resolve) => setTimeout(resolve, 0));+ // No flushing: applyUpdate resolving MEANS the asset graph agrees with+ // the manifest. What reads the graph converges on a frame, which is the+ // other barrier and not this one.expect(builtFrom[1], 'the widget kept the revision it was built in').toBe(`https://cdn/v2/assets/${REMOTE_HASH}.png`);});