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
fix(assets): release runtime entity replacements on despawn
yhh2f784b385e0a
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 37d77145e..8ff2bf34b 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -2449,11 +2449,10 @@ export class Assets {}/**- * What this Assets acquired for an owner the engine cannot name — a live- * binding on an entity no scene owns.+ * What is explicitly owned by the whole asset realm.*- * Its life is this instance's, which is how long such an entity can live.- * Never a place to park an acquisition an owner exists for.+ * Its life is this instance's. Entity bindings use scene or entity scopes,+ * including runtime entities with no scene, so their resources can end sooner.** @internal*/@@ -2462,8 +2461,8 @@ export class Assets {}/**- * What entities own for themselves — a persistent entity that outlived the- * scene it came from. Ends at the entity's despawn.+ * What entities own for themselves — runtime entities with no scene and+ * persistent entities that outlived theirs. Ends at the entity's despawn.** @internal*/diff --git a/sdk/src/asset/entityAssetScopes.ts b/sdk/src/asset/entityAssetScopes.tsindex 8d0ac6698..0ace6408e 100644--- a/sdk/src/asset/entityAssetScopes.ts+++ b/sdk/src/asset/entityAssetScopes.ts@@ -2,9 +2,10 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file entityAssetScopes.ts- * @brief What one entity owns, for an entity that outlives the scene it came from.+ * @brief What an entity owns outside a scene, ending at its despawn.*- * @details A persistent entity leaves its scene and keeps rendering. Somebody+ * @details A runtime entity can have no scene; a persistent entity leaves its+ * scene and keeps rendering. Somebody* has to owe a release for what it is still bound to, and the two* answers that existed were both wrong: the scene's scope is about to* be given back, and the app's never ends while an entity's does.diff --git a/sdk/src/asset/liveAssetBindings.ts b/sdk/src/asset/liveAssetBindings.tsindex 6a77c5ddd..b64dc9895 100644--- a/sdk/src/asset/liveAssetBindings.ts+++ b/sdk/src/asset/liveAssetBindings.ts@@ -54,6 +54,7 @@ export function findLiveAssetBindings(const fields = component.assetFields.filter((f) => f.type === type);if (fields.length === 0) continue;for (const entity of world.getEntitiesWithComponents([component])) {+ if (world.isDestructionPending(entity)) continue;const data = world.get(entity, component) as Record<string, unknown>;for (const { field } of fields) {if (data[field] === value) found.push({ entity, component, field });diff --git a/sdk/src/scene/sceneManager.ts b/sdk/src/scene/sceneManager.tsindex 61a66a13c..4bacd3bc4 100644--- a/sdk/src/scene/sceneManager.ts+++ b/sdk/src/scene/sceneManager.ts@@ -1026,11 +1026,12 @@ export const SceneManager = defineResource<SceneManagerState>();/**- * Who owes a release for what this entity's asset fields hold: entity, then- * scene, then app. The one answer, for every caller.+ * Who owes a release for what this entity's asset fields hold: its existing+ * entity scope, its scene, or a new scope ending at its own despawn.** A promoted entity owns what it holds and carries no scene tag, so a caller* working the rule out for itself hands its replacement to the app instead.+ * Runtime entities without a scene also end before the app does.*/export function assetScopeForEntity(app: App, assets: AssetsData, entity: Entity): AssetScope {const own = assets.entityScopes.scopeFor(entity, app.world);@@ -1039,7 +1040,7 @@ export function assetScopeForEntity(app: App, assets: AssetsData, entity: Entityconst scene = owner?.scene && app.hasResource(SceneManager)? app.getResource(SceneManager).assetScopeFor(owner.scene): null;- return scene ?? assets.appScope;+ return scene ?? assets.entityScopes.ensure(app.world, entity);}// =============================================================================diff --git a/sdk/tests/hot-update-rebind.test.ts b/sdk/tests/hot-update-rebind.test.tsindex eb39d51f2..e0b01a5be 100644--- a/sdk/tests/hot-update-rebind.test.ts+++ b/sdk/tests/hot-update-rebind.test.ts@@ -15,7 +15,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { App } from '../src/app/app';import { World } from '../src/ecs/world';-import { defineComponent, getComponentRegistry, type AnyComponentDef } from '../src/ecs/component';+import { defineComponent, getComponent, getComponentRegistry, type AnyComponentDef } from '../src/ecs/component';import { COMPONENT_META } from '../src/ecs/component.generated';import { Assets } from '../src/asset/Assets';import type { Backend } from '../src/asset/Backend';@@ -207,6 +207,20 @@ describe('the hot-update rebinder reaches every declared texture field', () => {world.insert(e, Widget, { icon: 7 });expect(findLiveAssetBindings(world, 'texture', 7)).toHaveLength(1);});++ it('does not hand a dying entity a new owner during despawn callbacks', () => {+ const world = new World(); connectFakeCpp(world);+ const entity = world.spawn(); world.insert(entity, Sprite, { texture: 7 });+ let pending: boolean | undefined;+ let bindingsDuringDespawn = -1;+ world.onDespawn(() => {+ pending = world.isDestructionPending(entity);+ bindingsDuringDespawn = findLiveAssetBindings(world, 'texture', 7).length;+ });+ world.despawn(entity);+ expect(pending).toBe(true);+ expect(bindingsDuringDespawn).toBe(0);+ });});describe('a replacement is a transaction per owning scope', () => {@@ -335,9 +349,7 @@ describe('a replacement is a transaction per owning scope', () => {expect(assets.sizes().refRows).toBe(base);});- it('an entity no scene owns is the app\'s, not nobody\'s', async () => {- // The rebinder must not keep what it acquires, and an acquisition with- // no owner is one nobody can ever give back — the leak this had.+ it('a runtime sprite releases its replacement when the entity despawns', async () => {const { app, assets } = sceneApp();const base = assets.sizes().refRows;@@ -351,9 +363,58 @@ describe('a replacement is a transaction per owning scope', () => {expect(boundValues(app, Sprite, 'texture')).toEqual([after]);lease.release(); // the game lets go of its own era- expect(assets.sizes().refRows).toBe(base + 1); // the app owns the replacement- assets.releaseAll();- expect(assets.sizes().refRows).toBe(base); // and gives it back at teardown+ expect(assets.sizes().refRows).toBe(base + 1);+ expect(assets.appScope.size).toBe(0);+ app.world.despawn(entity);+ expect(assets.entityScopes.size).toBe(0);+ expect(assets.sizes().refRows).toBe(base);+ });++ it('runtime mesh materials end with their own entities, including instance sets', async () => {+ const app = App.new(); connectFakeCpp(app.world);+ const assets = buildAssets({ 'leaf.esmaterial': JSON.stringify({+ version: '1.0', type: 'material', shader: 'builtin:model',+ properties: { u_normalMap: 'leaf.png' },+ }) });+ installHotUpdateRebind(app, assets);+ const base = assets.sizes().refRows;+ for (let i = 0; i < 3; i++) {+ const initial = await assets.acquireTyped<{ handle: number }>('material', 'leaf.esmaterial');+ const entities = [app.world.spawn(), app.world.spawn()];+ for (const entity of entities) app.world.insert(entity, MeshRenderer, { material: initial.value.handle });+ app.world.insert(entities[0], getComponent('MeshInstances')!, {});+ assets.invalidate('leaf.esmaterial'); await settle(app, 8);+ const replacement = app.world.get(entities[0], MeshRenderer).material;+ expect(replacement).not.toBe(initial.value.handle);+ expect(app.world.get(entities[1], MeshRenderer).material).toBe(replacement);+ initial.release();+ expect(assets.appScope.size).toBe(0);+ expect(assets.entityScopes.size).toBe(2);+ app.world.despawn(entities[0]);+ expect(assets.entityScopes.size).toBe(1);+ expect(materialFake.Material.release).not.toHaveBeenCalledWith(replacement);+ app.world.despawn(entities[1]);+ expect(materialFake.Material.release).toHaveBeenCalledWith(replacement);+ expect(assets.entityScopes.size).toBe(0);+ expect(assets.sizes().refRows, `after generation ${i}`).toBe(base);+ }+ });++ it('returns a late replacement when its runtime entity despawned while loading', async () => {+ const { app, assets } = sceneApp();+ const initial = await assets.acquireTexture('hero.png');+ const entity = app.world.spawn();+ app.world.insert(entity, Sprite, { texture: initial.value.handle });+ const acquire = assets.acquireTexture.bind(assets);+ let finish!: (lease: Awaited<ReturnType<typeof acquire>>) => void;+ vi.spyOn(assets, 'acquireTexture').mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ assets.invalidate('hero.png'); await app.tick(1 / 60);+ expect(assets.entityScopes.size).toBe(1);+ app.world.despawn(entity); initial.release();+ finish(await acquire('hero.png')); await settle(app);+ expect(assets.entityScopes.size).toBe(0);+ expect(assets.appScope.size).toBe(0);+ expect(assets.sizes().refRows).toBe(0);});});