Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(text): runtime glyph atlas manager — cache + multi-page packing (REARCH_GUI P1.1c)

esenginea540d08ed3f2
diff --git a/sdk/src/ui/text/glyph-atlas.ts b/sdk/src/ui/text/glyph-atlas.ts
new file mode 100644
index 000000000..bcf161244
--- /dev/null
+++ b/sdk/src/ui/text/glyph-atlas.ts
@@ -0,0 +1,176 @@
+/**
+ * @file ui/text/glyph-atlas.ts
+ * @brief Runtime dynamic glyph atlas (REARCH_GUI P1) — the cache + multi-page
+ * packer that turns "I need glyph X" into "here is its atlas rectangle".
+ *
+ * Design: the atlas is SDF-agnostic. It deals only in upload-ready bitmaps; the
+ * injected {@link GlyphRasterizer} owns rasterization AND any SDF conversion, and
+ * the injected {@link AtlasPageStore} owns the GPU texture pages. Both are
+ * interfaces so the orchestration is unit-testable (mock both) and the real
+ * Canvas2D + engine implementations stay thin and swappable (e.g. a plain-alpha
+ * rasterizer fallback per REARCH_GUI §7.6).
+ *
+ * Because SDF is resolution-independent, each glyph is rasterized ONCE at a fixed
+ * `sdfRenderSize`; the display size scales the quad at draw time. The cache key
+ * therefore carries no display size — only (font, codepoint, style).
+ */
+import { ShelfPacker, type Packer } from './atlas-packer';
+
+/** A glyph rendered to an upload-ready bitmap plus its layout metrics (in render-size px). */
+export interface RasterGlyph {
+ /** Upload-ready pixels matching the atlas page format (RGBA8), row-major. Empty for whitespace. */
+ pixels: Uint8Array;
+ /** Bitmap size in texels (0 for whitespace — no atlas cell is allocated). */
+ width: number;
+ height: number;
+ /** Pen advance after this glyph. */
+ advance: number;
+ /** Offset from the pen origin to the bitmap's left / top (top-left origin). */
+ bearingX: number;
+ bearingY: number;
+}
+
+export interface GlyphRasterizer {
+ /** The size glyphs are rasterized at; metrics are in these units. */
+ readonly renderSize: number;
+ /**
+ * Render one glyph to an upload-ready bitmap + metrics, or null if the glyph
+ * cannot be produced (unknown codepoint / no font).
+ */
+ rasterize(codepoint: number, fontFamily: string, style: number): RasterGlyph | null;
+}
+
+export interface AtlasPageStore {
+ /** Allocate a blank `size`×`size` page; return an opaque page id (e.g. a texture handle). */
+ createPage(size: number): number;
+ /** Upload `pixels` into the [x,y,w,h] sub-rect of page `pageId`. */
+ uploadSubRegion(pageId: number, x: number, y: number, w: number, h: number, pixels: Uint8Array): void;
+}
+
+/** A cached glyph's atlas location (normalized UVs) + metrics. */
+export interface GlyphEntry {
+ pageId: number;
+ u0: number;
+ v0: number;
+ u1: number;
+ v1: number;
+ width: number;
+ height: number;
+ advance: number;
+ bearingX: number;
+ bearingY: number;
+}
+
+export interface GlyphAtlasOptions {
+ /** Page texture size in texels (square). Default 1024. */
+ pageSize?: number;
+ /** Gutter between glyphs to prevent bilinear bleed. Default 1. */
+ padding?: number;
+}
+
+const STYLE_COUNT_HINT = 4; // plain / bold / italic / bold-italic — for key spread only
+
+/**
+ * Caches glyphs into one or more atlas pages, rasterizing on first use.
+ */
+export class GlyphAtlas {
+ private readonly pageSize: number;
+ private readonly padding: number;
+ private readonly cache = new Map<string, GlyphEntry | null>();
+ private readonly pages: number[] = [];
+ private readonly packers: Packer[] = [];
+
+ constructor(
+ private readonly rasterizer: GlyphRasterizer,
+ private readonly store: AtlasPageStore,
+ opts: GlyphAtlasOptions = {},
+ ) {
+ this.pageSize = opts.pageSize ?? 1024;
+ this.padding = opts.padding ?? 1;
+ }
+
+ /** Number of atlas pages currently allocated. */
+ get pageCount(): number { return this.pages.length; }
+
+ private key(codepoint: number, fontFamily: string, style: number): string {
+ return `${fontFamily}|${codepoint}|${style % STYLE_COUNT_HINT}`;
+ }
+
+ /**
+ * Get a glyph's atlas entry, rasterizing + packing it on first use. Returns
+ * null for glyphs the rasterizer cannot produce (caller skips / uses fallback).
+ * The result is cached (including the null), so a miss is paid once.
+ */
+ getGlyph(codepoint: number, fontFamily: string, style = 0): GlyphEntry | null {
+ const k = this.key(codepoint, fontFamily, style);
+ const hit = this.cache.get(k);
+ if (hit !== undefined) return hit;
+
+ const raster = this.rasterizer.rasterize(codepoint, fontFamily, style);
+ if (!raster) {
+ this.cache.set(k, null);
+ return null;
+ }
+
+ // Whitespace (no bitmap): cache an advance-only entry, no atlas cell.
+ if (raster.width <= 0 || raster.height <= 0) {
+ const entry: GlyphEntry = {
+ pageId: this.pages.length > 0 ? this.pages[0] : -1,
+ u0: 0, v0: 0, u1: 0, v1: 0,
+ width: 0, height: 0,
+ advance: raster.advance, bearingX: raster.bearingX, bearingY: raster.bearingY,
+ };
+ this.cache.set(k, entry);
+ return entry;
+ }
+
+ const placed = this.place(raster.width, raster.height);
+ if (!placed) {
+ // Glyph larger than a whole page — cannot atlas it. Cache null.
+ this.cache.set(k, null);
+ return null;
+ }
+
+ this.store.uploadSubRegion(placed.pageId, placed.x, placed.y, raster.width, raster.height, raster.pixels);
+
+ const inv = 1 / this.pageSize;
+ const entry: GlyphEntry = {
+ pageId: placed.pageId,
+ u0: placed.x * inv,
+ v0: placed.y * inv,
+ u1: (placed.x + raster.width) * inv,
+ v1: (placed.y + raster.height) * inv,
+ width: raster.width,
+ height: raster.height,
+ advance: raster.advance,
+ bearingX: raster.bearingX,
+ bearingY: raster.bearingY,
+ };
+ this.cache.set(k, entry);
+ return entry;
+ }
+
+ /** Reserve a w×h cell across pages, opening a new page when the last is full. */
+ private place(w: number, h: number): { pageId: number; x: number; y: number } | null {
+ const cellW = w + this.padding;
+ const cellH = h + this.padding;
+ if (cellW > this.pageSize || cellH > this.pageSize) return null;
+
+ if (this.packers.length === 0) this.addPage();
+
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const pi = this.packers.length - 1;
+ const pos = this.packers[pi].pack(cellW, cellH);
+ if (pos) return { pageId: this.pages[pi], x: pos.x, y: pos.y };
+ // Current page full → open a fresh one and retry once.
+ this.addPage();
+ }
+ return null;
+ }
+
+ private addPage(): void {
+ const pageId = this.store.createPage(this.pageSize);
+ this.pages.push(pageId);
+ this.packers.push(new ShelfPacker(this.pageSize, this.pageSize));
+ }
+}
diff --git a/sdk/tests/ui-glyph-atlas.test.ts b/sdk/tests/ui-glyph-atlas.test.ts
new file mode 100644
index 000000000..d794d3bfa
--- /dev/null
+++ b/sdk/tests/ui-glyph-atlas.test.ts
@@ -0,0 +1,123 @@
+/**
+ * @file REARCH_GUI P1.1c — GlyphAtlas orchestration. The Canvas2D rasterizer
+ * isn't headless-renderable, so the atlas takes injectable GlyphRasterizer
+ * + AtlasPageStore; here we drive it with mocks to verify cache, packing,
+ * multi-page overflow, whitespace, and unknown-glyph handling.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import {
+ GlyphAtlas,
+ type GlyphRasterizer,
+ type AtlasPageStore,
+ type RasterGlyph,
+} from '../src/ui/text/glyph-atlas';
+
+const UNKNOWN = 0xffff;
+const SPACE = 32;
+const HUGE = 0xaaaa;
+
+function makeRasterizer() {
+ const rasterize = vi.fn((cp: number): RasterGlyph | null => {
+ if (cp === UNKNOWN) return null;
+ if (cp === SPACE) return { pixels: new Uint8Array(0), width: 0, height: 0, advance: 12, bearingX: 0, bearingY: 0 };
+ if (cp === HUGE) return { pixels: new Uint8Array(100 * 100 * 4), width: 100, height: 100, advance: 100, bearingX: 0, bearingY: 0 };
+ const w = 10, h = 12;
+ return { pixels: new Uint8Array(w * h * 4).fill(200), width: w, height: h, advance: 11, bearingX: 1, bearingY: 10 };
+ });
+ return { renderSize: 48, rasterize } as GlyphRasterizer & { rasterize: typeof rasterize };
+}
+
+function makeStore() {
+ let next = 100;
+ const uploads: Array<{ pageId: number; x: number; y: number; w: number; h: number; len: number }> = [];
+ const createPage = vi.fn((_size: number) => next++);
+ const uploadSubRegion = vi.fn((pageId: number, x: number, y: number, w: number, h: number, pixels: Uint8Array) => {
+ uploads.push({ pageId, x, y, w, h, len: pixels.length });
+ });
+ return { createPage, uploadSubRegion, uploads } as AtlasPageStore & {
+ createPage: typeof createPage; uploadSubRegion: typeof uploadSubRegion;
+ uploads: typeof uploads;
+ };
+}
+
+describe('REARCH_GUI P1.1c: GlyphAtlas', () => {
+ it('rasterizes, packs and uploads on first use; returns UVs + metrics', () => {
+ const r = makeRasterizer();
+ const s = makeStore();
+ const atlas = new GlyphAtlas(r, s, { pageSize: 64, padding: 1 });
+
+ const g = atlas.getGlyph(65, 'Arial');
+ expect(g).not.toBeNull();
+ expect(g!.pageId).toBe(100);
+ expect(g!.width).toBe(10);
+ expect(g!.height).toBe(12);
+ expect(g!.advance).toBe(11);
+ expect(g!.bearingY).toBe(10);
+ expect(g!.u0).toBe(0);
+ expect(g!.u1).toBeCloseTo(10 / 64);
+ expect(g!.v1).toBeCloseTo(12 / 64);
+ expect(s.createPage).toHaveBeenCalledTimes(1);
+ expect(s.uploads).toEqual([{ pageId: 100, x: 0, y: 0, w: 10, h: 12, len: 480 }]);
+ });
+
+ it('caches: a second request neither rasterizes nor uploads again', () => {
+ const r = makeRasterizer();
+ const s = makeStore();
+ const atlas = new GlyphAtlas(r, s, { pageSize: 64 });
+
+ const a = atlas.getGlyph(65, 'Arial');
+ const b = atlas.getGlyph(65, 'Arial');
+ expect(b).toBe(a);
+ expect(r.rasterize).toHaveBeenCalledTimes(1);
+ expect(s.uploadSubRegion).toHaveBeenCalledTimes(1);
+ });
+
+ it('keys by font + style so distinct fonts/styles get distinct cells', () => {
+ const r = makeRasterizer();
+ const s = makeStore();
+ const atlas = new GlyphAtlas(r, s, { pageSize: 64 });
+ atlas.getGlyph(65, 'Arial', 0);
+ atlas.getGlyph(65, 'Arial', 1); // bold
+ atlas.getGlyph(65, 'Times', 0);
+ expect(r.rasterize).toHaveBeenCalledTimes(3);
+ });
+
+ it('whitespace gets an advance-only entry with no upload', () => {
+ const r = makeRasterizer();
+ const s = makeStore();
+ const atlas = new GlyphAtlas(r, s, { pageSize: 64 });
+ atlas.getGlyph(65, 'Arial'); // allocate a page first
+ s.uploadSubRegion.mockClear();
+ const sp = atlas.getGlyph(SPACE, 'Arial');
+ expect(sp).not.toBeNull();
+ expect(sp!.width).toBe(0);
+ expect(sp!.advance).toBe(12);
+ expect(s.uploadSubRegion).not.toHaveBeenCalled();
+ });
+
+ it('caches unknown glyphs as null (rasterized once)', () => {
+ const r = makeRasterizer();
+ const s = makeStore();
+ const atlas = new GlyphAtlas(r, s, { pageSize: 64 });
+ expect(atlas.getGlyph(UNKNOWN, 'Arial')).toBeNull();
+ expect(atlas.getGlyph(UNKNOWN, 'Arial')).toBeNull();
+ expect(r.rasterize).toHaveBeenCalledTimes(1);
+ });
+
+ it('opens a new page when the current one fills', () => {
+ const r = makeRasterizer();
+ const s = makeStore();
+ const atlas = new GlyphAtlas(r, s, { pageSize: 64, padding: 1 });
+ // 64/11 = 5 per row, 64/13 = 4 rows ⇒ ~20 glyphs/page; 25 forces a 2nd page.
+ for (let i = 0; i < 25; i++) atlas.getGlyph(0x100 + i, 'Arial');
+ expect(atlas.pageCount).toBe(2);
+ expect(s.createPage).toHaveBeenCalledTimes(2);
+ });
+
+ it('returns null for a glyph larger than a whole page', () => {
+ const r = makeRasterizer();
+ const s = makeStore();
+ const atlas = new GlyphAtlas(r, s, { pageSize: 64 });
+ expect(atlas.getGlyph(HUGE, 'Arial')).toBeNull();
+ });
+});