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(assets): a material instance acquires its parent instead of loading it

esengine78e5eafca127
diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.ts
index 7dc208024..2054d4478 100644
--- a/sdk/src/asset/AssetLoader.ts
+++ b/sdk/src/asset/AssetLoader.ts
@@ -25,8 +25,6 @@ export interface SpineLoadResult {
export interface MaterialResult {
handle: number;
shaderHandle: number;
- /** Parent material handle for an `instanceOf` material, released on unload. */
- parentHandle?: number;
}
export interface FontResult {
@@ -104,6 +102,12 @@ export interface LoadContext {
* this loader was handed.
*/
acquireTexture(path: string, flipY?: boolean): Promise<AssetLease<TextureResult>>;
+ /**
+ * The same for an asset of ANY type — a material instance acquiring the
+ * parent it diffs against. The general door; {@link acquireTexture} is the
+ * one specialization, for the flip variants a texture has.
+ */
+ acquireAsset<T>(type: string, ref: string): Promise<AssetLease<T>>;
loadText(path: string): Promise<string>;
loadBinary(path: string): Promise<ArrayBuffer>;
/**
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index a7994b876..bba569280 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -2109,6 +2109,7 @@ export class Assets {
...base,
acquireTexture: async (path, flipY) =>
recorder.own(path, await base.acquireTexture(path, flipY), 'texture'),
+ acquireAsset: async (type, ref) => recorder.own(ref, await base.acquireAsset(type, ref), type),
createOwnedTexture: async (width, height, pixels, flipY) => {
const lease = await base.createOwnedTexture!(width, height, pixels, flipY);
return recorder.own(`composed:${lease.value.handle}`, lease);
@@ -2137,6 +2138,9 @@ export class Assets {
const { result, lease } = await self.acquireTextureVariant_(path, flipY !== false);
return self.textureLease_(lease, result);
},
+ async acquireAsset<T>(type: string, ref: string): Promise<AssetLease<T>> {
+ return self.acquireTyped<T>(type, ref);
+ },
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.ts
index 8a1e469bf..325be397c 100644
--- a/sdk/src/asset/loaders/MaterialAssetLoader.ts
+++ b/sdk/src/asset/loaders/MaterialAssetLoader.ts
@@ -28,10 +28,10 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {
// and uniforms come from the parent material, so no shader is loaded here.
if (data.instanceOf) {
const parentPath = resolveDocumentRef(path, data.instanceOf);
- const parent = await this.load(parentPath, ctx);
- const handle = Material.createFromAsset(data, 0, parent.handle);
+ const parent = await ctx.acquireAsset<MaterialResult>('material', parentPath);
+ const handle = Material.createFromAsset(data, 0, parent.value.handle);
await this.applyTextureProps(handle, data, path, ctx);
- return { handle, shaderHandle: parent.shaderHandle, parentHandle: parent.handle };
+ return { handle, shaderHandle: parent.value.shaderHandle };
}
// Enabled static switches select the shader permutation (compiled once per switch-set).
@@ -67,7 +67,6 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {
}
unload(asset: MaterialResult): void {
- if (asset.parentHandle !== undefined) Material.release(asset.parentHandle);
Material.release(asset.handle);
}
diff --git a/sdk/tests/asset-dependencies.test.ts b/sdk/tests/asset-dependencies.test.ts
index d084411b6..5f0442d05 100644
--- a/sdk/tests/asset-dependencies.test.ts
+++ b/sdk/tests/asset-dependencies.test.ts
@@ -62,15 +62,22 @@ const platformFactory = vi.hoisted(() => () => ({
vi.mock('../src/platform', platformFactory);
vi.mock('../src/platform/base', platformFactory);
-vi.mock('../src/render/material', () => ({
- Material: {
- createFromAsset: vi.fn(() => 11),
- setUniform: vi.fn(),
- tex: vi.fn((handle: number) => ({ kind: 'tex', handle })),
- compileShader: vi.fn(() => 7),
- release: vi.fn(),
- },
-}));
+const materialFake = vi.hoisted(() => {
+ const live = new Set<number>();
+ let next = 100;
+ return {
+ live,
+ reset: () => { live.clear(); next = 100; },
+ Material: {
+ createFromAsset: vi.fn((): number => { const h = next++; live.add(h); return h; }),
+ setUniform: vi.fn(),
+ tex: vi.fn((handle: number) => ({ kind: 'tex', handle })),
+ compileShader: vi.fn(() => 7),
+ release: vi.fn((h: number) => { live.delete(h); }),
+ },
+ };
+});
+vi.mock('../src/render/material', () => ({ Material: materialFake.Material }));
/** A `.tmj` whose one tileset lives in an external `.tsj`. */
const MAP_WITH_EXTERNAL = JSON.stringify({
@@ -95,6 +102,10 @@ const MAP_WITH_COLLECTION = JSON.stringify({
const MATERIAL = JSON.stringify({
type: 'material', shader: 'builtin:sprite-unlit', properties: { mainTex: 'wall.png' },
});
+/** An instance of it: no shader of its own, only diffs against its parent. */
+const CHILD_MATERIAL = JSON.stringify({
+ type: 'material', shader: '', instanceOf: 'parent.esmaterial', properties: {},
+});
function realm(docs: Record<string, string>): Assets {
const assets = Assets.create({
@@ -299,3 +310,54 @@ describe('a handle-bound loader owns nothing of its own', () => {
expect(pool.liveTextures()).toBe(0);
});
});
+
+describe('a material instance acquires its parent', () => {
+ beforeEach(() => { pool = createPoolFake(); materialFake.reset(); });
+
+ function instanced(): Assets {
+ return realm({ 'parent.esmaterial': MATERIAL, 'child.esmaterial': CHILD_MATERIAL });
+ }
+
+ it('the parent is an owned dependency of the instance, named as a material', async () => {
+ const assets = instanced();
+ await assets.acquireTyped('material', 'materials/child.esmaterial');
+
+ expect(assets.dependenciesOf('material', 'materials/child.esmaterial'))
+ .toContainEqual({ kind: 'owned', type: 'material', path: 'materials/parent.esmaterial' });
+ });
+
+ it('the parent is an asset of this realm, with an era of its own', async () => {
+ // Loaded by recursion it was invisible: no cache entry, no receipt, and
+ // the graph stopped at the instance.
+ const assets = instanced();
+ await assets.acquireTyped('material', 'materials/child.esmaterial');
+
+ expect(assets.dependenciesOf('material', 'materials/parent.esmaterial'))
+ .toContainEqual({ kind: 'owned', type: 'texture', path: 'materials/wall.png' });
+ });
+
+ it('two instances of one parent share it', async () => {
+ const assets = realm({
+ 'parent.esmaterial': MATERIAL,
+ 'a.esmaterial': CHILD_MATERIAL,
+ 'b.esmaterial': CHILD_MATERIAL,
+ });
+ await assets.acquireTyped('material', 'materials/a.esmaterial');
+ await assets.acquireTyped('material', 'materials/b.esmaterial');
+
+ expect(materialFake.live.size, 'the parent was built once per instance').toBe(3);
+ });
+
+ it('the last instance letting go gives the whole chain back', async () => {
+ const assets = instanced();
+ const first = await assets.acquireTyped('material', 'materials/child.esmaterial');
+ const second = await assets.acquireTyped('material', 'materials/child.esmaterial');
+
+ first.release();
+ expect(materialFake.live.size, 'released while a holder was still using it').toBe(2);
+
+ second.release();
+ expect(materialFake.live.size).toBe(0);
+ expect(pool.liveTextures(), 'the texture the PARENT bound').toBe(0);
+ });
+});