All files / player-browser/src/skin/lr2 font-loader.ts

34.81% Statements 55/158
26.82% Branches 22/82
71.42% Functions 15/21
36.49% Lines 50/137

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323                              33x                                       6x 6x 6x 6x   1x 1x 1x     6x 6x             1x 1x   1x               1x 1x                                                                                           1x 1x 1x 1x 1x 1x 1x   1x                                                                                       1x 1x   1x 1x 1x 1x     1x       1x       1x                 1x         1x                                                                                                                 1x 1x 1x                       1x       1x 1x           1x 1x 1x 3x 3x       3x   1x       2x 2x                                                         2x    
import { Texture } from 'pixi.js';
import {
  decodeDDSImageData,
  decodeTGA,
  isTGAImage,
  parseLR2Font,
  readDxaArchive,
  type LR2BitmapFont,
  type LR2SkinFileEntry,
} from '@be-music/skin-lr2';
import { normalizePath } from '@be-music/shared-utils/core';
import type { LR2LoadedFont } from './bitmap-text.ts';
import { loadTextureFromBytes as loadImageTextureFromBytes } from '../../media/textures.ts';
import { logger } from '../../logger.ts';
 
const log = logger('lr2-font');
 
/**
 * Loads every `#LR2FONT,n,path` declared by a parsed skin into runtime `LR2LoadedFont` payloads.
 *
 * Each declared path can resolve to either:
 *
 * - A bare `.lr2font` text file (with sibling PNGs / BMPs) — the most permissive path; works as long as the user has
 *   extracted the LR2 default theme's `.dxa` archives ahead of time using the bundled `DxaDecode.exe`.
 * - A `.dxa` archive containing the `.lr2font` plus its images — we attempt to read it, but DXA decryption isn't
 *   implemented yet so encrypted archives (the LR2 default theme bundles) silently fall through to the system-font
 *   path.
 *
 * Failures are non-fatal: the returned map only contains fonts that loaded successfully. Missing entries make
 * `makeLR2TextSprite` use the system-font fallback for that font index, which still produces readable text.
 */
export async function loadSkinBitmapFonts(
  fontPaths: ReadonlyArray<string>,
  files: ReadonlyMap<string, LR2SkinFileEntry>,
): Promise<Map<number, LR2LoadedFont>> {
  const declared = fontPaths.filter((path) => path.length > 0).length;
  log.info(`start: ${declared}/${fontPaths.length} non-empty font slots, ${files.size} files in source`);
  const out = new Map<number, LR2LoadedFont>();
  await Promise.all(
    fontPaths.map(async (path, index) => {
      Iif (path.length === 0) return;
      const loaded = await tryLoadFont(path, files);
      Eif (loaded) out.set(index, loaded);
    }),
  );
  log.info(`done: loaded ${out.size}/${declared} bitmap fonts`);
  return out;
}
 
async function tryLoadFont(
  declaredPath: string,
  files: ReadonlyMap<string, LR2SkinFileEntry>,
): Promise<LR2LoadedFont | undefined> {
  const lower = declaredPath.toLowerCase();
  const direct = lookupCaseInsensitive(files, declaredPath);
  // Direct hit on a `.dxa` declaration.
  Iif (lower.endsWith('.dxa')) {
    if (!direct) {
      log.info(`miss: declared .dxa not found in source: ${declaredPath}`);
      return undefined;
    }
    return loadFontFromDxa(direct, declaredPath);
  }
  // Direct hit on a bare `.lr2font` text file (already-extracted theme).
  Eif (lower.endsWith('.lr2font') && direct) {
    return loadFontFromBareFile(direct, declaredPath, files);
  }
  // LR2 default-theme convention: skin CSV references e.g. `Select/optionfont/font.lr2font` even though no such
  // directory exists — the actual content sits inside `Select/optionfont.dxa`. LR2 strips the trailing
  // `<basename>/<basename>.lr2font` suffix and tries the `.dxa` next to it. We mirror that here.
  if (lower.endsWith('.lr2font')) {
    const archivePath = collapseLR2FontDirectoryToDxa(declaredPath);
    if (archivePath) {
      const archiveBytes = lookupCaseInsensitive(files, archivePath);
      if (archiveBytes) return loadFontFromDxa(archiveBytes, archivePath);
      log.info(`miss: collapsed-dir .dxa not found: ${declaredPath} → tried ${archivePath}`);
    }
  }
  // Some themes name the path without an extension. Try both common siblings before giving up.
  const dxa = lookupCaseInsensitive(files, `${declaredPath}.dxa`);
  if (dxa) return loadFontFromDxa(dxa, declaredPath);
  const lr2font = lookupCaseInsensitive(files, `${declaredPath}.lr2font`);
  if (lr2font) return loadFontFromBareFile(lr2font, declaredPath, files);
  // Nothing matched — emit a diagnostic listing the candidate paths we tried so the user can match against their actual
  // file layout. The most common cause is a filename-encoding mismatch (Shift-JIS path in the CSV vs. UTF-8 keys in the
  // source files map) or a directory-loader that skipped binary files entirely.
  log.info(
    `miss: no matching file for declared path "${declaredPath}" ` +
      `(tried direct, collapsed .dxa, suffix .dxa, suffix .lr2font)`,
  );
  return undefined;
}
 
/**
 * Returns the `.dxa` archive path corresponding to LR2's "directory-pretending-to-be-an-archive" convention. The skin
 * CSV references e.g. `Select/optionfont/font.lr2font` and LR2, when the directory doesn't exist, falls back to
 * `Select/optionfont.dxa` (the parent directory's name becomes the archive name; the leaf `.lr2font` filename is
 * whatever the archive packs internally).
 */
function collapseLR2FontDirectoryToDxa(declaredPath: string): string | undefined {
  const normalized = declaredPath.replace(/\\/g, '/');
  const lastSlash = normalized.lastIndexOf('/');
  if (lastSlash <= 0) return undefined;
  return `${normalized.slice(0, lastSlash)}.dxa`;
}
 
async function loadFontFromBareFile(
  bytes: Uint8Array,
  fontPath: string,
  files: ReadonlyMap<string, LR2SkinFileEntry>,
): Promise<LR2LoadedFont | undefined> {
  const text = decodeText(bytes);
  Iif (!text) return undefined;
  const font = parseLR2Font(text);
  const fontDir = directoryOf(fontPath);
  const textures = await loadFontTextures(font, (relPath) => {
    const resolved = joinRelative(fontDir, relPath);
    return lookupCaseInsensitive(files, resolved);
  });
  return { font, textures };
}
 
async function loadFontFromDxa(bytes: Uint8Array, fontPath: string): Promise<LR2LoadedFont | undefined> {
  const archive = readDxaArchive(bytes);
  if (!archive) {
    // Decode failed — most often because the archive is encrypted (the LR2 default theme bundles use a non-default key
    // we can't recover) or because the format isn't a DXA V3 we recognize. The renderer falls back to system-font /
    // placeholder text so the scene is still legible. Logged once per font path at INFO since this is expected on
    // user-shipped themes; not a warning.
    log.info(`DXA decode failed: ${fontPath} (encrypted or unsupported)`);
    return undefined;
  }
  // Build an in-archive lookup map so the .lr2font's relative image references resolve to extracted bytes.
  const archiveFiles = new Map<string, Uint8Array>();
  for (const file of archive.files) {
    archiveFiles.set(normalizePath(file.path).toLowerCase(), file.data);
  }
  const lr2FontFile = archive.files.find((file) => file.path.toLowerCase().endsWith('.lr2font'));
  if (!lr2FontFile) {
    log.info(`DXA decoded OK but contained no .lr2font: ${fontPath}`);
    return undefined;
  }
  const text = decodeText(lr2FontFile.data);
  if (!text) {
    log.info(`DXA .lr2font text decode failed: ${fontPath}`);
    return undefined;
  }
  const font = parseLR2Font(text);
  const textures = await loadFontTextures(font, (relPath) => {
    const normalized = normalizePath(relPath).toLowerCase();
    return archiveFiles.get(normalized);
  });
  // Success path — log so the user can confirm which fonts came through the DXA pipeline at runtime. Also emits the
  // texture count, which is the easiest cue when a font decodes but its sibling images don't (zero textures → glyphs
  // fall back to placeholder rectangles even though the layout is correct).
  log.info(`DXA decoded OK: ${fontPath} (${archive.files.length} entries, ${textures.size} textures)`);
  return { font, textures };
}
 
async function loadFontTextures(
  font: LR2BitmapFont,
  resolver: (relativePath: string) => Uint8Array | undefined,
): Promise<Map<number, Texture>> {
  const out = new Map<number, Texture>();
  await Promise.all(
    [...font.images.entries()].map(async ([gr, relPath]) => {
      const bytes = resolver(relPath);
      Iif (!bytes) return;
      const texture = await loadTextureFromBytes(bytes, relPath);
      Eif (texture) out.set(gr, texture);
    }),
  );
  return out;
}
 
async function loadTextureFromBytes(bytes: Uint8Array, relPath: string): Promise<Texture | undefined> {
  const ext = (relPath.toLowerCase().split('.').pop() ?? 'png').replace(/[^a-z0-9]/g, '');
  // TGA branch — browsers don't natively decode TrueVision Targa, so we run our own decoder and upload the raw RGBA
  // pixels via `createImageBitmap`. The LR2 default theme ships every font texture as `.tga`, so this is the hot path
  // for that bundle.
  Iif (ext === 'tga' || isTGAImage(bytes)) {
    return loadTGATexture(bytes, relPath);
  }
  // DDS branch — modern LR2 themes (LITONE4 etc.) ship bitmap-font textures as `.dds` (typically uncompressed
  // 32-bit BGRA inside a DXA archive). Browsers don't decode DDS natively; running it through `Assets.load(blobURL)`
  // makes Pixi resolve the URL with a null texture (the loader treats unrecognised payloads as a soft failure),
  // which then crashed `attachBlobURLToTexture(null, url)` with `Cannot set properties of null (...)`. Pre-decode via
  // {@link decodeDDSImageData} bypasses Pixi's URL pipeline entirely and produces the same texture shape as the TGA
  // branch — same canvas → `Texture.from(canvas)` chain so chroma keying / nearest sampling stays consistent.
  Iif (ext === 'dds') {
    return loadDDSTexture(bytes, relPath);
  }
  // Blob URLs carry no extension for Pixi's asset parser selection. Use the shared byte decoder,
  // which detects PNG/BMP/JPEG directly (WMIX_HD mixes PNG and TGA sheets in a single font).
  return loadImageTextureFromBytes(relPath, bytes);
}
 
/**
 * Decodes a DDS font sheet into a Pixi `Texture` via the OffscreenCanvas path. Mirrors {@link loadTGATexture}'s
 * shape so the two pre-decoded branches stay symmetric; the only differences are the DDS decoder call and the
 * (compressed) DDS variants that aren't supported yet returning `undefined` (a soft failure — the renderer falls
 * back to system-font placeholder rendering for that font slot).
 */
async function loadDDSTexture(bytes: Uint8Array, relPath: string): Promise<Texture | undefined> {
  const decoded = decodeDDSImageData(bytes);
  if (!decoded) {
    // `decodeDDSImageData` returns undefined for DXT-compressed / non-32-bit / DX10-header DDS variants. Logged at
    // INFO since "unsupported variant" is expected for some themes and the chrome stays usable via system-font
    // fallback.
    log.info(`unsupported DDS variant: ${relPath} (compressed or non-BGRA32) — falling back`);
    return undefined;
  }
  if (typeof OffscreenCanvas === 'undefined') return undefined;
  const canvas = new OffscreenCanvas(decoded.width, decoded.height);
  const ctx = canvas.getContext('2d');
  if (!ctx) return undefined;
  // `decoded.rgba` is a `Uint8ClampedArray`. `ctx.createImageData` allocates a fresh data array; we copy our pixel
  // bytes into it so the `ImageData` instance owns the buffer (matches the TGA path; lets the GC drop the original
  // typed array after the upload completes).
  const imageData = ctx.createImageData(decoded.width, decoded.height);
  imageData.data.set(decoded.rgba);
  ctx.putImageData(imageData, 0, 0);
  return Texture.from(canvas as unknown as HTMLCanvasElement);
}
 
async function loadTGATexture(bytes: Uint8Array, relPath: string): Promise<Texture | undefined> {
  const decoded = decodeTGA(bytes);
  if (!decoded) {
    log.warn(`failed to decode TGA ${relPath}`);
    return undefined;
  }
  // Wrap the raw pixels in `ImageData`, then either rasterize via `createImageBitmap` (browser fast path) or paint to
  // an OffscreenCanvas. Returns `undefined` if the runtime exposes neither (Node test environments).
  if (typeof OffscreenCanvas === 'undefined') return undefined;
  // Paint the decoded RGBA pixels onto an offscreen canvas via `putImageData`, then hand the canvas to Pixi as a
  // texture source. Using `OffscreenCanvas` (rather than mounting a DOM `<canvas>`) keeps the load path off the main
  // thread / DOM.
  const canvas = new OffscreenCanvas(decoded.width, decoded.height);
  const ctx = canvas.getContext('2d');
  if (!ctx) return undefined;
  // Construct ImageData via the ctx helper (`createImageData`) so we get a runtime-correct constructor regardless of
  // the lib version, then copy the decoded pixels into its `data` slot.
  const imageData = ctx.createImageData(decoded.width, decoded.height);
  imageData.data.set(decoded.data);
  ctx.putImageData(imageData, 0, 0);
  return Texture.from(canvas as unknown as HTMLCanvasElement);
}
 
function decodeText(bytes: Uint8Array): string | undefined {
  // `.lr2font` files are SHIFT-JIS in practice (FontUtil's output uses the LR2-era default codepage). Fall back to
  // UTF-8 so a hand-edited UTF-8 file still parses.
  try {
    const sjis = new TextDecoder('shift-jis', { fatal: false }).decode(bytes);
    Eif (looksLikeFontText(sjis)) return sjis;
  } catch {
    // not available in the runtime — fall through
  }
  try {
    return new TextDecoder('utf-8', { fatal: false }).decode(bytes);
  } catch {
    return undefined;
  }
}
 
function looksLikeFontText(text: string): boolean {
  return /^\s*#[STMR]\b/m.test(text);
}
 
function directoryOf(path: string): string {
  const slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
  return slash >= 0 ? path.slice(0, slash) : '';
}
 
function joinRelative(base: string, rel: string): string {
  // `.lr2font` references use Windows conventions (`..\foo\bar.png`). Normalize to forward slashes and resolve `.` /
  // `..` segments against `base`.
  const segments = `${base}/${rel}`.replace(/\\/g, '/').split('/');
  const stack: string[] = [];
  for (const seg of segments) {
    Iif (seg === '' || seg === '.') continue;
    Iif (seg === '..') {
      stack.pop();
      continue;
    }
    stack.push(seg);
  }
  return stack.join('/');
}
 
function lookupCaseInsensitive(files: ReadonlyMap<string, LR2SkinFileEntry>, path: string): Uint8Array | undefined {
  const direct = asLoadedBytes(files.get(path));
  Eif (direct) return direct;
  const target = normalizePath(path).toLowerCase();
  for (const [key, value] of files) {
    if (normalizePath(key).toLowerCase() === target) {
      const bytes = asLoadedBytes(value);
      if (bytes) return bytes;
    }
  }
  // Suffix-match fallback. Common case: the user dropped the `LR2beta3/` parent folder, so file keys look like
  // `LR2beta3/LR2files/Theme/LR2/Select/barfnt.dxa` while the skin CSV declares `LR2files/Theme/LR2/Select/barfnt.dxa`.
  // Treat any key that ends with `/<target>` as a match. Among multiple candidates we pick the shortest — the one whose
  // extra prefix is the smallest, which is the most-specific mount under the user-dropped root.
  const suffix = `/${target}`;
  let bestKey: string | undefined;
  let bestValue: Uint8Array | undefined;
  for (const [key, value] of files) {
    const norm = normalizePath(key).toLowerCase();
    if (!norm.endsWith(suffix)) continue;
    const bytes = asLoadedBytes(value);
    if (!bytes) continue;
    if (bestKey === undefined || key.length < bestKey.length) {
      bestKey = key;
      bestValue = bytes;
    }
  }
  return bestValue;
}
 
function asLoadedBytes(entry: LR2SkinFileEntry | undefined): Uint8Array | undefined {
  return entry instanceof Uint8Array ? entry : undefined;
}