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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(text): dynamic SDF glyph-atlas foundations (REARCH_GUI P1.0/P1.1)
esengined21a226d9511
diff --git a/CMakeLists.txt b/CMakeLists.txtindex faca36d78..81ee1e02e 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -90,6 +90,7 @@ endif()list(APPEND ESENGINE_SOURCESsrc/esengine/text/BitmapFont.cpp+ src/esengine/text/SdfGenerator.cpp)@@ -181,6 +182,7 @@ endif()list(APPEND ESENGINE_HEADERSsrc/esengine/text/BitmapFont.hpp+ src/esengine/text/SdfGenerator.hpp)diff --git a/sdk/src/runtimeAssets.ts b/sdk/src/runtimeAssets.tsindex 7d766ee29..652f18198 100644--- a/sdk/src/runtimeAssets.ts+++ b/sdk/src/runtimeAssets.ts@@ -46,3 +46,27 @@ export function createTextureFromPixels(return rm.createTexture(result.width, result.height, ptr, result.pixels.length, 1, flipY);});}++/**+ * Upload pixels into a sub-rectangle of an existing texture. Lets the dynamic+ * glyph atlas (REARCH_GUI P1) pack glyphs individually instead of re-uploading+ * the whole atlas. `pixels` must match the texture's format (RGBA8) and the+ * rect must lie inside the texture (the engine bounds-checks and no-ops if not).+ */+export function updateTextureSubregion(+ module: ESEngineModule,+ handle: number,+ x: number,+ y: number,+ width: number,+ height: number,+ pixels: Uint8Array,+): void {+ if (width <= 0 || height <= 0 || pixels.length === 0) return;+ const rm = requireResourceManager();+ if (!rm.updateTextureSubregion) return;+ withMalloc(module, pixels.length, ptr => {+ module.HEAPU8.set(pixels, ptr);+ rm.updateTextureSubregion(handle, x, y, width, height, ptr, pixels.length);+ });+}diff --git a/sdk/src/ui/text/atlas-packer.ts b/sdk/src/ui/text/atlas-packer.tsnew file mode 100644index 000000000..66d599f64--- /dev/null+++ b/sdk/src/ui/text/atlas-packer.ts@@ -0,0 +1,68 @@+/**+ * @file ui/text/atlas-packer.ts+ * @brief Rectangle packer for the runtime dynamic glyph atlas (REARCH_GUI P1).+ *+ * Glyphs are packed into a fixed-size atlas page incrementally as they are first+ * seen. The packer is an interface so the heuristic is swappable; the default+ * ShelfPacker (row-based) is near-optimal here because glyphs of one font-size+ * share a height (especially CJK, whose em boxes are uniform), and it inserts in+ * O(rows) with no fragmentation bookkeeping.+ */++export interface PackPos {+ x: number;+ y: number;+}++export interface Packer {+ /** Page dimensions in texels. */+ readonly width: number;+ readonly height: number;+ /** Reserve a `w`×`h` cell; returns its top-left, or null if the page is full. */+ pack(w: number, h: number): PackPos | null;+ /** Drop all reservations (e.g. when rebuilding a page). */+ reset(): void;+}++/**+ * Row ("shelf") packer: fills the current row left→right, opening a new row once+ * a glyph doesn't fit horizontally. Row height grows to the tallest glyph placed+ * in it. Returns null when a glyph fits in neither the current nor a new row.+ */+export class ShelfPacker implements Packer {+ readonly width: number;+ readonly height: number;+ private shelfX = 0;+ private shelfY = 0;+ private shelfH = 0;++ constructor(width: number, height: number) {+ this.width = width;+ this.height = height;+ }++ pack(w: number, h: number): PackPos | null {+ if (w <= 0 || h <= 0 || w > this.width || h > this.height) return null;++ // Wrap to a new shelf if the glyph overflows the current row width.+ if (this.shelfX + w > this.width) {+ this.shelfY += this.shelfH;+ this.shelfX = 0;+ this.shelfH = 0;+ }++ // Out of vertical space on this page.+ if (this.shelfY + h > this.height) return null;++ const pos: PackPos = { x: this.shelfX, y: this.shelfY };+ this.shelfX += w;+ if (h > this.shelfH) this.shelfH = h;+ return pos;+ }++ reset(): void {+ this.shelfX = 0;+ this.shelfY = 0;+ this.shelfH = 0;+ }+}diff --git a/sdk/src/ui/text/sdf.ts b/sdk/src/ui/text/sdf.tsnew file mode 100644index 000000000..6655d1689--- /dev/null+++ b/sdk/src/ui/text/sdf.ts@@ -0,0 +1,39 @@+/**+ * @file ui/text/sdf.ts+ * @brief TS wrapper over the engine's C++ 8SSEDT signed-distance-field+ * generator (REARCH_GUI P1). The dynamic glyph atlas rasterizes a+ * glyph to alpha via Canvas2D, then calls this to get an SDF that+ * stays crisp at any scale and supports cheap outline/shadow.+ */+import type { ESEngineModule } from '../../wasm';+import { withScratch } from '../../wasmScratch';++/**+ * Convert a tight `width*height` alpha coverage buffer to a single-channel SDF.+ * 128 encodes the edge; >128 inside, <128 outside, with `spread` pixels mapped+ * to half the byte range. Returns a fresh `width*height` Uint8Array, or `null`+ * when the engine build lacks the binding (caller falls back to a plain-alpha+ * atlas — see REARCH_GUI §7.6).+ */+export function sdfFromAlpha(+ module: ESEngineModule,+ alpha: Uint8Array,+ width: number,+ height: number,+ spread: number,+): Uint8Array | null {+ if (!module.sdfFromAlpha) return null;+ const n = width * height;+ if (n === 0 || alpha.length < n) return null;++ const out = new Uint8Array(n);+ withScratch(module, alloc => {+ const alphaPtr = alloc(n);+ const outPtr = alloc(n);+ module.HEAPU8.set(alpha.subarray(0, n), alphaPtr);+ module.sdfFromAlpha!(alphaPtr, outPtr, width, height, spread);+ // Copy out before the scratch buffers are freed on return.+ out.set(module.HEAPU8.subarray(outPtr, outPtr + n));+ });+ return out;+}diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 8ab14b3ed..adc06ed8b 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -47,6 +47,7 @@ export interface CppResourceManager {releaseTexture(handle: number): void;releaseShader(handle: number): void;setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;+ updateTextureSubregion(handle: number, x: number, y: number, width: number, height: number, pixels: number, pixelsLen: number): void;registerTextureWithPath(handle: number, path: string): void;loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;@@ -117,6 +118,12 @@ export interface ESEngineModule {renderFrame(registry: CppRegistry, width: number, height: number): void;renderFrameWithMatrix(registry: CppRegistry, width: number, height: number, matrixPtr: number): void;getResourceManager(): CppResourceManager;+ /**+ * Convert a Canvas2D-rasterized alpha bitmap to a signed distance field for+ * the runtime glyph atlas (REARCH_GUI P1). `alphaPtr`/`outPtr` are HEAPU8+ * pointers to width*height byte buffers; the SDF is written into `outPtr`.+ */+ sdfFromAlpha?(alphaPtr: number, outPtr: number, width: number, height: number, spread: number): void;getSpineBounds?(registry: CppRegistry, entity: number): SpineBounds;renderer_submitSpineBatch?(diff --git a/sdk/tests/ui-atlas-packer.test.ts b/sdk/tests/ui-atlas-packer.test.tsnew file mode 100644index 000000000..91cf96aff--- /dev/null+++ b/sdk/tests/ui-atlas-packer.test.ts@@ -0,0 +1,67 @@+/**+ * @file REARCH_GUI P1.1 — ShelfPacker (glyph atlas rectangle packer). Pure+ * logic; verifies row advance, wrapping, no overlaps, page-full + oversize+ * rejection, and reset.+ */+import { describe, it, expect } from 'vitest';+import { ShelfPacker, type PackPos } from '../src/ui/text/atlas-packer';++function overlaps(a: PackPos & { w: number; h: number }, b: PackPos & { w: number; h: number }): boolean {+ return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;+}++describe('REARCH_GUI P1.1: ShelfPacker', () => {+ it('advances along a row then wraps to the next shelf', () => {+ const p = new ShelfPacker(100, 100);+ expect(p.pack(40, 20)).toEqual({ x: 0, y: 0 });+ expect(p.pack(40, 20)).toEqual({ x: 40, y: 0 });+ // 40+40+40 > 100 → wraps to a new shelf at y = tallest-of-row (20)+ expect(p.pack(40, 20)).toEqual({ x: 0, y: 20 });+ });++ it('grows shelf height to the tallest glyph in the row', () => {+ const p = new ShelfPacker(100, 100);+ p.pack(10, 30); // tall glyph sets row height 30+ p.pack(10, 10);+ // next row starts below the 30-tall shelf+ p.pack(95, 5); // forces wrap on the following pack+ const wrapped = p.pack(95, 5);+ expect(wrapped).toEqual({ x: 0, y: 35 }); // 30 (row0) + 5 (row1) = 35+ });++ it('packs many glyphs with no overlaps', () => {+ const p = new ShelfPacker(256, 256);+ const placed: Array<PackPos & { w: number; h: number }> = [];+ for (let i = 0; i < 200; i++) {+ const w = 8 + (i % 5) * 4;+ const h = 12;+ const pos = p.pack(w, h);+ if (!pos) break;+ placed.push({ ...pos, w, h });+ }+ expect(placed.length).toBeGreaterThan(50);+ for (let i = 0; i < placed.length; i++) {+ for (let j = i + 1; j < placed.length; j++) {+ expect(overlaps(placed[i], placed[j])).toBe(false);+ }+ expect(placed[i].x + placed[i].w).toBeLessThanOrEqual(256);+ expect(placed[i].y + placed[i].h).toBeLessThanOrEqual(256);+ }+ });++ it('returns null when the page is full and for oversize rects', () => {+ const p = new ShelfPacker(32, 32);+ expect(p.pack(40, 10)).toBeNull(); // wider than page+ expect(p.pack(10, 40)).toBeNull(); // taller than page+ p.pack(32, 32); // fills the page+ expect(p.pack(1, 1)).toBeNull(); // no room left+ });++ it('reset reclaims the whole page', () => {+ const p = new ShelfPacker(32, 32);+ p.pack(32, 32);+ expect(p.pack(1, 1)).toBeNull();+ p.reset();+ expect(p.pack(1, 1)).toEqual({ x: 0, y: 0 });+ });+});diff --git a/sdk/tests/ui-glyph-atlas-subregion.test.ts b/sdk/tests/ui-glyph-atlas-subregion.test.tsnew file mode 100644index 000000000..a4ab1e459--- /dev/null+++ b/sdk/tests/ui-glyph-atlas-subregion.test.ts@@ -0,0 +1,34 @@+/**+ * @file REARCH_GUI P1.0 — the texture sub-region upload primitive that the+ * dynamic glyph atlas (P1.1) builds on. The actual GL upload needs a GL+ * context (covered later by the headless render host); here we verify the+ * embind binding is registered on the C++ ResourceManager class, i.e. the+ * Texture::updateSubRegion + rm_updateTextureSubregion wiring compiled and+ * is reachable from TS.+ *+ * getResourceManager() is null headless (no GL context), so we assert on+ * the embind-bound class prototype rather than an instance.+ *+ * Requires the built WASM SDK (build/wasm/web). Skips if absent.+ */+import { describe, it, expect, beforeAll } from 'vitest';+import type { ESEngineModule } from '../src/wasm';+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';++describe.skipIf(!HAS_WASM)('REARCH_GUI P1.0: texture sub-region upload binding', () => {+ let proto: Record<string, unknown>;++ beforeAll(async () => {+ const module = await loadWasmModule();+ const RM = (module as unknown as { ResourceManager: { prototype: Record<string, unknown> } })+ .ResourceManager;+ proto = RM.prototype;+ });++ it('embind registers updateTextureSubregion on ResourceManager (alongside known methods)', () => {+ // Sanity: detection method is sound — a pre-existing binding is present.+ expect(typeof proto.setTextureMetadata).toBe('function');+ // The new P1.0 binding is registered.+ expect(typeof proto.updateTextureSubregion).toBe('function');+ });+});diff --git a/sdk/tests/ui-sdf-generator.test.ts b/sdk/tests/ui-sdf-generator.test.tsnew file mode 100644index 000000000..45927ed67--- /dev/null+++ b/sdk/tests/ui-sdf-generator.test.ts@@ -0,0 +1,57 @@+/**+ * @file REARCH_GUI P1.1 — verifies the C++ 8SSEDT signed-distance-field+ * generator (text/SdfGenerator.cpp) end-to-end through the `sdfFromAlpha`+ * embind binding + TS wrapper. Pure compute, so it is fully verifiable+ * headless (unlike Canvas2D glyph rasterization).+ *+ * Requires the built WASM SDK (build/wasm/web). Skips if absent.+ */+import { describe, it, expect, beforeAll } from 'vitest';+import type { ESEngineModule } from '../src/wasm';+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';+import { sdfFromAlpha } from '../src/ui/text/sdf';++const W = 16;+const H = 16;+const at = (x: number, y: number) => y * W + x;++describe.skipIf(!HAS_WASM)('REARCH_GUI P1.1: SDF generator (8SSEDT)', () => {+ let module: ESEngineModule;+ let sdf: Uint8Array;++ beforeAll(async () => {+ module = await loadWasmModule();+ // A centered 8x8 filled square (cols/rows 4..11 inside) in a 16x16 grid.+ const alpha = new Uint8Array(W * H);+ for (let y = 4; y <= 11; y++) {+ for (let x = 4; x <= 11; x++) alpha[at(x, y)] = 255;+ }+ const out = sdfFromAlpha(module, alpha, W, H, 4);+ expect(out).not.toBeNull();+ sdf = out!;+ });++ it('returns a width*height buffer', () => {+ expect(sdf.length).toBe(W * H);+ });++ it('encodes deep interior high and far exterior low', () => {+ expect(sdf[at(8, 8)]).toBeGreaterThan(200); // center: deep inside+ expect(sdf[at(0, 0)]).toBeLessThan(56); // corner: far outside+ });++ it('crosses the 128 edge between an inside and an adjacent outside texel', () => {+ const inside = sdf[at(4, 8)]; // first inside column+ const outside = sdf[at(3, 8)]; // adjacent outside column+ expect(inside).toBeGreaterThan(128);+ expect(outside).toBeLessThan(128);+ expect(inside).toBeGreaterThan(outside);+ });++ it('is monotonic inward along a row (closer to center ⇒ larger SDF)', () => {+ // x = 3 (outside) < 4 (edge) < 6 (deeper) < 8 (center)+ expect(sdf[at(3, 8)]).toBeLessThan(sdf[at(4, 8)]);+ expect(sdf[at(4, 8)]).toBeLessThan(sdf[at(6, 8)]);+ expect(sdf[at(6, 8)]).toBeLessThanOrEqual(sdf[at(8, 8)]);+ });+});diff --git a/src/esengine/bindings/ResourceManagerBindings.cpp b/src/esengine/bindings/ResourceManagerBindings.cppindex d9a9c5f10..ee58b8a87 100644--- a/src/esengine/bindings/ResourceManagerBindings.cpp+++ b/src/esengine/bindings/ResourceManagerBindings.cpp@@ -150,6 +150,17 @@ emscripten::val rm_measureBitmapText(resource::ResourceManager& rm, u32 fontHand}#endif+void rm_updateTextureSubregion(resource::ResourceManager& rm, u32 handleId,+ u32 x, u32 y, u32 width, u32 height,+ uintptr_t pixelsPtr, u32 pixelsLen) {+ auto* tex = rm.getTexture(resource::TextureHandle(handleId));+ if (!tex) return;+ // Sub-region pixels must already match the texture's format (RGBA8 atlas);+ // updateSubRegion bounds-checks the rect + buffer size internally.+ const u8* pixels = reinterpret_cast<const u8*>(pixelsPtr);+ tex->updateSubRegion(x, y, width, height, pixels, pixelsLen, /*flipY=*/false);+}+void rm_setTextureMetadata(resource::ResourceManager& rm, u32 handleId,f32 left, f32 right, f32 top, f32 bottom) {resource::TextureMetadata metadata;diff --git a/src/esengine/bindings/ResourceManagerBindings.hpp b/src/esengine/bindings/ResourceManagerBindings.hppindex dfe4ecc9b..0a4f99fe3 100644--- a/src/esengine/bindings/ResourceManagerBindings.hpp+++ b/src/esengine/bindings/ResourceManagerBindings.hpp@@ -38,6 +38,10 @@ u32 rm_getBitmapFontRefCount(resource::ResourceManager& rm, u32 handleId);emscripten::val rm_measureBitmapText(resource::ResourceManager& rm, u32 fontHandle,const std::string& text, f32 fontSize, f32 spacing);#endif+void rm_updateTextureSubregion(resource::ResourceManager& rm, u32 handleId,+ u32 x, u32 y, u32 width, u32 height,+ uintptr_t pixelsPtr, u32 pixelsLen);+void rm_setTextureMetadata(resource::ResourceManager& rm, u32 handleId,f32 left, f32 right, f32 top, f32 bottom);diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 697ed6ae8..54a67c4d6 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -36,6 +36,7 @@#include "../renderer/ImmediateDraw.hpp"#include "../renderer/CustomGeometry.hpp"#include "../resource/ResourceManager.hpp"+#include "../text/SdfGenerator.hpp"#include "../ecs/TransformSystem.hpp"#include "../core/World.hpp"#include "../ecs/components/Velocity.hpp"@@ -233,6 +234,15 @@ resource::ResourceManager* getResourceManager() {return g_resourceManager;}+// Runtime glyph atlas (REARCH_GUI P1): convert a Canvas2D-rasterized alpha+// bitmap to a signed distance field. Both buffers are caller-allocated in WASM+// linear memory (TS passes HEAPU8 pointers); `alpha` and `out` are width*height.+void web_sdfFromAlpha(uintptr_t alphaPtr, uintptr_t outPtr, u32 width, u32 height, f32 spread) {+ const u8* alpha = reinterpret_cast<const u8*>(alphaPtr);+ u8* out = reinterpret_cast<u8*>(outPtr);+ text::sdfFromAlpha(alpha, out, width, height, spread);+}+// =============================================================================// Pointer-based Component Access// =============================================================================@@ -333,6 +343,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("renderFrame", &esengine::renderFrame);emscripten::function("renderFrameWithMatrix", &esengine::renderFrameWithMatrix);emscripten::function("getResourceManager", &esengine::getResourceManager, emscripten::allow_raw_pointers());+ emscripten::function("sdfFromAlpha", &esengine::web_sdfFromAlpha);emscripten::class_<esengine::resource::ResourceManager>("ResourceManager").function("createTexture", &esengine::rm_createTexture)@@ -346,6 +357,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {.function("getTextureGLId", &esengine::rm_getTextureGLId).function("getTextureDimensions", &esengine::rm_getTextureDimensions).function("setTextureMetadata", &esengine::rm_setTextureMetadata)+ .function("updateTextureSubregion", &esengine::rm_updateTextureSubregion).function("registerTextureWithPath", &esengine::rm_registerTextureWithPath)#ifdef ES_ENABLE_BITMAP_TEXT.function("loadBitmapFont", &esengine::rm_loadBitmapFont)diff --git a/src/esengine/renderer/Texture.cpp b/src/esengine/renderer/Texture.cppindex ca86f39f8..49ec2f396 100644--- a/src/esengine/renderer/Texture.cpp+++ b/src/esengine/renderer/Texture.cpp@@ -188,4 +188,28 @@ void Texture::setDataRaw(const void* data, u32 sizeBytes, bool flipY) {if (flipY) device_->setUnpackFlipY(false);}+void Texture::updateSubRegion(u32 xoffset, u32 yoffset, u32 width, u32 height,+ const void* data, u32 sizeBytes, bool flipY) {+ // The sub-rect must lie fully inside the texture; otherwise texSubImage2D+ // writes outside the allocated GL texture (GL error / undefined).+ if (xoffset + width > width_ || yoffset + height > height_) {+ ES_LOG_ERROR("Texture::updateSubRegion: rect {}x{} at ({},{}) exceeds texture {}x{}; skipping",+ width, height, xoffset, yoffset, width_, height_);+ return;+ }+ // Always-on size guard (ES_ASSERT is stripped in release): texSubImage2D+ // reads width*height*bpp bytes from `data`; a smaller buffer would OOB-read+ // WASM linear memory.+ u32 expectedSize = width * height * bytesPerPixel(format_);+ if (sizeBytes < expectedSize) {+ ES_LOG_ERROR("Texture::updateSubRegion: data size {} < required {} for {}x{}; skipping to avoid OOB read",+ sizeBytes, expectedSize, width, height);+ return;+ }++ if (flipY) device_->setUnpackFlipY(true);+ device_->texSubImage2D(textureId_, xoffset, yoffset, width, height, toGfxPixelFormat(format_), data);+ if (flipY) device_->setUnpackFlipY(false);+}+} // namespace esenginediff --git a/src/esengine/renderer/Texture.hpp b/src/esengine/renderer/Texture.hppindex e0c18b513..6534da6bd 100644--- a/src/esengine/renderer/Texture.hpp+++ b/src/esengine/renderer/Texture.hpp@@ -196,6 +196,20 @@ public:*/void setData(const std::vector<u8>& pixels);+ /**+ * @brief Uploads pixel data to a sub-rectangle of the texture.+ *+ * Lets the dynamic glyph atlas (REARCH_GUI P1) pack glyphs one-by-one+ * without re-uploading the whole atlas. The sub-rect must lie fully inside+ * the texture and `data` must be tightly packed in this texture's format.+ *+ * @param xoffset,yoffset top-left of the sub-rect, in texels+ * @param width,height sub-rect size, in texels+ * @param data,sizeBytes pixel buffer matching the texture's format+ */+ void updateSubRegion(u32 xoffset, u32 yoffset, u32 width, u32 height,+ const void* data, u32 sizeBytes, bool flipY = false);+// =========================================================================// Properties// =========================================================================diff --git a/src/esengine/text/SdfGenerator.cpp b/src/esengine/text/SdfGenerator.cppnew file mode 100644index 000000000..06f020e65--- /dev/null+++ b/src/esengine/text/SdfGenerator.cpp@@ -0,0 +1,124 @@+/**+ * @file text/SdfGenerator.cpp+ * @brief 8SSEDT (8-point signed sequential euclidean distance transform).+ *+ * Two distance fields are propagated — one toward the nearest "inside" texel,+ * one toward the nearest "outside" texel — and subtracted to get a signed+ * distance that is positive inside the glyph, negative outside, ~0 at the edge.+ * The classic two-pass sequential sweep is approximate but fast and allocation-+ * light, which matters because glyphs are generated on-demand at runtime.+ */+#include "SdfGenerator.hpp"++#include <vector>+#include <cmath>+#include <algorithm>++namespace esengine::text {+namespace {++// Offset from a texel to its nearest opposite-class texel, in texels.+struct Point {+ i32 dx;+ i32 dy;+};++constexpr Point kInside{0, 0};+constexpr Point kEmpty{9999, 9999}; // distSq ~2e8, well within i32++inline i32 distSq(const Point& p) { return p.dx * p.dx + p.dy * p.dy; }++struct Grid {+ std::vector<Point> cells;+ i32 w;+ i32 h;++ usize index(i32 x, i32 y) const {+ return static_cast<usize>(y) * static_cast<usize>(w) + static_cast<usize>(x);+ }+ Point get(i32 x, i32 y) const {+ if (x < 0 || y < 0 || x >= w || y >= h) return kEmpty;+ return cells[index(x, y)];+ }+ void put(i32 x, i32 y, const Point& p) { cells[index(x, y)] = p; }+};++inline void compare(const Grid& g, Point& p, i32 x, i32 y, i32 ox, i32 oy) {+ Point other = g.get(x + ox, y + oy);+ other.dx += ox;+ other.dy += oy;+ if (distSq(other) < distSq(p)) p = other;+}++// Two-pass sequential sweep: each pass updates every texel from the four+// already-visited neighbours, so two passes cover all eight directions.+void propagate(Grid& g) {+ for (i32 y = 0; y < g.h; ++y) {+ for (i32 x = 0; x < g.w; ++x) {+ Point p = g.get(x, y);+ compare(g, p, x, y, -1, 0);+ compare(g, p, x, y, 0, -1);+ compare(g, p, x, y, -1, -1);+ compare(g, p, x, y, 1, -1);+ g.put(x, y, p);+ }+ for (i32 x = g.w - 1; x >= 0; --x) {+ Point p = g.get(x, y);+ compare(g, p, x, y, 1, 0);+ g.put(x, y, p);+ }+ }+ for (i32 y = g.h - 1; y >= 0; --y) {+ for (i32 x = g.w - 1; x >= 0; --x) {+ Point p = g.get(x, y);+ compare(g, p, x, y, 1, 0);+ compare(g, p, x, y, 0, 1);+ compare(g, p, x, y, -1, 1);+ compare(g, p, x, y, 1, 1);+ g.put(x, y, p);+ }+ for (i32 x = 0; x < g.w; ++x) {+ Point p = g.get(x, y);+ compare(g, p, x, y, -1, 0);+ g.put(x, y, p);+ }+ }+}++} // namespace++void sdfFromAlpha(const u8* alpha, u8* out, u32 width, u32 height, f32 spread) {+ if (!alpha || !out || width == 0 || height == 0) return;++ const i32 w = static_cast<i32>(width);+ const i32 h = static_cast<i32>(height);+ const i32 n = w * h;++ Grid inside{std::vector<Point>(static_cast<usize>(n)), w, h}; // toward nearest inside texel+ Grid outside{std::vector<Point>(static_cast<usize>(n)), w, h}; // toward nearest outside texel++ const usize count = static_cast<usize>(n);+ for (usize i = 0; i < count; ++i) {+ if (alpha[i] >= 128) {+ inside.cells[i] = kInside;+ outside.cells[i] = kEmpty;+ } else {+ inside.cells[i] = kEmpty;+ outside.cells[i] = kInside;+ }+ }++ propagate(inside);+ propagate(outside);++ const f32 scale = (spread > 0.0f) ? (127.0f / spread) : 127.0f;+ for (usize i = 0; i < count; ++i) {+ const f32 distToInside = std::sqrt(static_cast<f32>(distSq(inside.cells[i]))); // 0 inside, grows outward+ const f32 distToOutside = std::sqrt(static_cast<f32>(distSq(outside.cells[i]))); // 0 outside, grows inward+ const f32 signedDist = distToOutside - distToInside; // + inside, - outside, ~0 at edge+ const i32 v = static_cast<i32>(std::lround(128.0f + signedDist * scale));+ out[i] = static_cast<u8>(std::clamp(v, 0, 255));+ }+}++} // namespace esengine::textdiff --git a/src/esengine/text/SdfGenerator.hpp b/src/esengine/text/SdfGenerator.hppnew file mode 100644index 000000000..7588accb9--- /dev/null+++ b/src/esengine/text/SdfGenerator.hpp@@ -0,0 +1,30 @@+/**+ * @file text/SdfGenerator.hpp+ * @brief Signed distance field generation from an 8-bit alpha coverage bitmap.+ *+ * Used by the runtime dynamic glyph atlas (REARCH_GUI P1): glyphs are rasterized+ * to alpha via Canvas2D on the TS side, then converted to an SDF here so they+ * stay crisp at any scale and support cheap outline/shadow in the shader. Pure+ * (no GL / no emscripten) so it is unit-testable and portable.+ */+#pragma once++#include "../core/Types.hpp"++namespace esengine::text {++/**+ * @brief 8SSEDT signed distance field from an alpha coverage bitmap.+ *+ * @param alpha width*height coverage bytes; a texel is "inside" the glyph+ * when its value is >= 128.+ * @param out width*height output bytes. 128 encodes the edge; values above+ * 128 are inside, below are outside. The mapping is linear with+ * `spread` pixels spanning half the [0,255] range, matching what+ * the SDF text shader expects.+ * @param spread distance in pixels mapped to half the byte range (the SDF+ * "range"/padding). Larger = softer falloff / more outline room.+ */+void sdfFromAlpha(const u8* alpha, u8* out, u32 width, u32 height, f32 spread);++} // namespace esengine::text