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.

fix(text): smooth magnified SDF glyphs — AA-seeded exact EDT + 4× supersampling

yhh6c80b0f74e1c
diff --git a/sdk/src/ui/text/glyph-rasterizer.ts b/sdk/src/ui/text/glyph-rasterizer.ts
index a2d1a93f4..2b3f6f61d 100644
--- a/sdk/src/ui/text/glyph-rasterizer.ts
+++ b/sdk/src/ui/text/glyph-rasterizer.ts
@@ -39,6 +39,34 @@ export function sdfToAtlasRgba(sdf: Uint8Array, width: number, height: number):
return out;
}
+/**
+ * Box-downsample a byte grid by an integer factor (averaging factor² texels
+ * per output texel). Used to fold a supersampled SDF back to the stored
+ * resolution: the field is computed at `factor²` the resolution — so edge
+ * positions carry sub-(stored-)texel accuracy — and averaging a linearly
+ * encoded field preserves that accuracy in the stored texels. Pure.
+ */
+export function downsampleBytes(src: Uint8Array, width: number, height: number, factor: number): Uint8Array {
+ if (factor <= 1) return src;
+ const w = Math.floor(width / factor);
+ const h = Math.floor(height / factor);
+ const out = new Uint8Array(w * h);
+ const area = factor * factor;
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ let sum = 0;
+ const sy0 = y * factor;
+ const sx0 = x * factor;
+ for (let sy = 0; sy < factor; sy++) {
+ const row = (sy0 + sy) * width + sx0;
+ for (let sx = 0; sx < factor; sx++) sum += src[row + sx];
+ }
+ out[y * w + x] = Math.round(sum / area);
+ }
+ }
+ return out;
+}
+
export interface CanvasGlyphRasterizerOptions {
/** Size glyphs are rasterized at (SDF is resolution-independent). Default 48. */
renderSize?: number;
@@ -51,6 +79,13 @@ export interface CanvasGlyphRasterizerOptions {
type Canvas2D = HTMLCanvasElement | OffscreenCanvas;
type Ctx2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+// SDF supersampling: rasterize + distance-transform at SS× the stored
+// resolution, then box-downsample the field. Coverage seeding recovers the
+// edge only to ~⅓ texel; computing at 4× and averaging down stores distances
+// at ~1/12-texel accuracy, so magnified glyphs stop showing the source grid
+// as edge wobble. One-time per glyph; atlas memory is unchanged.
+const SDF_SUPERSAMPLE = 4;
+
export class CanvasGlyphRasterizer implements GlyphRasterizer {
readonly renderSize: number;
private readonly module: ESEngineModule;
@@ -64,8 +99,10 @@ export class CanvasGlyphRasterizer implements GlyphRasterizer {
this.renderSize = opts.renderSize ?? 48;
this.pad = opts.padding ?? 6;
this.sdf = opts.sdf ?? true;
- // Scratch canvas sized for the largest glyph (em + ascenders + padding).
- const dim = Math.ceil(this.renderSize * 2 + this.pad * 2);
+ // Scratch canvas sized for the largest glyph (em + ascenders + padding),
+ // at supersampled resolution on the SDF path.
+ const ss = this.sdf ? SDF_SUPERSAMPLE : 1;
+ const dim = Math.ceil((this.renderSize * 2 + this.pad * 2) * ss);
this.canvas = platformCreateCanvas(dim, dim);
this.ctx = this.canvas.getContext('2d', { willReadFrequently: true }) as Ctx2D | null;
}
@@ -75,55 +112,63 @@ export class CanvasGlyphRasterizer implements GlyphRasterizer {
if (!ctx) return null;
const ch = String.fromCodePoint(codepoint);
+ // All drawing happens at ss× the requested size; metrics divide back
+ // down, gaining sub-px accuracy from the larger measurement.
+ const ss = this.sdf ? SDF_SUPERSAMPLE : 1;
const weight = (style & FONT_STYLE_BOLD) ? 'bold ' : '';
const italic = (style & FONT_STYLE_ITALIC) ? 'italic ' : '';
- ctx.font = `${italic}${weight}${pixelSize}px ${fontFamily}`;
+ ctx.font = `${italic}${weight}${pixelSize * ss}px ${fontFamily}`;
ctx.textBaseline = 'alphabetic';
ctx.textAlign = 'left';
const m = ctx.measureText(ch);
- const advance = m.width;
- const left = m.actualBoundingBoxLeft ?? 0;
- const right = m.actualBoundingBoxRight ?? advance;
- const ascent = m.actualBoundingBoxAscent ?? pixelSize * 0.8;
- const descent = m.actualBoundingBoxDescent ?? pixelSize * 0.2;
-
- const inkW = Math.ceil(left + right);
- const inkH = Math.ceil(ascent + descent);
+ const advanceSS = m.width;
+ const leftSS = m.actualBoundingBoxLeft ?? 0;
+ const rightSS = m.actualBoundingBoxRight ?? advanceSS;
+ const ascentSS = m.actualBoundingBoxAscent ?? pixelSize * ss * 0.8;
+ const descentSS = m.actualBoundingBoxDescent ?? pixelSize * ss * 0.2;
+
+ // Ink box in *stored* texels (rounded up so the ss grid tiles exactly).
+ const inkW = Math.ceil((leftSS + rightSS) / ss);
+ const inkH = Math.ceil((ascentSS + descentSS) / ss);
if (inkW <= 0 || inkH <= 0) {
// Whitespace: advance only, no atlas cell.
- return { pixels: new Uint8Array(0), width: 0, height: 0, advance, bearingX: 0, bearingY: 0 };
+ return { pixels: new Uint8Array(0), width: 0, height: 0, advance: advanceSS / ss, bearingX: 0, bearingY: 0 };
}
const pad = this.pad;
const w = inkW + pad * 2;
const h = inkH + pad * 2;
- if (w > this.canvas.width || h > this.canvas.height) return null; // glyph too large for scratch
+ const wSS = w * ss;
+ const hSS = h * ss;
+ if (wSS > this.canvas.width || hSS > this.canvas.height) return null; // glyph too large for scratch
- ctx.clearRect(0, 0, w, h);
+ ctx.clearRect(0, 0, wSS, hSS);
ctx.fillStyle = '#ffffff';
- ctx.fillText(ch, pad + left, pad + ascent);
+ ctx.fillText(ch, pad * ss + leftSS, pad * ss + ascentSS);
- const img = ctx.getImageData(0, 0, w, h);
- const alpha = extractAlpha(img.data, w, h);
- // SDF: convert to a distance field (scalable). Bitmap: keep the native-AA
+ const img = ctx.getImageData(0, 0, wSS, hSS);
+ const alpha = extractAlpha(img.data, wSS, hSS);
+ // SDF: distance-transform at the supersampled resolution (spread scales
+ // with ss, so the downsampled encoding matches spread = pad in stored
+ // texels exactly), then fold back down. Bitmap: keep the native-AA
// coverage as-is for a crisp 1:1 blit. Both pack as (RGB=255, A=coverage).
let coverage = alpha;
if (this.sdf) {
- const sdf = sdfFromAlpha(this.module, alpha, w, h, pad);
+ const sdf = sdfFromAlpha(this.module, alpha, wSS, hSS, pad * ss);
if (!sdf) return null;
- coverage = sdf;
+ coverage = downsampleBytes(sdf, wSS, hSS, ss);
}
return {
pixels: sdfToAtlasRgba(coverage, w, h),
width: w,
height: h,
- advance,
- // Drawn at pen x = pad + left (ink lands at tile x = pad), so the pen
- // origin maps back to tile x = 0 at -(left + pad).
- bearingX: -(left + pad),
- bearingY: ascent + pad,
+ advance: advanceSS / ss,
+ // Drawn at pen x = (pad + left) (ink lands at tile x = pad), so the
+ // pen origin maps back to tile x = 0 at -(left + pad).
+ bearingX: -(leftSS / ss + pad),
+ bearingY: ascentSS / ss + pad,
};
}
}
diff --git a/sdk/src/ui/text/sdf.ts b/sdk/src/ui/text/sdf.ts
index 2b36aaf77..bc898b7af 100644
--- a/sdk/src/ui/text/sdf.ts
+++ b/sdk/src/ui/text/sdf.ts
@@ -2,10 +2,11 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file ui/text/sdf.ts
- * @brief TS wrapper over the engine's C++ 8SSEDT signed-distance-field
- * generator. 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.
+ * @brief TS wrapper over the engine's C++ signed-distance-field generator
+ * (exact EDT with antialiased-coverage sub-texel seeding). 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';
diff --git a/sdk/tests/ui-sdf-generator.test.ts b/sdk/tests/ui-sdf-generator.test.ts
index fef729390..0a13d5533 100644
--- a/sdk/tests/ui-sdf-generator.test.ts
+++ b/sdk/tests/ui-sdf-generator.test.ts
@@ -1,10 +1,11 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @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).
+ * @file REARCH_GUI P1.1 — verifies the C++ signed-distance-field generator
+ * (text/SdfGenerator.cpp: exact EDT with antialiased-coverage sub-texel
+ * seeding) 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.
*/
@@ -17,7 +18,7 @@ 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)', () => {
+describe.skipIf(!HAS_WASM)('REARCH_GUI P1.1: SDF generator', () => {
let module: ESEngineModule;
let sdf: Uint8Array;
@@ -56,4 +57,32 @@ describe.skipIf(!HAS_WASM)('REARCH_GUI P1.1: SDF generator (8SSEDT)', () => {
expect(sdf[at(4, 8)]).toBeLessThan(sdf[at(6, 8)]);
expect(sdf[at(6, 8)]).toBeLessThanOrEqual(sdf[at(8, 8)]);
});
+
+ it('uses antialiased coverage for sub-texel edge placement (not a 0.5 threshold)', () => {
+ // Same square, but the leading edge column carries partial coverage.
+ // Under the old binarized 8SSEDT both variants collapsed to the same
+ // field (64 < 128 ⇒ outside, 192 ≥ 128 ⇒ inside, full step apart);
+ // with coverage seeding the encoded edge shifts fractionally.
+ const make = (edgeAlpha: number): Uint8Array => {
+ const alpha = new Uint8Array(W * H);
+ for (let y = 4; y <= 11; y++) {
+ alpha[at(4, y)] = edgeAlpha;
+ for (let x = 5; x <= 11; x++) alpha[at(x, y)] = 255;
+ }
+ return sdfFromAlpha(module, alpha, W, H, 4)!;
+ };
+
+ const quarter = make(64); // edge column 25% covered
+ const threeQ = make(192); // edge column 75% covered
+
+ // More coverage ⇒ that texel is deeper inside ⇒ larger SDF value.
+ expect(threeQ[at(4, 8)]).toBeGreaterThan(quarter[at(4, 8)]);
+ // Both must land strictly between "far outside" and "fully inside" —
+ // i.e. fractional, not snapped a full texel apart on the 0.5 cliff.
+ const step = 127 / 4; // one texel in encoded units at spread 4
+ expect(Math.abs(threeQ[at(4, 8)] - quarter[at(4, 8)])).toBeLessThan(step);
+ // And the fractional shift propagates to the neighbouring texels.
+ expect(threeQ[at(3, 8)]).toBeGreaterThanOrEqual(quarter[at(3, 8)]);
+ expect(threeQ[at(5, 8)]).toBeGreaterThanOrEqual(quarter[at(5, 8)]);
+ });
});
diff --git a/sdk/tests/ui-text-rasterizer.test.ts b/sdk/tests/ui-text-rasterizer.test.ts
index e924d798a..6f29b31b9 100644
--- a/sdk/tests/ui-text-rasterizer.test.ts
+++ b/sdk/tests/ui-text-rasterizer.test.ts
@@ -10,7 +10,7 @@
import { describe, it, expect, beforeAll } from 'vitest';
import type { ESEngineModule } from '../src/wasm';
import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
-import { extractAlpha, sdfToAtlasRgba } from '../src/ui/text/glyph-rasterizer';
+import { extractAlpha, sdfToAtlasRgba, downsampleBytes } from '../src/ui/text/glyph-rasterizer';
import { sdfFromAlpha } from '../src/ui/text/sdf';
describe('REARCH_GUI P1.3b: glyph rasterizer pure transforms', () => {
@@ -42,4 +42,31 @@ describe('REARCH_GUI P1.3b: glyph rasterizer pure transforms', () => {
expect(sdf[c]).toBeGreaterThan(128);
});
});
+
+ describe('downsampleBytes (SDF supersampling fold-down)', () => {
+ it('averages factor² blocks into one output texel', () => {
+ // 4×2 source, factor 2 → 2×1 output.
+ const src = new Uint8Array([
+ 10, 20, 100, 200,
+ 30, 40, 100, 200,
+ ]);
+ const out = downsampleBytes(src, 4, 2, 2);
+ expect(Array.from(out)).toEqual([25, 150]);
+ });
+
+ it('factor 1 is the identity', () => {
+ const src = new Uint8Array([1, 2, 3, 4]);
+ expect(downsampleBytes(src, 2, 2, 1)).toBe(src);
+ });
+
+ it('preserves a linear gradient (sub-texel edge positions survive)', () => {
+ // 8×4 source of a horizontal ramp (rows identical), factor 4 → 2×1.
+ const row = [0, 32, 64, 96, 128, 160, 192, 224];
+ const src = new Uint8Array([...row, ...row, ...row, ...row]);
+ const out = downsampleBytes(src, 8, 4, 4);
+ expect(out.length).toBe(2);
+ expect(out[0]).toBe(48); // avg(0,32,64,96)
+ expect(out[1]).toBe(176); // avg(128..224)
+ });
+ });
});
diff --git a/src/esengine/text/SdfGenerator.cpp b/src/esengine/text/SdfGenerator.cpp
index 1c3d48bdd..1ed3669f0 100644
--- a/src/esengine/text/SdfGenerator.cpp
+++ b/src/esengine/text/SdfGenerator.cpp
@@ -2,13 +2,22 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file text/SdfGenerator.cpp
- * @brief 8SSEDT (8-point signed sequential euclidean distance transform).
+ * @brief Exact signed distance field from an antialiased coverage bitmap.
*
- * 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.
+ * Felzenszwalb–Huttenlocher separable squared-distance transform with
+ * coverage-derived fractional seeds (the tiny-sdf / Gustavson lineage): a
+ * partially covered texel seeds the transform with its sub-texel distance to
+ * the true edge, (0.5 − α)², so the reconstructed field carries the edge
+ * position at sub-texel accuracy instead of quantizing it to the source grid.
+ * The previous 8SSEDT binarized coverage at 0.5, which baked the rasterizer's
+ * pixel staircase into the field — invisible at 1:1, but magnified glyphs
+ * showed it as wobbling, aliased edges.
+ *
+ * Two fields are computed — squared distance to the glyph interior and to the
+ * exterior — and their square roots subtracted for a signed distance that is
+ * positive inside, negative outside, ~0 on the edge. The 1D transform is
+ * exact and O(n); scratch buffers are reused across rows/columns, keeping the
+ * on-demand per-glyph cost allocation-light.
*/
#include "SdfGenerator.hpp"
@@ -19,71 +28,54 @@
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;
+constexpr f32 kInf = 1e20f;
- usize index(i32 x, i32 y) const {
- return static_cast<usize>(y) * static_cast<usize>(w) + static_cast<usize>(x);
+/**
+ * 1D squared-distance transform (Felzenszwalb & Huttenlocher): d[q] =
+ * min_p((q-p)² + f[p]). The additive seed cost f is what lets partially
+ * covered texels contribute fractional distances. v/z are the parabola
+ * lower-envelope scratch (v: site indices, z: envelope boundaries).
+ */
+void edt1d(f32* f, f32* d, i32* v, f32* z, i32 n) {
+ i32 k = 0;
+ v[0] = 0;
+ z[0] = -kInf;
+ z[1] = kInf;
+ for (i32 q = 1; q < n; ++q) {
+ f32 s;
+ while (true) {
+ const i32 p = v[k];
+ s = (f[q] + static_cast<f32>(q) * q - (f[p] + static_cast<f32>(p) * p))
+ / (2.0f * (q - p));
+ if (s > z[k]) break;
+ --k;
+ }
+ ++k;
+ v[k] = q;
+ z[k] = s;
+ z[k + 1] = kInf;
}
- Point get(i32 x, i32 y) const {
- if (x < 0 || y < 0 || x >= w || y >= h) return kEmpty;
- return cells[index(x, y)];
+ k = 0;
+ for (i32 q = 0; q < n; ++q) {
+ while (z[k + 1] < static_cast<f32>(q)) ++k;
+ const f32 dx = static_cast<f32>(q - v[k]);
+ d[q] = dx * dx + f[v[k]];
}
- 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);
- }
+/** 2D squared EDT in place: columns then rows, sharing the 1D scratch. */
+void edt2d(std::vector<f32>& grid, i32 w, i32 h,
+ std::vector<f32>& f, std::vector<f32>& d,
+ std::vector<i32>& v, std::vector<f32>& z) {
+ for (i32 x = 0; x < w; ++x) {
+ for (i32 y = 0; y < h; ++y) f[static_cast<usize>(y)] = grid[static_cast<usize>(y) * w + x];
+ edt1d(f.data(), d.data(), v.data(), z.data(), h);
+ for (i32 y = 0; y < h; ++y) grid[static_cast<usize>(y) * w + x] = d[static_cast<usize>(y)];
}
- 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);
- }
+ for (i32 y = 0; y < h; ++y) {
+ f32* row = grid.data() + static_cast<usize>(y) * w;
+ edt1d(row, d.data(), v.data(), z.data(), w);
+ std::copy_n(d.data(), w, row);
}
}
@@ -94,32 +86,44 @@ void sdfFromAlpha(const u8* alpha, u8* out, u32 width, u32 height, f32 spread) {
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;
+ const usize n = static_cast<usize>(w) * static_cast<usize>(h);
+ const i32 m = std::max(w, h);
+
+ // Squared distance to the glyph interior (outer) and exterior (inner).
+ // Coverage seeds: a fully covered texel is interior (outer seed 0); a
+ // fully empty one is exterior (inner seed 0); a partial texel sits within
+ // half a texel of the edge, on the side its coverage says.
+ std::vector<f32> outer(n);
+ std::vector<f32> inner(n);
+ for (usize i = 0; i < n; ++i) {
+ const f32 a = static_cast<f32>(alpha[i]) / 255.0f;
+ if (a >= 1.0f) {
+ outer[i] = 0.0f;
+ inner[i] = kInf;
+ } else if (a <= 0.0f) {
+ outer[i] = kInf;
+ inner[i] = 0.0f;
} else {
- inside.cells[i] = kEmpty;
- outside.cells[i] = kInside;
+ const f32 dOut = std::max(0.0f, 0.5f - a); // toward the interior side
+ const f32 dIn = std::max(0.0f, a - 0.5f); // toward the exterior side
+ outer[i] = dOut * dOut;
+ inner[i] = dIn * dIn;
}
}
- propagate(inside);
- propagate(outside);
+ std::vector<f32> f(static_cast<usize>(m));
+ std::vector<f32> d(static_cast<usize>(m));
+ std::vector<i32> v(static_cast<usize>(m));
+ std::vector<f32> z(static_cast<usize>(m) + 1);
+ edt2d(outer, w, h, f, d, v, z);
+ edt2d(inner, w, h, f, d, v, z);
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));
+ for (usize i = 0; i < n; ++i) {
+ // + inside, − outside, ~0 at the (sub-texel) edge.
+ const f32 signedDist = std::sqrt(inner[i]) - std::sqrt(outer[i]);
+ const i32 b = static_cast<i32>(std::lround(128.0f + signedDist * scale));
+ out[i] = static_cast<u8>(std::clamp(b, 0, 255));
}
}
diff --git a/src/esengine/text/SdfGenerator.hpp b/src/esengine/text/SdfGenerator.hpp
index afedc692d..5e55576cd 100644
--- a/src/esengine/text/SdfGenerator.hpp
+++ b/src/esengine/text/SdfGenerator.hpp
@@ -16,10 +16,15 @@
namespace esengine::text {
/**
- * @brief 8SSEDT signed distance field from an alpha coverage bitmap.
+ * @brief Signed distance field from an antialiased alpha coverage bitmap.
*
- * @param alpha width*height coverage bytes; a texel is "inside" the glyph
- * when its value is >= 128.
+ * Exact Felzenszwalb–Huttenlocher squared-distance transform with
+ * coverage-derived fractional seeds: partially covered texels place the edge
+ * at sub-texel accuracy, so magnified glyphs keep smooth edges instead of the
+ * source rasterization's pixel staircase.
+ *
+ * @param alpha width*height coverage bytes (antialiased coverage is used,
+ * not thresholded).
* @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