@forgeax/engine-font 0.0.0-dev.8d955ade1c79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +98 -0
  3. package/dist/.tsbuildinfo +1 -0
  4. package/dist/__tests__/font-importer.test.d.ts +2 -0
  5. package/dist/__tests__/font-importer.test.d.ts.map +1 -0
  6. package/dist/__tests__/font-local-artifacts.test.d.ts +2 -0
  7. package/dist/__tests__/font-local-artifacts.test.d.ts.map +1 -0
  8. package/dist/__tests__/font.unit.test.d.ts +2 -0
  9. package/dist/__tests__/font.unit.test.d.ts.map +1 -0
  10. package/dist/cli-font.d.ts +96 -0
  11. package/dist/cli-font.d.ts.map +1 -0
  12. package/dist/cli-font.mjs +339 -0
  13. package/dist/cli-font.mjs.map +1 -0
  14. package/dist/font-importer.d.ts +18 -0
  15. package/dist/font-importer.d.ts.map +1 -0
  16. package/dist/font-importer.mjs +469 -0
  17. package/dist/font-importer.mjs.map +1 -0
  18. package/dist/index.d.ts +2 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.mjs +54 -0
  21. package/dist/index.mjs.map +1 -0
  22. package/dist/node-msdf-worker.mjs +35 -0
  23. package/dist/node-msdf-worker.mjs.map +1 -0
  24. package/dist/node-worker-adapter.d.ts +17 -0
  25. package/dist/node-worker-adapter.d.ts.map +1 -0
  26. package/dist/runtime/font-decoder.d.ts +3 -0
  27. package/dist/runtime/font-decoder.d.ts.map +1 -0
  28. package/package.json +80 -0
  29. package/src/__tests__/font-importer.test.ts +24 -0
  30. package/src/__tests__/font-local-artifacts.test.ts +58 -0
  31. package/src/__tests__/font.unit.test.ts +394 -0
  32. package/src/cli-font.ts +472 -0
  33. package/src/font-importer.ts +205 -0
  34. package/src/index.ts +7 -0
  35. package/src/node-msdf-worker.mjs +38 -0
  36. package/src/node-worker-adapter.ts +41 -0
  37. package/src/runtime/font-decoder.ts +70 -0
@@ -0,0 +1,472 @@
1
+ #!/usr/bin/env node
2
+
3
+ // @forgeax/engine-font/src/cli-font — `forgeax-engine-remote-font` plugin
4
+ // bin. Discovered by the base bin via the kubectl 4th-path
5
+ // `forgeax-engine-remote-` prefix scanner.
6
+ //
7
+ // `bake <ttf> <out>` reads a TrueType font and produces an MSDF atlas PNG +
8
+ // a glyph-metrics sidecar JSON (importer: 'font'). The real bake calls
9
+ // @zappar/msdf-generator (feat-20260531-world-space-msdf-text-rendering M5 /
10
+ // w28 -- replaces the M1 placeholder).
11
+ //
12
+ // Error model (FontErrorCode, structured to stderr, exit code 1):
13
+ // - non-TTF magic (not 0x00010000 / 'true' / 'OTTO') -> 'unsupported-font-format'
14
+ // (AC-15 / plan-strategy D-11). The check runs BEFORE the generator so a
15
+ // bad format never reaches the wasm path.
16
+ // - @zappar/msdf-generator throws (wasm / Worker unavailable, internal error)
17
+ // -> 'bake-failed' (charter P3: explicit failure, never a silent exit-0
18
+ // no-atlas). In a plain Node CI without a Web Worker the generator throws
19
+ // 'Worker is not defined' and the bake reports 'bake-failed' (exit 1) --
20
+ // the best-effort real run requires a Worker + wasm host.
21
+
22
+ import { Buffer } from 'node:buffer';
23
+ import { mkdir, readFile, realpath, writeFile } from 'node:fs/promises';
24
+ import { basename, extname, join } from 'node:path';
25
+ import { fileURLToPath } from 'node:url';
26
+ import { parseArgs } from 'node:util';
27
+ import { deflateSync } from 'node:zlib';
28
+ import { FontError, type GlyphMetric } from '@forgeax/engine-types';
29
+ import { NodeWorkerAdapter } from './node-worker-adapter.js';
30
+
31
+ /**
32
+ * Minimal subset of the @zappar/msdf-generator glyph record consumed by the
33
+ * bake. Mirrors the package's `GlyphInfo` (dist/index.d.ts) -- only the fields
34
+ * the BMFont -> FontAsset mapping needs (toolchain wiki section 4).
35
+ */
36
+ export interface BakeGlyph {
37
+ readonly unicode: number;
38
+ readonly advance: number;
39
+ readonly xoffset: number;
40
+ readonly yoffset: number;
41
+ readonly atlasPosition: readonly [number, number];
42
+ readonly atlasSize: readonly [number, number];
43
+ }
44
+
45
+ /**
46
+ * Minimal subset of the @zappar/msdf-generator `MSDFAtlas` consumed by the
47
+ * bake. `texture` carries the RGBA pixel buffer + dimensions (the package's
48
+ * `ImageData`-shaped texture, but reduced to POD so the bake stays
49
+ * environment-agnostic for testing).
50
+ */
51
+ export interface BakeAtlas {
52
+ readonly texture: { readonly width: number; readonly height: number; readonly data: Uint8Array };
53
+ readonly glyphs: readonly BakeGlyph[];
54
+ readonly metrics: { readonly lineHeight: number; readonly ascender: number };
55
+ readonly textureSize: readonly [number, number];
56
+ readonly fieldRange: number;
57
+ }
58
+
59
+ /**
60
+ * The bake-time MSDF generator contract. Injected into {@link bakeFont} so
61
+ * unit tests can supply a mock (real path: `@zappar/msdf-generator`'s `MSDF`).
62
+ */
63
+ export interface MsdfGenerator {
64
+ generateAtlas(ttf: Uint8Array): Promise<BakeAtlas>;
65
+ dispose(): Promise<void>;
66
+ }
67
+
68
+ /** Default charset baked into the atlas (printable ASCII). */
69
+ const DEFAULT_CHARSET = (() => {
70
+ let s = '';
71
+ for (let c = 0x20; c <= 0x7e; c++) s += String.fromCharCode(c);
72
+ return s;
73
+ })();
74
+
75
+ const DEFAULT_TEXTURE_SIZE = 1024;
76
+ const DEFAULT_FIELD_RANGE = 4;
77
+ const DEFAULT_FONT_SIZE = 48;
78
+
79
+ /**
80
+ * Bake-time sidecar JSON shape (importer: 'font'). Carries the glyph metrics
81
+ * (BMFont -> FontAsset mapping, toolchain wiki section 4) + the common block
82
+ * (distanceRange / atlas dimensions). Parsed by the runtime font load path.
83
+ */
84
+ export interface BakeSidecar {
85
+ readonly schemaVersion: string;
86
+ readonly kind: 'external-asset-package';
87
+ readonly importer: 'font';
88
+ readonly source: string;
89
+ readonly importSettings: { readonly colorSpace: 'linear'; readonly mipmap: 'none' };
90
+ readonly common: {
91
+ readonly lineHeight: number;
92
+ readonly base: number;
93
+ readonly distanceRange: number;
94
+ readonly pxRange: number;
95
+ readonly atlasWidth: number;
96
+ readonly atlasHeight: number;
97
+ };
98
+ readonly glyphs: Record<number, GlyphMetric>;
99
+ }
100
+
101
+ /** TTF / OTF magic numbers (first 4 bytes). Per the OpenType spec. */
102
+ function isSupportedFontMagic(bytes: Uint8Array): boolean {
103
+ if (bytes.length < 4) return false;
104
+ const b0 = bytes[0] ?? 0;
105
+ const b1 = bytes[1] ?? 0;
106
+ const b2 = bytes[2] ?? 0;
107
+ const b3 = bytes[3] ?? 0;
108
+ // 0x00010000 = TrueType outlines; 'true' (0x74727565) = legacy Apple TTF;
109
+ // 'OTTO' (0x4f54544f) = OpenType with CFF outlines. WOFF/WOFF2 ('wOFF' /
110
+ // 'wOF2') are rejected as non-TTF per AC-15.
111
+ const isTrueType = b0 === 0x00 && b1 === 0x01 && b2 === 0x00 && b3 === 0x00;
112
+ const isTrue = b0 === 0x74 && b1 === 0x72 && b2 === 0x75 && b3 === 0x65;
113
+ const isOtto = b0 === 0x4f && b1 === 0x54 && b2 === 0x54 && b3 === 0x4f;
114
+ return isTrueType || isTrue || isOtto;
115
+ }
116
+
117
+ /** CRC-32 (PNG / zlib polynomial) over a byte slice. */
118
+ function crc32(bytes: Uint8Array): number {
119
+ let crc = 0xffffffff;
120
+ for (let i = 0; i < bytes.length; i++) {
121
+ crc ^= bytes[i] ?? 0;
122
+ for (let k = 0; k < 8; k++) {
123
+ crc = crc & 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;
124
+ }
125
+ }
126
+ return (crc ^ 0xffffffff) >>> 0;
127
+ }
128
+
129
+ function pngChunk(type: string, data: Uint8Array): Uint8Array {
130
+ const typeBytes = new Uint8Array([
131
+ type.charCodeAt(0),
132
+ type.charCodeAt(1),
133
+ type.charCodeAt(2),
134
+ type.charCodeAt(3),
135
+ ]);
136
+ const body = new Uint8Array(typeBytes.length + data.length);
137
+ body.set(typeBytes, 0);
138
+ body.set(data, typeBytes.length);
139
+ const out = new Uint8Array(4 + body.length + 4);
140
+ const dv = new DataView(out.buffer);
141
+ dv.setUint32(0, data.length);
142
+ out.set(body, 4);
143
+ dv.setUint32(4 + body.length, crc32(body));
144
+ return out;
145
+ }
146
+
147
+ /**
148
+ * Encode an RGBA pixel buffer into a PNG (zlib deflate, no external deps).
149
+ * The atlas texture from @zappar is RGBA8; this writes a standard 8-bit
150
+ * RGBA PNG so any consumer (engine image importer / browser) can decode it.
151
+ */
152
+ export function encodePng(width: number, height: number, rgba: Uint8Array): Uint8Array {
153
+ // Filter byte 0 (None) prefixes each scanline.
154
+ const stride = width * 4;
155
+ const raw = new Uint8Array((stride + 1) * height);
156
+ for (let y = 0; y < height; y++) {
157
+ raw[y * (stride + 1)] = 0;
158
+ raw.set(rgba.subarray(y * stride, y * stride + stride), y * (stride + 1) + 1);
159
+ }
160
+ const idat = deflateSync(raw);
161
+ const ihdr = new Uint8Array(13);
162
+ const dv = new DataView(ihdr.buffer);
163
+ dv.setUint32(0, width);
164
+ dv.setUint32(4, height);
165
+ ihdr[8] = 8; // bit depth
166
+ ihdr[9] = 6; // color type RGBA
167
+ ihdr[10] = 0; // compression
168
+ ihdr[11] = 0; // filter
169
+ ihdr[12] = 0; // interlace
170
+ const signature = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
171
+ const chunks = [
172
+ signature,
173
+ pngChunk('IHDR', ihdr),
174
+ pngChunk('IDAT', new Uint8Array(idat)),
175
+ pngChunk('IEND', new Uint8Array(0)),
176
+ ];
177
+ const total = chunks.reduce((n, c) => n + c.length, 0);
178
+ const out = new Uint8Array(total);
179
+ let off = 0;
180
+ for (const c of chunks) {
181
+ out.set(c, off);
182
+ off += c.length;
183
+ }
184
+ return out;
185
+ }
186
+
187
+ /** Map a @zappar atlas into the FontAsset glyph-metrics sidecar shape. */
188
+ export function atlasToSidecar(atlas: BakeAtlas, sourcePng: string): BakeSidecar {
189
+ const glyphs: Record<number, GlyphMetric> = {};
190
+ for (const g of atlas.glyphs) {
191
+ glyphs[g.unicode] = {
192
+ advance: g.advance,
193
+ bearingX: g.xoffset,
194
+ bearingY: g.yoffset,
195
+ size: { w: g.atlasSize[0], h: g.atlasSize[1] },
196
+ region: {
197
+ x: g.atlasPosition[0],
198
+ y: g.atlasPosition[1],
199
+ w: g.atlasSize[0],
200
+ h: g.atlasSize[1],
201
+ },
202
+ };
203
+ }
204
+ return {
205
+ schemaVersion: '1.0.0',
206
+ kind: 'external-asset-package',
207
+ importer: 'font',
208
+ source: sourcePng,
209
+ importSettings: { colorSpace: 'linear', mipmap: 'none' },
210
+ common: {
211
+ lineHeight: atlas.metrics.lineHeight,
212
+ base: atlas.metrics.ascender,
213
+ distanceRange: atlas.fieldRange,
214
+ pxRange: atlas.fieldRange,
215
+ atlasWidth: atlas.textureSize[0],
216
+ atlasHeight: atlas.textureSize[1],
217
+ },
218
+ glyphs,
219
+ };
220
+ }
221
+
222
+ /** Result of a successful bake -- the written artefact paths. */
223
+ export interface BakeResult {
224
+ readonly atlasPath: string;
225
+ readonly sidecarPath: string;
226
+ }
227
+
228
+ /**
229
+ * Bake an MSDF atlas + glyph-metrics sidecar from a TTF.
230
+ *
231
+ * @param ttfPath path to the TrueType source.
232
+ * @param outDir output directory (created if missing).
233
+ * @param generatorFactory yields the MSDF generator (real: @zappar; tests: mock).
234
+ * @returns `Result`-style: throws a {@link FontError} on every failure mode
235
+ * (unsupported-font-format before the generator runs; bake-failed when the
236
+ * generator throws). The CLI layer maps the thrown FontError to a structured
237
+ * stderr line + exit code 1 -- never a silent exit 0 without artefacts
238
+ * (charter P3).
239
+ */
240
+ export async function bakeFont(
241
+ ttfPath: string,
242
+ outDir: string,
243
+ generatorFactory: () => Promise<MsdfGenerator>,
244
+ ): Promise<BakeResult> {
245
+ const ttf = await readFile(ttfPath);
246
+ const ttfBytes = new Uint8Array(ttf.buffer, ttf.byteOffset, ttf.byteLength);
247
+ if (!isSupportedFontMagic(ttfBytes)) {
248
+ throw new FontError({
249
+ code: 'unsupported-font-format',
250
+ expected: 'ttf',
251
+ hint: 'bake accepts TrueType (.ttf / 0x00010000 / "true") or OpenType-TTF ("OTTO") sources; WOFF / WOFF2 / other formats are not supported -- convert to TTF first',
252
+ detail: { path: ttfPath },
253
+ });
254
+ }
255
+
256
+ let atlas: BakeAtlas;
257
+ let generator: MsdfGenerator | undefined;
258
+ try {
259
+ generator = await generatorFactory();
260
+ atlas = await generator.generateAtlas(ttfBytes);
261
+ } catch (e) {
262
+ throw new FontError({
263
+ code: 'bake-failed',
264
+ expected: '@zappar/msdf-generator to produce an MSDF atlas',
265
+ hint: 'the MSDF generator threw -- a Web Worker + wasm host is required (a plain Node process reports "Worker is not defined"); run the bake in a Worker-capable environment',
266
+ detail: { cause: e instanceof Error ? e.message : String(e) },
267
+ });
268
+ } finally {
269
+ if (generator !== undefined) {
270
+ await generator.dispose().catch(() => undefined);
271
+ }
272
+ }
273
+
274
+ await mkdir(outDir, { recursive: true });
275
+ const base = basename(ttfPath, extname(ttfPath));
276
+ const atlasName = `${base}.atlas.png`;
277
+ const atlasPath = join(outDir, atlasName);
278
+ const sidecarPath = join(outDir, `${base}.meta.json`);
279
+ const png = encodePng(atlas.texture.width, atlas.texture.height, atlas.texture.data);
280
+ await writeFile(atlasPath, png);
281
+ const sidecar = atlasToSidecar(atlas, atlasName);
282
+ await writeFile(sidecarPath, `${JSON.stringify(sidecar, null, 2)}\n`);
283
+ return { atlasPath, sidecarPath };
284
+ }
285
+
286
+ /**
287
+ * Real @zappar/msdf-generator factory. Dynamically imported so a non-bake
288
+ * subcommand (or a test that injects a mock) never pays the wasm load cost,
289
+ * and so the package builds without the browser globals the generator needs.
290
+ */
291
+ /**
292
+ * Shape of @zappar/msdf-generator's `MSDFAtlas` (dist/index.d.ts) that the
293
+ * real factory adapts into the POD {@link BakeAtlas}. The package's `texture`
294
+ * is an ImageData-shaped `{ width, height, data }`; we read those fields
295
+ * structurally so the font package never needs the DOM `ImageData` type.
296
+ */
297
+ interface ZapparAtlas {
298
+ texture: { width: number; height: number; data: Uint8ClampedArray | Uint8Array };
299
+ glyphs: ReadonlyArray<{
300
+ unicode: number;
301
+ advance: number;
302
+ xoffset: number;
303
+ yoffset: number;
304
+ atlasPosition: [number, number];
305
+ atlasSize: [number, number];
306
+ }>;
307
+ metrics: { lineHeight: number; ascender: number };
308
+ textureSize: [number, number];
309
+ fieldRange: number;
310
+ }
311
+
312
+ export async function realGeneratorFactory(): Promise<MsdfGenerator> {
313
+ const mod = (await import('@zappar/msdf-generator')) as unknown as {
314
+ MSDF: new (config?: {
315
+ workerUrl?: URL;
316
+ wasmUrl?: string;
317
+ }) => {
318
+ initialize(): Promise<void>;
319
+ generateAtlas(opts: {
320
+ font: Uint8Array;
321
+ charset: string;
322
+ textureSize: [number, number];
323
+ fieldRange: number;
324
+ fontSize: number;
325
+ }): Promise<ZapparAtlas>;
326
+ dispose(): Promise<void>;
327
+ };
328
+ };
329
+
330
+ const wasmModuleUrl = import.meta.resolve('@zappar/msdf-generator/msdfgen_wasm.wasm');
331
+ const wasmBytes = await readFile(new URL(wasmModuleUrl));
332
+ const wasmUrl = `data:application/octet-stream;base64,${Buffer.from(wasmBytes).toString('base64')}`;
333
+ const nodeGlobal = globalThis as unknown as { Worker?: typeof NodeWorkerAdapter };
334
+ const previousWorker = nodeGlobal.Worker;
335
+ nodeGlobal.Worker = NodeWorkerAdapter;
336
+ let msdf: InstanceType<typeof mod.MSDF> | undefined;
337
+ try {
338
+ msdf = new mod.MSDF({
339
+ workerUrl: new URL('./node-msdf-worker.mjs', import.meta.url),
340
+ wasmUrl,
341
+ });
342
+ await msdf.initialize();
343
+ } finally {
344
+ if (previousWorker === undefined) {
345
+ delete nodeGlobal.Worker;
346
+ } else {
347
+ nodeGlobal.Worker = previousWorker;
348
+ }
349
+ }
350
+ if (msdf === undefined) {
351
+ throw new Error('the MSDF generator did not initialize');
352
+ }
353
+ return {
354
+ async generateAtlas(ttf: Uint8Array): Promise<BakeAtlas> {
355
+ const a = await msdf.generateAtlas({
356
+ font: ttf,
357
+ charset: DEFAULT_CHARSET,
358
+ textureSize: [DEFAULT_TEXTURE_SIZE, DEFAULT_TEXTURE_SIZE],
359
+ fieldRange: DEFAULT_FIELD_RANGE,
360
+ fontSize: DEFAULT_FONT_SIZE,
361
+ });
362
+ return {
363
+ texture: {
364
+ width: a.texture.width,
365
+ height: a.texture.height,
366
+ data: new Uint8Array(a.texture.data),
367
+ },
368
+ glyphs: a.glyphs.map((g) => ({
369
+ unicode: g.unicode,
370
+ advance: g.advance,
371
+ xoffset: g.xoffset,
372
+ yoffset: g.yoffset,
373
+ atlasPosition: [g.atlasPosition[0], g.atlasPosition[1]],
374
+ atlasSize: [g.atlasSize[0], g.atlasSize[1]],
375
+ })),
376
+ metrics: { lineHeight: a.metrics.lineHeight, ascender: a.metrics.ascender },
377
+ textureSize: [a.textureSize[0], a.textureSize[1]],
378
+ fieldRange: a.fieldRange,
379
+ };
380
+ },
381
+ async dispose(): Promise<void> {
382
+ await msdf.dispose();
383
+ },
384
+ };
385
+ }
386
+
387
+ function bakeHelpBody(): string {
388
+ return [
389
+ 'forgeax-engine-remote-font bake — bake MSDF font atlas from TTF',
390
+ '',
391
+ 'Usage:',
392
+ ' forgeax-engine-remote-font bake <ttf> <out>',
393
+ '',
394
+ 'Reads a TrueType font file and produces:',
395
+ ` <out>/<basename>.atlas.png — ${DEFAULT_TEXTURE_SIZE}x${DEFAULT_TEXTURE_SIZE} MSDF atlas`,
396
+ ' <out>/<basename>.meta.json — glyph metrics sidecar (importer: font)',
397
+ '',
398
+ ].join('\n');
399
+ }
400
+
401
+ function helpBody(): string {
402
+ return [
403
+ 'forgeax-engine-remote-font — MSDF font atlas baking',
404
+ '',
405
+ 'Usage:',
406
+ ' forgeax-engine-remote-font bake <ttf> <out>',
407
+ '',
408
+ ].join('\n');
409
+ }
410
+
411
+ export async function runCliFont(argv: string[]): Promise<number> {
412
+ const [sub, ...rest] = argv;
413
+ if (sub === undefined || sub === '--help' || sub === '-h') {
414
+ process.stdout.write(`${helpBody()}\n`);
415
+ return 0;
416
+ }
417
+ if (sub !== 'bake') {
418
+ process.stderr.write(`unknown subcommand: ${sub}\n`);
419
+ return 1;
420
+ }
421
+ return runBake(rest);
422
+ }
423
+
424
+ async function runBake(rest: string[]): Promise<number> {
425
+ if (rest[0] === '--help' || rest[0] === '-h') {
426
+ process.stdout.write(`${bakeHelpBody()}\n`);
427
+ return 0;
428
+ }
429
+ let positionals: string[];
430
+ try {
431
+ const parsed = parseArgs({ args: rest, allowPositionals: true, strict: true });
432
+ positionals = [...parsed.positionals];
433
+ } catch {
434
+ process.stderr.write('error parsing CLI args\n');
435
+ return 1;
436
+ }
437
+ const ttfPath = positionals[0];
438
+ const outDir = positionals[1];
439
+ if (ttfPath === undefined || outDir === undefined) {
440
+ process.stderr.write('usage: forgeax-engine-remote-font bake <ttf> <out>\n');
441
+ return 1;
442
+ }
443
+ try {
444
+ const result = await bakeFont(ttfPath, outDir, realGeneratorFactory);
445
+ process.stdout.write(`baked ${result.atlasPath} + ${result.sidecarPath}\n`);
446
+ return 0;
447
+ } catch (e) {
448
+ if (e instanceof FontError) {
449
+ process.stderr.write(
450
+ `${JSON.stringify({ code: e.code, expected: e.expected, hint: e.hint, detail: e.detail })}\n`,
451
+ );
452
+ return 1;
453
+ }
454
+ process.stderr.write(`bake failed: ${e instanceof Error ? e.message : String(e)}\n`);
455
+ return 1;
456
+ }
457
+ }
458
+
459
+ const isBinEntry = await (async (): Promise<boolean> => {
460
+ const argv1 = process.argv[1];
461
+ if (typeof argv1 !== 'string') return false;
462
+ const argv1Real = await realpath(argv1).catch(() => argv1);
463
+ const selfReal = await realpath(fileURLToPath(import.meta.url)).catch(() =>
464
+ fileURLToPath(import.meta.url),
465
+ );
466
+ return argv1Real === selfReal;
467
+ })();
468
+
469
+ if (isBinEntry) {
470
+ const exitCode = await runCliFont(process.argv.slice(2));
471
+ process.exit(exitCode);
472
+ }
@@ -0,0 +1,205 @@
1
+ // font-importer.ts - the build-time fontImporter (feat-20260603-asset-import-loader-injection M3 / w24).
2
+ //
3
+ // The `{ key: 'font', import }` Importer the @forgeax/engine-import runner
4
+ // dispatches a `*.meta.json` with `importer: 'font'` to. It absorbs the MSDF
5
+ // bake that previously lived only behind the `forgeax-engine-remote-font
6
+ // bake` CLI: read the `.ttf` source -> @zappar/msdf-generator atlas ->
7
+ // (a) one atlas `TextureAsset` ImportedAsset (the RGBA MSDF atlas, kind
8
+ // 'texture') under the declared `kind: 'texture'` sub-asset GUID, (b) one
9
+ // sampler ImportedAsset under the declared `kind: 'sampler'` sub-asset GUID,
10
+ // and (c) one font glyph-metrics ImportedAsset (kind 'font') under the
11
+ // declared `kind: 'font'` sub-asset GUID. The font carries the BMFont ->
12
+ // FontAsset glyph map + the common block + atlas/sampler GUID refs.
13
+ //
14
+ // Build-time-only boundary (AC-18 / requirements callout): @zappar/msdf-generator
15
+ // is a generator dependency that MUST stay out of the runtime bundle. The
16
+ // runtime today statically imports ZERO @forgeax/engine-font and ZERO @zappar
17
+ // symbols (research Finding 7); this importer keeps that invariant. fontImporter
18
+ // is a NODE-ONLY sub-export (`@forgeax/engine-font/font-importer`,
19
+ // `default: null` under browser conditions); the generator is dynamically
20
+ // imported (cli-font realGeneratorFactory) so even the build-time graph only
21
+ // pays the wasm load cost when a font is actually baked. The runtime fontLoader
22
+ // (M1 w6) reads an already-baked atlas DDC and has no bake dependency.
23
+ //
24
+ // GUID import-stable iron law: produced GUIDs come from `ctx.subAssets[]`. The
25
+ // font sidecar declares `texture`, `sampler`, and `font` sub-assets; this
26
+ // importer maps the bake output onto those declared GUIDs and stamps nothing
27
+ // of its own.
28
+ //
29
+ // `ctx.importSettings` may inject a test `generatorFactory` (an
30
+ // `() => Promise<MsdfGenerator>`) so unit tests drive the bake with a mock
31
+ // instead of the real wasm generator; production import calls fall through to
32
+ // the real @zappar factory.
33
+
34
+ import type {
35
+ FontAsset,
36
+ GlyphMetric,
37
+ ImportContext,
38
+ ImportedAsset,
39
+ Importer,
40
+ ImportResult,
41
+ SamplerAsset,
42
+ TextureAsset,
43
+ } from '@forgeax/engine-types';
44
+ import type { BakeAtlas, MsdfGenerator } from './cli-font.js';
45
+ import { realGeneratorFactory } from './cli-font.js';
46
+
47
+ /** Stable semantic identities for the three writable font outputs. */
48
+ export function sourceKeyForFontOutput(kind: string): string | undefined {
49
+ const normalizedKind = kind.trim();
50
+ return normalizedKind.length === 0 ? undefined : `font:${normalizedKind}`;
51
+ }
52
+
53
+ export function fontOutputSourceKeys(): readonly string[] {
54
+ return ['texture', 'sampler', 'font'].map((kind) => sourceKeyForFontOutput(kind) as string);
55
+ }
56
+
57
+ /** Map the @zappar atlas glyphs into the FontAsset glyph-metrics record. */
58
+ function atlasGlyphsToMetrics(atlas: BakeAtlas): Record<number, GlyphMetric> {
59
+ const glyphs: Record<number, GlyphMetric> = {};
60
+ for (const g of atlas.glyphs) {
61
+ glyphs[g.unicode] = {
62
+ advance: g.advance,
63
+ bearingX: g.xoffset,
64
+ bearingY: g.yoffset,
65
+ size: { w: g.atlasSize[0], h: g.atlasSize[1] },
66
+ region: {
67
+ x: g.atlasPosition[0],
68
+ y: g.atlasPosition[1],
69
+ w: g.atlasSize[0],
70
+ h: g.atlasSize[1],
71
+ },
72
+ };
73
+ }
74
+ return glyphs;
75
+ }
76
+
77
+ function makeAtlasTexture(atlas: BakeAtlas): TextureAsset {
78
+ return {
79
+ kind: 'texture',
80
+ width: atlas.texture.width,
81
+ height: atlas.texture.height,
82
+ // MSDF atlas is linear-space RGBA8 (signed-distance channels, never gamma).
83
+ format: 'rgba8unorm',
84
+ data: atlas.texture.data,
85
+ colorSpace: 'linear',
86
+ mipmap: false,
87
+ };
88
+ }
89
+
90
+ function makeFontCommon(atlas: BakeAtlas): FontAsset['common'] {
91
+ return {
92
+ lineHeight: atlas.metrics.lineHeight,
93
+ base: atlas.metrics.ascender,
94
+ distanceRange: atlas.fieldRange,
95
+ pxRange: atlas.fieldRange,
96
+ atlasWidth: atlas.textureSize[0],
97
+ atlasHeight: atlas.textureSize[1],
98
+ };
99
+ }
100
+
101
+ function makeAtlasSampler(): SamplerAsset {
102
+ return {
103
+ kind: 'sampler',
104
+ addressModeU: 'clamp-to-edge',
105
+ addressModeV: 'clamp-to-edge',
106
+ addressModeW: 'clamp-to-edge',
107
+ magFilter: 'linear',
108
+ minFilter: 'linear',
109
+ mipmapFilter: 'nearest',
110
+ };
111
+ }
112
+
113
+ async function importFont(ctx: ImportContext): Promise<ImportResult> {
114
+ const read = await ctx.readSource();
115
+ if (!read.ok) {
116
+ throw new Error(
117
+ `fontImporter: readSource failed: ${read.error instanceof Error ? read.error.message : String(read.error)}`,
118
+ );
119
+ }
120
+
121
+ const factory =
122
+ (ctx.importSettings.generatorFactory as (() => Promise<MsdfGenerator>) | undefined) ??
123
+ realGeneratorFactory;
124
+ const generator = await factory();
125
+ let atlas: BakeAtlas;
126
+ try {
127
+ atlas = await generator.generateAtlas(read.value);
128
+ } finally {
129
+ await generator.dispose().catch(() => undefined);
130
+ }
131
+
132
+ const atlasSub = ctx.subAssets.find((s) => s.kind === 'texture');
133
+ const samplerSub = ctx.subAssets.find((s) => s.kind === 'sampler');
134
+ const fontSub = ctx.subAssets.find((s) => s.kind === 'font');
135
+ const out: ImportedAsset[] = [];
136
+ if (atlasSub !== undefined) {
137
+ out.push({
138
+ guid: atlasSub.guid,
139
+ kind: 'texture',
140
+ payload: makeAtlasTexture(atlas),
141
+ refs: [],
142
+ artifacts: {
143
+ atlas: {
144
+ // Pack v2's runtime texture loader consumes non-Basis artifacts as
145
+ // raw pixels. Keep the baked RGBA8 MSDF atlas in that form here;
146
+ // the CLI still emits a PNG for standalone bake output.
147
+ mediaType: 'application/octet-stream',
148
+ bytes: atlas.texture.data,
149
+ },
150
+ },
151
+ });
152
+ }
153
+ if (samplerSub !== undefined) {
154
+ out.push({
155
+ guid: samplerSub.guid,
156
+ kind: 'sampler',
157
+ payload: makeAtlasSampler(),
158
+ refs: [],
159
+ artifacts: {},
160
+ });
161
+ }
162
+ if (fontSub !== undefined) {
163
+ // The runtime font loader reads atlasGuid / samplerGuid / glyphs / common
164
+ // off the DDC payload (asset-registry loadFontAsset); the produced payload
165
+ // mirrors that shape. atlas Handle / sampler Handle are runtime-resolved
166
+ // from the GUID refs, so the build-time payload carries the GUID strings
167
+ // (cast through FontAsset for the ImportedAsset.payload Asset slot, same
168
+ // build-time POD-vs-Handle bridge the gltfImporter scene arm uses).
169
+ const fontPayload = {
170
+ kind: 'font',
171
+ atlasGuid: atlasSub?.guid ?? '',
172
+ samplerGuid: samplerSub?.guid ?? '',
173
+ glyphs: atlasGlyphsToMetrics(atlas),
174
+ common: makeFontCommon(atlas),
175
+ } as unknown as FontAsset;
176
+ out.push({
177
+ guid: fontSub.guid,
178
+ kind: 'font',
179
+ payload: fontPayload,
180
+ refs: [
181
+ ...(atlasSub !== undefined ? [{ guid: atlasSub.guid }] : []),
182
+ ...(samplerSub !== undefined ? [{ guid: samplerSub.guid }] : []),
183
+ ],
184
+ artifacts: {},
185
+ });
186
+ }
187
+ return { ok: true, value: { assets: out, sourceDependencies: [] } };
188
+ }
189
+
190
+ /**
191
+ * The font {@link Importer}. Register it into an `ImporterRegistry` so the
192
+ * import runner dispatches `meta.importer === 'font'` sidecars here.
193
+ *
194
+ * @example
195
+ * ```ts
196
+ * import { ImporterRegistry } from '@forgeax/engine-import';
197
+ * import { fontImporter } from '@forgeax/engine-font/font-importer';
198
+ * const importers = new ImporterRegistry();
199
+ * importers.register(fontImporter);
200
+ * ```
201
+ */
202
+ export const fontImporter: Importer = {
203
+ key: 'font',
204
+ import: importFont,
205
+ };
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ // @forgeax/engine-font - runtime-safe font asset contribution.
2
+ //
3
+ // Build-time baking lives behind the explicit Node-only `./cli-font` and
4
+ // `./font-importer` subpaths. Keeping the main entry free of the CLI's
5
+ // `node:buffer`/WASM graph prevents App bundles from pulling the producer
6
+ // toolchain into the browser runtime.
7
+ export { fontContribution } from './runtime/font-decoder.js';