Files

60 lines
1.6 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import { load_texture, Texture } from "./renderer/mod.ts";
import { decode_png } from "./png.ts";
import { platform } from "./platform.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;
}
// the client's own files are next to the page, see platform.page
const url = new URL(src, platform.page);
if (src.endsWith(".png")) {
const promise = async () => {
const resp = await fetch(url);
if (!resp.ok) throw new Error(`Failed to load image: ${src}`);
this.assets[key] = load_texture(decode_png(new Uint8Array(await resp.arrayBuffer())));
};
this.loading_promises.push(promise());
} else if (src.endsWith(".txt") || src.endsWith(".md") || src.endsWith(".fnt")) {
const promise = async () => {
const resp = await fetch(url);
this.assets[key] = await resp.text();
};
this.loading_promises.push(promise());
} else if (src.endsWith(".json")) {
const promise = async () => {
const resp = await fetch(url);
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;
}
}