msagent.js: Cache parsed ACS data

Instead of duplicating it per every instance of an Agent, since it is never mutated by an Agent, we can just cache it.
This commit is contained in:
Lily Tsuru 2024-07-12 19:13:53 -04:00
parent 1d19098ca7
commit 61dc78ba3b

View file

@ -13,7 +13,15 @@ export class AcsData {
images: AcsImageEntry[] = []; images: AcsImageEntry[] = [];
} }
function agentCharacterParseACS(buffer: BufferStream): AcsData { // Cache of ACS data per character (for agentCreateCharacterFromUrl)
let acsDataCache = new Map<string, AcsData>();
// Purges the ACS cache.
export function agentPurgeACSCache() {
acsDataCache.clear();
}
export function agentCharacterParseACS(buffer: BufferStream): AcsData {
// Make sure the magic is correct for the ACS file. // Make sure the magic is correct for the ACS file.
if (buffer.readU32LE() != 0xabcdabc3) { if (buffer.readU32LE() != 0xabcdabc3) {
throw new Error('The provided data buffer does not contain valid ACS data.'); throw new Error('The provided data buffer does not contain valid ACS data.');
@ -47,12 +55,22 @@ function agentCharacterParseACS(buffer: BufferStream): AcsData {
return acsData; return acsData;
} }
export function agentCreateCharacter(data: Uint8Array): Agent { export function agentCreateCharacter(data: AcsData): Agent {
return new Agent(agentCharacterParseACS(new BufferStream(data))); return new Agent(data);
} }
export async function agentCreateCharacterFromUrl(url: string) { export async function agentCreateCharacterFromUrl(url: string) : Promise<Agent> {
let res = await fetch(url); // just return the cache object
let data = await res.arrayBuffer(); if(acsDataCache.has(url)) {
return agentCreateCharacter(new Uint8Array(data)); return agentCreateCharacter(acsDataCache.get(url)!);
} else {
let res = await fetch(url);
let data = await res.arrayBuffer();
let buffer = new Uint8Array(data);
let acsData = agentCharacterParseACS(new BufferStream(buffer));
acsDataCache.set(url, acsData);
return agentCreateCharacter(acsData);
}
} }