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(sdk): materials release their bound textures on unload
esengine47405dc788e3
diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.tsindex 857875b1c..dc0c637ec 100644--- a/sdk/src/asset/AssetLoader.ts+++ b/sdk/src/asset/AssetLoader.ts@@ -23,6 +23,11 @@ export interface SpineLoadResult {export interface MaterialResult {handle: number;shaderHandle: number;+ /** Texture refs this material bound; released on unload to balance the+ * loadTexture that bound them (they aren't in the scene's texture set). */+ texturePaths?: string[];+ /** Parent material handle for an `instanceOf` material, released on unload. */+ parentHandle?: number;}export interface FontResult {@@ -74,6 +79,9 @@ export interface LoadContext {catalog: Catalog;resourceManager: CppResourceManager;loadTexture(path: string, flipY?: boolean): Promise<TextureResult>;+ /** Release a texture obtained via {@link loadTexture} (balances the refcount).+ * Handles both flip variants, so the same ref that was loaded releases it. */+ releaseTexture(path: string): void;loadText(path: string): Promise<string>;loadBinary(path: string): Promise<ArrayBuffer>;/**@@ -115,7 +123,9 @@ export interface AssetLoader<T> {readonly type: string;readonly extensions: string[];load(path: string, ctx: LoadContext): Promise<T>;- unload(asset: T): void;+ /** Free the loaded asset. `ctx` gives loaders that pulled sub-assets during+ * load (e.g. a material's bound textures) a channel to release them. */+ unload(asset: T, ctx: LoadContext): void;/*** Sever any residency identity the loader's subsystem keeps for `path`* (hot reload: the source bytes changed, so a warm-cache entry must neverdiff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex b1beb502e..7ee0aa757 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -951,7 +951,7 @@ export class Assets {return;}const loader = this.loaders_.get(type);- loader?.unload(entry);+ loader?.unload(entry, this.getLoadContext_());cache.delete(path);this.genericRefCounts_.delete(key);}@@ -1220,6 +1220,9 @@ export class Assets {}return self.loadTexture(path);},+ releaseTexture(path: string): void {+ self.releaseTexture(path);+ },async loadText(path: string): Promise<string> {return self.backend.fetchText(self.backend.resolveUrl(path));},diff --git a/sdk/src/asset/loaders/MaterialAssetLoader.ts b/sdk/src/asset/loaders/MaterialAssetLoader.tsindex 99ba2fcb5..ab48118cd 100644--- a/sdk/src/asset/loaders/MaterialAssetLoader.ts+++ b/sdk/src/asset/loaders/MaterialAssetLoader.ts@@ -28,8 +28,13 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {const parentPath = resolveRelativePath(path, data.instanceOf);const parent = await this.load(parentPath, ctx);const handle = Material.createFromAsset(data, 0, parent.handle);- await this.applyTextureProps(handle, data, path, ctx);- return { handle, shaderHandle: parent.shaderHandle };+ const texturePaths = await this.applyTextureProps(handle, data, path, ctx);+ return {+ handle,+ shaderHandle: parent.shaderHandle,+ texturePaths: [...(parent.texturePaths ?? []), ...texturePaths],+ parentHandle: parent.handle,+ };}// Enabled static switches select the shader permutation (compiled once per switch-set).@@ -37,33 +42,41 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {const shaderPath = resolveRelativePath(path, data.shader);const shaderHandle = await this.loadShader(shaderPath, features, ctx);const handle = Material.createFromAsset(data, shaderHandle);- await this.applyTextureProps(handle, data, path, ctx);+ const texturePaths = await this.applyTextureProps(handle, data, path, ctx);- return { handle, shaderHandle };+ return { handle, shaderHandle, texturePaths };}// A texture param is a string property (an asset ref); scalar/vector params are- // numbers/objects (handled by createFromAsset). Load each texture and bind it to its param.+ // numbers/objects (handled by createFromAsset). Load each texture, bind it to its+ // param, and return the refs so unload can release them (they hold a texture ref).private async applyTextureProps(handle: number,data: MaterialAssetData,matPath: string,ctx: LoadContext,- ): Promise<void> {+ ): Promise<string[]> {+ const bound: string[] = [];for (const [name, value] of Object.entries(data.properties)) {if (typeof value !== 'string') continue;const texPath = resolveRelativePath(matPath, value);try {const tex = await ctx.loadTexture(texPath);Material.setUniform(handle, name, Material.tex(tex.handle));+ bound.push(texPath); // recorded only on success — matches the refcount taken} catch (e) {// Missing texture: leave the param unbound (it samples whatever is at the unit).log.warn('asset', `Material ${matPath}: failed to load texture '${texPath}' for param '${name}'`, e);}}+ return bound;}- unload(asset: MaterialResult): void {+ unload(asset: MaterialResult, ctx: LoadContext): void {+ if (asset.texturePaths) {+ for (const texPath of asset.texturePaths) ctx.releaseTexture(texPath);+ }+ if (asset.parentHandle !== undefined) Material.release(asset.parentHandle);Material.release(asset.handle);}diff --git a/sdk/tests/material-asset-loader.test.ts b/sdk/tests/material-asset-loader.test.tsindex 9e9201746..bde5a04a4 100644--- a/sdk/tests/material-asset-loader.test.ts+++ b/sdk/tests/material-asset-loader.test.ts@@ -62,3 +62,40 @@ describe('MaterialAssetLoader texture failure', () => {warnSpy.mockRestore();});});++describe('MaterialAssetLoader texture release on unload', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (Material.createFromAsset as ReturnType<typeof vi.fn>).mockReturnValue(11);+ (Material.compileShader as ReturnType<typeof vi.fn>).mockReturnValue(7);+ });++ function makeCtxWithTexture() {+ const materialJson = JSON.stringify({+ type: 'material', shader: 'fx.esshader', properties: { mainTex: TEX_REF },+ });+ const releaseTexture = vi.fn();+ const ctx = {+ catalog: { getBuildPath: (p: string) => p },+ loadText: vi.fn(async (p: string) => (p.endsWith('.esmaterial') ? materialJson : '// shader src')),+ loadTexture: vi.fn(async () => ({ handle: 42 })),+ releaseTexture,+ } as unknown as LoadContext;+ return { ctx, releaseTexture };+ }++ it('records bound texture refs and releases them on unload (no VRAM leak)', async () => {+ const loader = new MaterialAssetLoader();+ const { ctx, releaseTexture } = makeCtxWithTexture();++ const result = await loader.load(MAT_PATH, ctx);+ // The bound texture is recorded so unload can balance its loadTexture ref;+ // the scene's texture set never sees a material-internal texture.+ expect(result.texturePaths).toEqual(['assets/materials/missing.png']);+ expect(Material.setUniform).toHaveBeenCalled();++ loader.unload(result, ctx);+ expect(releaseTexture).toHaveBeenCalledWith('assets/materials/missing.png');+ expect(Material.release).toHaveBeenCalledWith(11);+ });+});