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(runtime): a packaged scene gives back the receipts its preload made

esengine404a14dd798f
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 27eeeac5f..46ea3312d 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -739,6 +739,7 @@ refCount: number
## AssetScope — class @experimental
```
@internal leases: () => readonly AssetLease[]
+absorb: (other: AssetScope) => void
add: <T>(lease: AssetLease<T>) => AssetLease<T>
forget: (lease: AssetLease) => boolean
releaseAll: () => void
@@ -6834,6 +6835,7 @@ name: string
registerDrawCallback: (id: string, fn: DrawCallback) => void
setPersistent: (entity: Entity, persistent: boolean) => void
spawn: () => Entity
+trackAssetScope: (scope: AssetScope) => void
trackAssets: (byType: ReadonlyMap<string, ReadonlySet<string>>) => void
unbindPostProcess: (camera: Entity) => void
```
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 8afd9c246..d96d185e7 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -739,6 +739,7 @@ refCount: number
## AssetScope — class @experimental
```
@internal leases: () => readonly AssetLease[]
+absorb: (other: AssetScope) => void
add: <T>(lease: AssetLease<T>) => AssetLease<T>
forget: (lease: AssetLease) => boolean
releaseAll: () => void
@@ -7027,6 +7028,7 @@ name: string
registerDrawCallback: (id: string, fn: DrawCallback) => void
setPersistent: (entity: Entity, persistent: boolean) => void
spawn: () => Entity
+trackAssetScope: (scope: AssetScope) => void
trackAssets: (byType: ReadonlyMap<string, ReadonlySet<string>>) => void
unbindPostProcess: (camera: Entity) => void
```
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 45a84a772..1a35af215 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -734,6 +734,7 @@ refCount: number
## AssetScope — class @experimental
```
@internal leases: () => readonly AssetLease[]
+absorb: (other: AssetScope) => void
add: <T>(lease: AssetLease<T>) => AssetLease<T>
forget: (lease: AssetLease) => boolean
releaseAll: () => void
@@ -6829,6 +6830,7 @@ name: string
registerDrawCallback: (id: string, fn: DrawCallback) => void
setPersistent: (entity: Entity, persistent: boolean) => void
spawn: () => Entity
+trackAssetScope: (scope: AssetScope) => void
trackAssets: (byType: ReadonlyMap<string, ReadonlySet<string>>) => void
unbindPostProcess: (camera: Entity) => void
```
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 564695e1e..b3509597c 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -734,6 +734,7 @@ refCount: number
## AssetScope — class @experimental
```
@internal leases: () => readonly AssetLease[]
+absorb: (other: AssetScope) => void
add: <T>(lease: AssetLease<T>) => AssetLease<T>
forget: (lease: AssetLease) => boolean
releaseAll: () => void
@@ -7075,6 +7076,7 @@ name: string
registerDrawCallback: (id: string, fn: DrawCallback) => void
setPersistent: (entity: Entity, persistent: boolean) => void
spawn: () => Entity
+trackAssetScope: (scope: AssetScope) => void
trackAssets: (byType: ReadonlyMap<string, ReadonlySet<string>>) => void
unbindPostProcess: (camera: Entity) => void
```
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 29f12921d..843a3d9ac 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -734,6 +734,7 @@ refCount: number
## AssetScope — class @experimental
```
@internal leases: () => readonly AssetLease[]
+absorb: (other: AssetScope) => void
add: <T>(lease: AssetLease<T>) => AssetLease<T>
forget: (lease: AssetLease) => boolean
releaseAll: () => void
@@ -6836,6 +6837,7 @@ name: string
registerDrawCallback: (id: string, fn: DrawCallback) => void
setPersistent: (entity: Entity, persistent: boolean) => void
spawn: () => Entity
+trackAssetScope: (scope: AssetScope) => void
trackAssets: (byType: ReadonlyMap<string, ReadonlySet<string>>) => void
unbindPostProcess: (camera: Entity) => void
```
diff --git a/sdk/src/asset/AssetLease.ts b/sdk/src/asset/AssetLease.ts
index db6527892..138a2f2b7 100644
--- a/sdk/src/asset/AssetLease.ts
+++ b/sdk/src/asset/AssetLease.ts
@@ -43,6 +43,19 @@ export class AssetScope {
this.leases_ = [];
}
+ /**
+ * Take over every receipt `other` holds; it owes nothing afterwards.
+ *
+ * The transfer an owner needs when the acquiring code is not the owning
+ * code: a loader acquires into a scope of its own and hands the whole thing
+ * to whoever will outlive it.
+ */
+ absorb(other: AssetScope): void {
+ if (other === this) return;
+ for (const lease of other.leases_) this.leases_.push(lease);
+ other.leases_ = [];
+ }
+
/** Stop tracking one lease without releasing it — for an ownership transfer. */
forget(lease: AssetLease): boolean {
const i = this.leases_.indexOf(lease);
diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.ts
index 2f148aa26..6d54417d3 100644
--- a/sdk/src/runtime/runtimeLoader.ts
+++ b/sdk/src/runtime/runtimeLoader.ts
@@ -483,10 +483,10 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis
if (ctx) ctx.adopt(entity);
else app.world.insert(entity, SceneOwner, { scene: sceneName, persistent: false });
}
- // And the assets, for the same reason: a packaged scene carries no
- // `data`, so the manager's preload never ran and these references are
- // ones only this function knows about.
- ctx?.trackAssets(discovered.byType);
+ // The RECEIPTS, not the paths: after a hot update a path-addressed
+ // release gives back the oldest era, which belongs to whoever loaded
+ // before the update.
+ ctx?.trackAssetScope(assetResult.scope);
}
}
diff --git a/sdk/src/scene/sceneManager.ts b/sdk/src/scene/sceneManager.ts
index 4738b286a..5c163c076 100644
--- a/sdk/src/scene/sceneManager.ts
+++ b/sdk/src/scene/sceneManager.ts
@@ -70,6 +70,14 @@ export interface SceneContext {
* preloads its own, and a reference nothing records is one nothing releases.
*/
trackAssets(byType: ReadonlyMap<string, ReadonlySet<string>>): void;
+ /**
+ * Take over the receipts a loader acquired for this scene.
+ *
+ * What {@link trackAssets} is for a caller that only ever had paths. A
+ * caller holding receipts hands them over instead: unload then gives back
+ * the acquisitions this load made, not the oldest ones sharing their path.
+ */
+ trackAssetScope(scope: AssetScope): void;
despawn(entity: Entity): void;
registerDrawCallback(id: string, fn: DrawCallback): void;
bindPostProcess(camera: Entity, stack: PostProcessStack): void;
@@ -160,6 +168,10 @@ class SceneContextImpl implements SceneContext {
});
}
+ trackAssetScope(scope: AssetScope): void {
+ this.instance_.assetScope.absorb(scope);
+ }
+
trackAssets(byType: ReadonlyMap<string, ReadonlySet<string>>): void {
for (const [type, paths] of byType) {
// Materials are handle-keyed and skeletons belong to the
diff --git a/sdk/tests/asset-generation-ownership.test.ts b/sdk/tests/asset-generation-ownership.test.ts
index 658adba90..c6351f911 100644
--- a/sdk/tests/asset-generation-ownership.test.ts
+++ b/sdk/tests/asset-generation-ownership.test.ts
@@ -165,6 +165,38 @@ describe('asset ownership is generation-exact', () => {
expect(assets.sizes().refRows).toBe(base);
});
+ it('a scope absorbs another\'s receipts, and gives back what it took', async () => {
+ // The packaged-game shape: the loader acquires into a scope of its own
+ // and hands the whole thing to the scene that will outlive it. Releasing
+ // by PATH instead is what took the wrong era below.
+ const unloaded: string[] = [];
+ const assets = makeAssets(unloaded);
+ const base = assets.sizes().refRows;
+
+ const sceneA = new AssetScope();
+ sceneA.add(await assets.acquireTyped('font', 'shared.ttf')); // gen1
+
+ assets.invalidate('shared.ttf'); // a hot update lands
+
+ const loaderScope = new AssetScope();
+ loaderScope.add(await assets.acquireTyped('font', 'shared.ttf')); // gen2
+ const sceneB = new AssetScope();
+ sceneB.absorb(loaderScope);
+ expect(loaderScope.size).toBe(0); // the loader owes nothing afterwards
+ expect(sceneB.size).toBe(1);
+
+ sceneB.releaseAll();
+ expect(unloaded).toEqual(['gen2']); // B's own era
+ expect(assets.sizes().refRows).toBe(base + 1); // A still holds gen1
+
+ // What the path door does with the same call — the era it takes is the
+ // OLDEST, which is the scene that loaded before the update.
+ assets.releaseTyped('font', 'shared.ttf');
+ expect(unloaded).toEqual(['gen2', 'gen1']);
+ sceneA.releaseAll(); // already gone: no double free
+ expect(unloaded).toEqual(['gen2', 'gen1']);
+ });
+
it('a scene survives many hot updates and still balances at unload', async () => {
// The dogfood shape: load, hot-update the same asset repeatedly, unload.
// Every era that was acquired is given back exactly once.
diff --git a/sdk/tests/scene-asset-release.test.ts b/sdk/tests/scene-asset-release.test.ts
index f4ea06de2..06db6fed8 100644
--- a/sdk/tests/scene-asset-release.test.ts
+++ b/sdk/tests/scene-asset-release.test.ts
@@ -50,6 +50,7 @@ vi.mock('../src/asset/discoverAssets', () => ({
import { SceneManagerState } from '../src/scene/sceneManager';
import { Assets } from '../src/asset';
+import { AssetScope } from '../src/asset/AssetLease';
import { Material } from '../src/render/material';
/**
@@ -191,6 +192,28 @@ describe('Scene unload releases all tracked asset categories', () => {
expect(releasedTyped).toContainEqual(['tileset', 'maps/tiles.estileset']);
});
+ it('takes over the receipts a packaged scene\'s loader acquired', async () => {
+ // The runtime loader preloads into a scope of its own and hands it here.
+ // Reporting paths instead left a release guessing which era it meant,
+ // and left what the paths omitted (materials) with nobody to give back.
+ const released: string[] = [];
+ const app = createMockApp({
+ releaseTexture: vi.fn(), releaseTyped: vi.fn(),
+ });
+ const manager = new SceneManagerState(app as never);
+ const loaderScope = new AssetScope();
+ for (const key of ['texture:hero.png', 'material:hero.esmat']) {
+ loaderScope.add({ key, generation: 1, value: null, release: () => released.push(key) });
+ }
+
+ manager.register({ name: 'packaged', setup: (ctx) => { ctx.trackAssetScope(loaderScope); } });
+ await manager.load('packaged');
+ expect(loaderScope.size).toBe(0); // ownership moved, it was not copied
+
+ await manager.unload('packaged');
+ expect(released).toEqual(['material:hero.esmat', 'texture:hero.png']);
+ });
+
it('releases every type the scene acquired, whatever its type', async () => {
const releasedTextures: string[] = [];
const releasedTyped: Array<[string, string]> = [];
diff --git a/tools/check-live-asset-rebind.mjs b/tools/check-live-asset-rebind.mjs
index 7cbb66f26..b687845e1 100644
--- a/tools/check-live-asset-rebind.mjs
+++ b/tools/check-live-asset-rebind.mjs
@@ -12,10 +12,12 @@
*
* A list like that cannot be kept correct, because the thing it must agree with
* is authored somewhere else (a C++ ES_PROPERTY, a project's defineComponent).
- * So the rule guarded here is that there is no list:
+ * So the rules guarded here are that there is no list, and that a caller who
+ * holds receipts does not fall back to naming paths:
*
* 1. No file on the rebind path names an asset-bearing component type.
* 2. The walk goes through the registry and reads `assetFields`.
+ * 3. The runtime scene loader hands the scene its receipts, not its paths.
*
* Run: node tools/check-live-asset-rebind.mjs (exit 1 on violation)
*/
@@ -117,10 +119,24 @@ for (const fn of ['findLiveAssetBindings', 'componentsBindingAssetType']) {
}
}
+// A caller holding receipts must not hand over paths: a path-addressed release
+// after a hot update gives back the oldest era, and what the paths omit is
+// never given back at all.
+const LOADER = 'sdk/src/runtime/runtimeLoader.ts';
+const loader = stripComments(readFileSync(path.join(ROOT, LOADER), 'utf8'));
+if (!/\bpreloadSceneAssets\(/.test(loader)) {
+ findings.push(`${LOADER} no longer preloads scene assets — this guard is reading the wrong file.`);
+} else {
+ const call = /\btrackAssets\(/.exec(loader);
+ if (call) {
+ findings.push(`${LOADER}:${loader.slice(0, call.index).split('\n').length} hands the scene PATHS while holding the preload's receipts — use trackAssetScope.`);
+ }
+}
+
if (findings.length === 0) {
- console.log(`check-live-asset-rebind: the rebind path names none of the ${components.size} asset-bearing components, and reads the declaration.`);
+ console.log(`check-live-asset-rebind: the rebind path names none of the ${components.size} asset-bearing components, reads the declaration, and the scene loader hands over receipts.`);
process.exit(0);
}
for (const f of findings) console.error(f);
-console.error('\nRebinding is per DECLARED asset field. Widen the walk instead of adding a case.');
+console.error('\nLive assets are addressed by what DECLARES them: the asset field for a binding, the receipt for an acquisition.');
process.exit(1);