File size: 4,450 Bytes
3530df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import parseASCII from "parse-bmfont-ascii";
import parseXML from "parse-bmfont-xml";
import readBinary from "parse-bmfont-binary";
import { BmCharacter, BmKerning, BmFont, BmCommonProps } from "./types.js";
import png from "@jimp/js-png";
import { createJimp } from "@jimp/core";
import path from "path";
import xmlPackage from "simple-xml-to-json";

const { convertXML } = xmlPackage;

export const isWebWorker =
  typeof self !== "undefined" && self.document === undefined;

const CharacterJimp = createJimp({ formats: [png] });
const HEADER = Buffer.from([66, 77, 70, 3]);

function isBinary(buf: Buffer | string) {
  if (typeof buf === "string") {
    return buf.substring(0, 3) === "BMF";
  }

  const startOfHeader = buf.slice(0, 4);

  return (
    buf.length > 4 &&
    startOfHeader[0] === HEADER[0] &&
    startOfHeader[1] === HEADER[1] &&
    startOfHeader[2] === HEADER[2]
  );
}

export interface LoadedFont {
  chars: BmCharacter[];
  kernings: BmKerning[];
  common: BmCommonProps;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  info: Record<string, any>;
  pages: string[];
}

function parseFont(file: string, data: Buffer | string): LoadedFont {
  if (isBinary(data)) {
    if (typeof data === "string") {
      data = Buffer.from(data, "binary");
    }

    return readBinary(data);
  }

  data = data.toString().trim();

  if (/.json$/.test(file) || data.charAt(0) === "{") {
    return JSON.parse(data);
  }

  if (/.xml$/.test(file) || data.charAt(0) === "<") {
    return parseXML(data);
  }

  return parseASCII(data);
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function parseNumbersInObject<T extends Record<string, any>>(obj: T) {
  for (const key in obj) {
    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (obj as any)[key] = parseInt(obj[key], 10);
    } catch {
      // do nothing
    }

    if (typeof obj[key] === "object") {
      parseNumbersInObject(obj[key]);
    }
  }

  return obj;
}

/**
 *
 * @param bufferOrUrl A URL to a file or a buffer
 * @returns
 */
export async function loadBitmapFontData(
  bufferOrUrl: string | Buffer
): Promise<LoadedFont> {
  if (isWebWorker && typeof bufferOrUrl === "string") {
    const res = await fetch(bufferOrUrl);
    const text = await res.text();
    const json = convertXML(text);

    const font = json.font.children.reduce(
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (acc: Record<string, any>, i: any) => ({ ...acc, ...i }),
      {}
    );
    const pages: LoadedFont["pages"] = [];
    const chars: LoadedFont["chars"] = [];
    const kernings: LoadedFont["kernings"] = [];

    for (let i = 0; i < font.pages.children.length; i++) {
      const p = font.pages.children[i].page;
      const id = parseInt(p.id, 10);
      pages[id] = parseNumbersInObject(p.file);
    }

    for (let i = 0; i < font.chars.children.length; i++) {
      chars.push(parseNumbersInObject(font.chars.children[i].char));
    }

    for (let i = 0; i < font.kernings.children.length; i++) {
      kernings.push(parseNumbersInObject(font.kernings.children[i].kerning));
    }

    return {
      info: font.info,
      common: font.common,
      pages,
      chars,
      kernings,
    } satisfies LoadedFont;
  } else if (typeof bufferOrUrl === "string") {
    const res = await fetch(bufferOrUrl);
    const text = await res.text();

    return parseFont(bufferOrUrl, text);
  } else {
    return parseFont("", bufferOrUrl);
  }
}

type RawFont = Awaited<ReturnType<typeof loadBitmapFontData>>;
export type ResolveBmFont = Omit<BmFont, "pages"> & Pick<RawFont, "pages">;

export async function processBitmapFont(file: string, font: LoadedFont) {
  const chars: Record<string, BmCharacter> = {};
  const kernings: Record<string, BmKerning> = {};

  for (let i = 0; i < font.chars.length; i++) {
    const char = font.chars[i]!;
    chars[String.fromCharCode(char.id)] = char;
  }

  for (let i = 0; i < font.kernings.length; i++) {
    const firstString = String.fromCharCode(font.kernings[i]!.first);

    kernings[firstString] = kernings[firstString]! || {};
    kernings[firstString]![String.fromCharCode(font.kernings[i]!.second)] =
      font.kernings[i]!.amount;
  }

  return {
    ...font,
    chars,
    kernings,
    pages: await Promise.all(
      font.pages.map(async (page) =>
        CharacterJimp.read(path.join(path.dirname(file), page))
      )
    ),
  };
}