Files
bworld/client/assets.ts
T
2026-11-22 07:21:29 -03:00

60 lines
1.5 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import { load_texture, Texture } from "./renderer/mod.ts";
type Asset = Texture | string | Record<string, unknown>;
export class AssetManager {
static instance = new AssetManager();
assets: Record<string, Asset> = {};
loading_promises: Promise<void>[] = [];
constructor() {}
load(key: string, src: string) {
if (this.assets[key]) {
return;
}
if (src.endsWith(".png")) {
const img = new Image();
const promise = new Promise<void>((resolve, reject) => {
img.onload = () => {
this.assets[key] = load_texture(img);
resolve();
};
img.onerror = () => reject(new Error(`Failed to load image: ${src}`));
});
img.src = src;
this.loading_promises.push(promise);
} else if (src.endsWith(".txt") || src.endsWith(".md") || src.endsWith(".fnt")) {
const promise = async () => {
const resp = await fetch(src);
this.assets[key] = await resp.text();
};
this.loading_promises.push(promise());
} else if (src.endsWith(".json")) {
const promise = async () => {
const resp = await fetch(src);
this.assets[key] = await resp.json();
};
this.loading_promises.push(promise());
}
}
async load_all() {
await Promise.all(this.loading_promises);
this.loading_promises = [];
}
get<T>(key: string): T {
const asset = this.assets[key];
if (!asset) {
throw new Error(`Asset not found: ${key}`);
}
return asset as T;
}
}