Fix multiple resources allocation for same instances during startup.

This commit is contained in:
Davide Tantillo 2025-12-04 12:10:29 +01:00
parent 1afafb9e16
commit 9167263c6f

View File

@ -32,15 +32,18 @@ import { C3TextureEditor, C3TextureRuntime } from "./C3Texture";
interface CacheEntry<T> { interface CacheEntry<T> {
data: T; data?: T;
promise: Promise<T>;
refCount: number; refCount: number;
} }
type ResourceCache<T> = Map<string, CacheEntry<T>>;
export class AssetLoader { export class AssetLoader {
private static CacheSkeleton = new Map<string, CacheEntry<SkeletonData>>(); private static CacheSkeleton: ResourceCache<SkeletonData> = new Map();
private static CacheAtlas = new Map<string, CacheEntry<TextureAtlas>>(); private static CacheAtlas: ResourceCache<TextureAtlas> = new Map();
private static CacheTexture = new Map<string, CacheEntry<C3TextureRuntime>>(); private static CacheTexture: ResourceCache<C3TextureRuntime> = new Map();
public async loadSkeletonEditor (sid: number, textureAtlas: TextureAtlas, scale = 1, instance: SDK.IWorldInstance) { public async loadSkeletonEditor (sid: number, textureAtlas: TextureAtlas, scale = 1, instance: SDK.IWorldInstance) {
const projectFile = instance.GetProject().GetProjectFileBySID(sid); const projectFile = instance.GetProject().GetProjectFileBySID(sid);
@ -96,13 +99,9 @@ export class AssetLoader {
} }
public async loadSkeletonRuntime (path: string, textureAtlas: TextureAtlas, scale = 1, instance: IRuntime) { public async loadSkeletonRuntime (path: string, textureAtlas: TextureAtlas, scale = 1, instance: IRuntime) {
const cacheKey = `${path}|scale${scale}`; const loadPromise = (async () => {
const fileInCache = this.getFromCache(AssetLoader.CacheSkeleton, cacheKey);
if (fileInCache) return fileInCache;
const fullPath = await instance.assets.getProjectFileUrl(path); const fullPath = await instance.assets.getProjectFileUrl(path);
if (!fullPath) return null; if (!fullPath) throw new Error(`Cannot find project file url for: ${path}`);
const atlasLoader = new AtlasAttachmentLoader(textureAtlas); const atlasLoader = new AtlasAttachmentLoader(textureAtlas);
@ -110,34 +109,32 @@ export class AssetLoader {
const isBinary = path.endsWith(".skel"); const isBinary = path.endsWith(".skel");
if (isBinary) { if (isBinary) {
const content = await instance.assets.fetchArrayBuffer(fullPath); const content = await instance.assets.fetchArrayBuffer(fullPath);
if (!content) return null; if (!content) throw new Error(`Cannot fetch array buffer for: ${fullPath}`);
const skeletonLoader = new SkeletonBinary(atlasLoader); const skeletonLoader = new SkeletonBinary(atlasLoader);
skeletonLoader.scale = scale; skeletonLoader.scale = scale;
skeletonData = skeletonLoader.readSkeletonData(content); skeletonData = skeletonLoader.readSkeletonData(content);
} else { } else {
const content = await instance.assets.fetchJson(fullPath); const content = await instance.assets.fetchJson(fullPath);
if (!content) return null; if (!content) throw new Error(`Cannot fetch json for: ${fullPath}`);
const skeletonLoader = new SkeletonJson(atlasLoader); const skeletonLoader = new SkeletonJson(atlasLoader);
skeletonLoader.scale = scale; skeletonLoader.scale = scale;
skeletonData = skeletonLoader.readSkeletonData(content); skeletonData = skeletonLoader.readSkeletonData(content);
} }
AssetLoader.CacheSkeleton.set(cacheKey, { data: skeletonData, refCount: 1 });
return skeletonData; return skeletonData;
});
return this.loadRuntimeResource(`${path}|scale${scale}`, AssetLoader.CacheSkeleton, loadPromise);
} }
public async loadAtlasRuntime (path: string, instance: IRuntime, renderer: IRenderer) { public async loadAtlasRuntime (path: string, instance: IRuntime, renderer: IRenderer) {
const cacheKey = path; const loadPromise = (async () => {
const fileInCache = this.getFromCache(AssetLoader.CacheAtlas, cacheKey);
if (fileInCache) return fileInCache;
const fullPath = await instance.assets.getProjectFileUrl(path); const fullPath = await instance.assets.getProjectFileUrl(path);
if (!fullPath) return null; if (!fullPath) throw new Error(`Cannot find project file url for: ${path}`);
const content = await instance.assets.fetchText(fullPath); const content = await instance.assets.fetchText(fullPath);
if (!content) return null; if (!content) throw new Error(`Cannot fetch text for: ${fullPath}`);
const basePath = path.substring(0, path.lastIndexOf("/") + 1); const basePath = path.substring(0, path.lastIndexOf("/") + 1);
const textureAtlas = new TextureAtlas(content); const textureAtlas = new TextureAtlas(content);
@ -147,31 +144,29 @@ export class AssetLoader {
return texture; return texture;
})); }));
AssetLoader.CacheAtlas.set(cacheKey, { data: textureAtlas, refCount: 1 });
return textureAtlas; return textureAtlas;
});
return this.loadRuntimeResource(path, AssetLoader.CacheAtlas, loadPromise);
} }
public async loadSpineTextureRuntime (basePath: string, page: TextureAtlasPage, instance: IRuntime, renderer: IRenderer) { public async loadSpineTextureRuntime (basePath: string, page: TextureAtlasPage, instance: IRuntime, renderer: IRenderer) {
const cacheKey = basePath + page.name; const cacheKey = basePath + page.name;
const fileInCache = this.getFromCache(AssetLoader.CacheTexture, cacheKey); const loadPromise = (async () => {
if (fileInCache) return fileInCache;
const fullPath = await instance.assets.getProjectFileUrl(cacheKey); const fullPath = await instance.assets.getProjectFileUrl(cacheKey);
if (!fullPath) return null; if (!fullPath) throw new Error(`Cannot find project file url for: ${cacheKey}`);
const content = await instance.assets.fetchBlob(fullPath); const content = await instance.assets.fetchBlob(fullPath);
if (!content) return null; if (!content) throw new Error(`Cannot fetch blob for: ${fullPath}`);
const image = await AssetLoader.createImageBitmapFromBlob(content, page.pma); const image = await AssetLoader.createImageBitmapFromBlob(content, page.pma);
if (!image) return null; if (!image) throw new Error(`Cannot create image bitmap for: ${fullPath}`);
const spineTexture = new C3TextureRuntime(image, renderer, page); return new C3TextureRuntime(image, renderer, page);
});
this.addToCache(AssetLoader.CacheTexture, cacheKey, spineTexture); return this.loadRuntimeResource(cacheKey, AssetLoader.CacheTexture, loadPromise);
return spineTexture;
} }
public releaseInstanceResources (skeletonPath: string, atlasPath: string, loaderScale: number) { public releaseInstanceResources (skeletonPath: string, atlasPath: string, loaderScale: number) {
@ -179,19 +174,19 @@ export class AssetLoader {
const atlasEntry = AssetLoader.CacheAtlas.get(atlasPath); const atlasEntry = AssetLoader.CacheAtlas.get(atlasPath);
if (atlasEntry) { if (atlasEntry) {
this.releaseResource(AssetLoader.CacheAtlas, atlasPath, () => { this.releaseResource(AssetLoader.CacheAtlas, atlasPath, async () => {
const basePath = atlasPath.substring(0, atlasPath.lastIndexOf("/") + 1); const basePath = atlasPath.substring(0, atlasPath.lastIndexOf("/") + 1);
for (const page of atlasEntry.data.pages) { for (const page of (await atlasEntry.promise).pages) {
const textureKey = basePath + page.name; const textureKey = basePath + page.name;
this.releaseResource(AssetLoader.CacheTexture, textureKey, (texture) => { this.releaseResource(AssetLoader.CacheTexture, textureKey, (texture) => {
texture.dispose(); texture?.dispose();
}); });
} }
}); });
} }
} }
private releaseResource<T> (cache: Map<string, CacheEntry<T>>, key: string, disposer?: (data: T) => void) { private releaseResource<T> (cache: ResourceCache<T>, key: string, disposer?: (data?: T) => void) {
const entry = cache.get(key); const entry = cache.get(key);
if (!entry) return; if (!entry) return;
@ -203,16 +198,26 @@ export class AssetLoader {
} }
} }
private addToCache<T> (cache: Map<string, CacheEntry<T>>, cacheKey: string, data: T) { private async loadRuntimeResource<T> (cacheKey: string, resourceCache: ResourceCache<T>, loader: () => Promise<T>): Promise<T> {
cache.set(cacheKey, { data, refCount: 1 }); const entry = this.getFromCache(resourceCache, cacheKey);
if (entry) return entry.promise;
const result = loader();
this.addToCache(resourceCache, cacheKey, result);
return result;
} }
private getFromCache<T> (cache: Map<string, CacheEntry<T>>, cacheKey: string) { private async addToCache<T> (cache: ResourceCache<T>, cacheKey: string, promise: Promise<T>) {
const fileInCache = cache.get(cacheKey); const cachEntry: CacheEntry<T> = { promise, refCount: 1 };
if (!fileInCache) return undefined; cache.set(cacheKey, cachEntry);
cachEntry.data = await promise;
}
fileInCache.refCount++; private getFromCache<T> (cache: ResourceCache<T>, cacheKey: string) {
return fileInCache.data; const entry = cache.get(cacheKey);
if (!entry) return undefined;
entry.refCount++;
return entry;
} }
static async createImageBitmapFromBlob (blob: Blob, pma: boolean): Promise<ImageBitmap | null> { static async createImageBitmapFromBlob (blob: Blob, pma: boolean): Promise<ImageBitmap | null> {
@ -220,7 +225,7 @@ export class AssetLoader {
return createImageBitmap(blob, { premultiplyAlpha: pma ? "none" : "premultiply" }); return createImageBitmap(blob, { premultiplyAlpha: pma ? "none" : "premultiply" });
} catch (e) { } catch (e) {
console.error("Failed to create ImageBitmap from blob:", e); console.error("Failed to create ImageBitmap from blob:", e);
return null; throw e;
} }
} }