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): a bitmap glyph's outline is the glyph grown, not eight stamped copies of it

yhh61f26ef3bc0b
diff --git a/docs/astro/src/content/docs/ui/text.mdx b/docs/astro/src/content/docs/ui/text.mdx
index 6a6ab2a0e..34e4b78e6 100644
--- a/docs/astro/src/content/docs/ui/text.mdx
+++ b/docs/astro/src/content/docs/ui/text.mdx
@@ -88,7 +88,7 @@ Defaults below are the component defaults (what the inspector shows).
| `lineHeight` | number | `1.2` | Line spacing as a **ratio of `fontSize`** (baseline-to-baseline = `lineHeight × fontSize`). |
| `bold` / `italic` | boolean | `false` | Base font style (rich-text `<b>`/`<i>` layer on top). |
| `strokeColor` | Color | `{0,0,0,1}` | Outline color. |
-| `strokeWidth` | number | `0` | Outline width in px; `0` disables. On an SDF atlas the glyph's own edge is pushed outward, so it stays the glyph's shape at any width (see [below](#outlines)). |
+| `strokeWidth` | number | `0` | Outline width in px; `0` disables. An SDF glyph's own edge is pushed outward and a bitmap glyph is grown, so it stays the glyph's shape at any width (see [below](#outlines)). |
| `shadowColor` | Color | `{0,0,0,1}` | Drop-shadow color. The shadow and the outline fade with the text's own `color` alpha, so a label faded out leaves neither behind. |
| `shadowOffsetX` / `shadowOffsetY` | number | `0` | Shadow offset in px. |
| `shadowBlur` | number | `0` | Softens the shadow, in px. `0` is a hard offset copy; above that the shadow spreads into a ring, so it reads as a soft mass under the glyphs rather than a second stamp of them. A blur with no offset is a halo. |
@@ -143,10 +143,14 @@ through the atlas's spread and render size, so it means the same thing at every
`fontSize` and every camera zoom, and asking for more than the atlas can dilate
degrades to the widest real outline instead of flooding the glyph's cell.
-**Bitmap** glyphs have no distance to push, so they keep the old eight-direction
-stamp of the glyph. That reads as an outline while it is a hairline and merges
-into a blob past a few pixels — force [`renderMode: Sdf`](#the-two-glyph-pipelines)
-for anything thicker than about a pixel.
+**Bitmap** glyphs have no distance to push, so each one is grown instead: the
+atlas places the glyph again, dilated by the width (in the texels it was
+rasterized at), and the outline draws those grown glyphs once behind the fill.
+The ring is solid and antialiased at any width, and a grown glyph is cached per
+size and width like the glyph itself. (Up to 0.97 this path stamped the glyph in
+eight directions, which turned anything wider than a hairline into eight ghost
+copies of the label.) A bitmap font without a baked outline keeps that stamp, the
+one glyph source the atlas cannot grow.
A `shadowBlur` above 0 stamps the shadow at the centre plus a ring of eight
around it, with each tap's alpha inverted out of the compositing equation so the
diff --git a/docs/astro/src/content/docs/zh-cn/ui/text.mdx b/docs/astro/src/content/docs/zh-cn/ui/text.mdx
index 5d503e65d..3c373d742 100644
--- a/docs/astro/src/content/docs/zh-cn/ui/text.mdx
+++ b/docs/astro/src/content/docs/zh-cn/ui/text.mdx
@@ -82,7 +82,7 @@ const pulseBanner = defineSystem([Query(Mut(Transform), Text), Res(Time)], (q, t
| `lineHeight` | number | `1.2` | 行距,为 **`fontSize` 的比率**(基线间距 = `lineHeight × fontSize`)。 |
| `bold` / `italic` | boolean | `false` | 基础字体样式(富文本 `<b>`/`<i>` 在其上叠加)。 |
| `strokeColor` | Color | `{0,0,0,1}` | 描边颜色。 |
-| `strokeWidth` | number | `0` | 描边宽度(px);`0` 关闭。SDF 图集上是把字形自己的边缘向外推,所以任意宽度下描出来的仍是这个字的形状([见下文](#描边))。 |
+| `strokeWidth` | number | `0` | 描边宽度(px);`0` 关闭。SDF 字形把自己的边缘向外推,位图字形则把字形长大,所以任意宽度下描出来的仍是这个字的形状([见下文](#描边))。 |
| `shadowColor` | Color | `{0,0,0,1}` | 投影颜色。投影和描边会随文字自身 `color` 的 alpha 一起淡出,文字淡到透明时不会留下投影。 |
| `shadowOffsetX` / `shadowOffsetY` | number | `0` | 投影偏移(px)。 |
| `shadowBlur` | number | `0` | 投影柔度(px)。`0` 是硬边偏移副本;大于 0 时投影摊成一圈,读起来是字下面一团柔和的暗,而不是又盖了一遍字。只给柔度不给偏移就是一圈光晕。 |
@@ -126,9 +126,11 @@ const pulseBanner = defineSystem([Query(Mut(Transform), Text), Res(Time)], (q, t
经图集的 spread 与渲染尺寸换算,因此在任何 `fontSize`、任何相机缩放下含义一致;
要得比图集能膨胀的更宽时,退化为最宽的那圈真实描边,而不是糊满字形的格子。
-**Bitmap** 字形没有距离可推,仍走旧的 8 方向字形拓印。那在发丝宽时读起来像描边,
-超过几个像素就糊成一团——要更粗的描边,请强制
-[`renderMode: Sdf`](#双字形管线)。
+**Bitmap** 字形没有距离可推,所以改为把字形本身长大:图集按描边宽度(换算到它光栅化时的
+纹素)把字形膨胀后另放一格,描边用这些长大的字形在填充之后画一遍。任何宽度下都是一圈实心、
+带抗锯齿的边,长大的字形和字形本身一样按尺寸和宽度缓存。(0.97 及之前这条路径是把字形朝
+8 个方向各盖一次,比发丝宽一点就成了标签的 8 个重影。)没有烘焙描边的位图字体仍走那种拓印——
+那是图集唯一长不大的字形来源。
`shadowBlur` 大于 0 时,投影在中心加外围一圈共九次拓印,每次的 alpha 从合成方程里
反解出来,使叠起来正好是你要的 alpha。与描边不同,它是把边缘**变柔**而不是挪动,
diff --git a/sdk/src/ui/text/glyph-atlas.ts b/sdk/src/ui/text/glyph-atlas.ts
index 77927fc0a..6d60a81f1 100644
--- a/sdk/src/ui/text/glyph-atlas.ts
+++ b/sdk/src/ui/text/glyph-atlas.ts
@@ -102,16 +102,93 @@ interface GlyphPlacement {
fontFamily: string;
style: number;
pixelSize: number;
+ /** The outline radius this cell was grown by, in rasterized px; 0 for the glyph itself. */
+ outline: number;
x: number;
y: number;
width: number;
height: number;
}
+/** Which glyph an entry is, for an atlas that has to produce a variant of it. */
+interface GlyphIdentity {
+ codepoint: number;
+ fontFamily: string;
+ style: number;
+ pixelSize: number;
+}
+
+/**
+ * Grow a coverage glyph by @p radius texels: every texel takes the strongest
+ * coverage within the radius, faded over its last texel so the ring's edge is
+ * antialiased like the glyph's own. The tile gains `margin` texels on every side
+ * for the ring to grow into. Pure.
+ *
+ * This is the outline a coverage glyph can have. A distance-field glyph is grown
+ * by moving the edge the shader reads (see text-renderer outlineBias); a coverage
+ * one has no distance to move, and stamping copies of it around a circle draws
+ * the glyph several times rather than drawing a ring — fine for a hairline, eight
+ * ghosts at the widths a game label asks for.
+ */
+export function dilateCoverage(alpha: Uint8Array, width: number, height: number, radius: number): {
+ alpha: Uint8Array; width: number; height: number; margin: number;
+} {
+ const r = Math.max(0, radius);
+ const margin = Math.ceil(r) + 1;
+ const w = width + margin * 2;
+ const h = height + margin * 2;
+ const out = new Uint8Array(w * h);
+ // The disk's offsets and their weights, once: a texel at distance d inside
+ // r - 0.5 counts whole, one past r + 0.5 not at all.
+ const reach = Math.ceil(r + 0.5);
+ const taps: number[] = [];
+ for (let dy = -reach; dy <= reach; dy++) {
+ for (let dx = -reach; dx <= reach; dx++) {
+ const weight = Math.min(1, Math.max(0, r + 0.5 - Math.hypot(dx, dy)));
+ if (weight > 0) taps.push(dx, dy, weight);
+ }
+ }
+ for (let y = 0; y < h; y++) {
+ const sy = y - margin;
+ for (let x = 0; x < w; x++) {
+ const sx = x - margin;
+ let best = 0;
+ for (let t = 0; t < taps.length; t += 3) {
+ const ix = sx + taps[t];
+ const iy = sy + taps[t + 1];
+ if (ix < 0 || iy < 0 || ix >= width || iy >= height) continue;
+ const v = alpha[iy * width + ix] * taps[t + 2];
+ if (v > best) best = v;
+ }
+ out[y * w + x] = best + 0.5;
+ }
+ }
+ return { alpha: out, width: w, height: h, margin };
+}
+
+/** A coverage tile grown into its outline, in the atlas's RGBA format (RGB 255, A coverage). */
+function outlineRaster(raster: RasterGlyph, radius: number): RasterGlyph {
+ const n = raster.width * raster.height;
+ const alpha = new Uint8Array(n);
+ for (let i = 0; i < n; i++) alpha[i] = raster.pixels[i * 4 + 3];
+ const grown = dilateCoverage(alpha, raster.width, raster.height, radius);
+ const pixels = new Uint8Array(grown.width * grown.height * 4);
+ for (let i = 0; i < grown.alpha.length; i++) {
+ const o = i * 4;
+ pixels[o] = 255; pixels[o + 1] = 255; pixels[o + 2] = 255; pixels[o + 3] = grown.alpha[i];
+ }
+ return {
+ pixels, width: grown.width, height: grown.height, advance: raster.advance,
+ bearingX: raster.bearingX - grown.margin, bearingY: raster.bearingY + grown.margin,
+ };
+}
+
/**
* Caches glyphs into one or more atlas pages, rasterizing on first use.
*/
export class GlyphAtlas {
+ /** Which glyph each placed entry is — what an outline of it is grown from. */
+ private readonly identity_ = new WeakMap<GlyphEntry, GlyphIdentity>();
private readonly pageSize: number;
private readonly padding: number;
private readonly sdf: boolean;
@@ -238,8 +315,11 @@ export class GlyphAtlas {
/** Reported families with non-drawable glyphs still in the bounded CPU cache. */
private readonly mute_ = new Set<string>();
- private key(codepoint: number, fontFamily: string, style: number, pixelSize: number): string {
- return `${fontFamily}|${codepoint}|${style % STYLE_COUNT_HINT}|${pixelSize}`;
+ private key(codepoint: number, fontFamily: string, style: number, pixelSize: number, outline = 0): string {
+ // The radius rides on the size segment, so the key keeps the three numeric
+ // suffixes familyFromKey strips.
+ const size = outline > 0 ? `${pixelSize}o${outline}` : `${pixelSize}`;
+ return `${fontFamily}|${codepoint}|${style % STYLE_COUNT_HINT}|${size}`;
}
/**
@@ -250,7 +330,29 @@ export class GlyphAtlas {
getGlyph(codepoint: number, fontFamily: string, style = 0, pixelSize = this.renderSize): GlyphEntry | null {
// A bitmap font is its own atlas: the glyph is already on a page the engine holds.
if (bitmapFontOf(fontFamily)) return bitmapGlyph(fontFamily, codepoint);
- const k = this.key(codepoint, fontFamily, style, pixelSize);
+ return this.glyph_({ codepoint, fontFamily, style, pixelSize }, 0);
+ }
+
+ /**
+ * @p entry's glyph grown by @p radius rasterized px — the shape its outline
+ * is drawn with, in one pass, on an atlas of coverage glyphs. Placed and cached
+ * like the glyph itself (one cell per glyph, size and radius), with metrics in
+ * the same units: its box is the glyph's, `margin` larger on every side.
+ *
+ * Null on a distance-field atlas (the shader grows those, see outlineBias), for
+ * a glyph this atlas did not place (a bitmap font's), and when the glyph cannot
+ * be produced — the caller keeps its own fallback for all three.
+ */
+ outlined(entry: GlyphEntry, radius: number): GlyphEntry | null {
+ if (this.sdf || !(radius > 0)) return null;
+ const id = this.identity_.get(entry);
+ if (!id) return null;
+ return this.glyph_(id, radius);
+ }
+
+ private glyph_(id: GlyphIdentity, outline: number): GlyphEntry | null {
+ const { codepoint, fontFamily, style, pixelSize } = id;
+ const k = this.key(codepoint, fontFamily, style, pixelSize, outline);
const hit = this.cache.get(k);
if (hit !== undefined) return hit;
const cpuHit = this.cpuCache.get(k);
@@ -260,7 +362,7 @@ export class GlyphAtlas {
return cpuHit;
}
- const raster = this.rasterizer.rasterize(codepoint, fontFamily, style, pixelSize);
+ const raster = this.raster_(codepoint, fontFamily, style, pixelSize, outline);
if (!raster) {
// Cached non-drawable glyphs own their family's diagnostic suppression.
this.cacheCPU(k, null);
@@ -308,7 +410,7 @@ export class GlyphAtlas {
const pageId = this.pages[placed.page];
this.store.uploadSubRegion(pageId, placed.x, placed.y, raster.width, raster.height, raster.pixels);
this.placements[placed.page].push({
- codepoint, fontFamily, style, pixelSize,
+ codepoint, fontFamily, style, pixelSize, outline,
x: placed.x, y: placed.y, width: raster.width, height: raster.height,
});
@@ -326,9 +428,18 @@ export class GlyphAtlas {
bearingY: raster.bearingY,
};
this.cache.set(k, entry);
+ if (outline === 0) this.identity_.set(entry, id);
return entry;
}
+ /** The tile for one cell: the glyph as rasterized, or grown into its outline. */
+ private raster_(codepoint: number, fontFamily: string, style: number, pixelSize: number,
+ outline: number): RasterGlyph | null {
+ const raster = this.rasterizer.rasterize(codepoint, fontFamily, style, pixelSize);
+ if (!raster || outline <= 0 || raster.width <= 0 || raster.height <= 0) return raster;
+ return outlineRaster(raster, outline);
+ }
+
/** Page-free entries can be recreated without changing any live layout or UV. */
private cacheCPU(key: string, glyph: GlyphEntry | null): void {
const wasMissing = this.cpuCache.get(key) === null;
@@ -389,7 +500,7 @@ export class GlyphAtlas {
private paintPage(glyphs: readonly GlyphPlacement[], pixels: Uint8Array): void {
const size = this.pageSize;
for (const g of glyphs) {
- const raster = this.rasterizer.rasterize(g.codepoint, g.fontFamily, g.style, g.pixelSize);
+ const raster = this.raster_(g.codepoint, g.fontFamily, g.style, g.pixelSize, g.outline);
if (!raster) continue;
const width = Math.min(raster.width, g.width);
const height = Math.min(raster.height, g.height);
diff --git a/sdk/src/ui/text/layout.ts b/sdk/src/ui/text/layout.ts
index 97b755f92..a4ea1e6ed 100644
--- a/sdk/src/ui/text/layout.ts
+++ b/sdk/src/ui/text/layout.ts
@@ -13,7 +13,7 @@
* Glyph metrics from the atlas are in renderSize px; everything scales by
* displaySize / atlas.renderSize (SDF is resolution-independent).
*/
-import type { GlyphAtlas } from './glyph-atlas';
+import type { GlyphAtlas, GlyphEntry } from './glyph-atlas';
import { TEXT_VERTEX_FLOATS } from './submit';
import { parseRichText, type TextSegment, type ImageSegment, type RichTextRun } from './rich-text-parser';
import { UI_TEXT_BOLD, UI_TEXT_ITALIC } from './text-transform';
@@ -37,6 +37,8 @@ export interface LaidGlyph {
x1: number; y1: number; // top-right
pageId: number;
color?: RGBA;
+ /** The atlas entry the quad was cut from — what an outline of the glyph is grown from. */
+ entry?: GlyphEntry;
}
/** One placed inline `<img>` run: a box in the same local space as glyphs
@@ -100,7 +102,7 @@ export function layoutLine(
const y1 = g.bearingY * scale; // top, above baseline
const x1 = x0 + g.width * scale;
const y0 = y1 - g.height * scale; // bottom
- glyphs.push({ u0: g.u0, v0: g.v0, u1: g.u1, v1: g.v1, x0, y0, x1, y1, pageId: g.pageId });
+ glyphs.push({ u0: g.u0, v0: g.v0, u1: g.u1, v1: g.v1, x0, y0, x1, y1, pageId: g.pageId, entry: g });
}
penX += g.advance * scale + spacing;
}
@@ -676,7 +678,7 @@ export function layoutRichRuns(
glyphs.push({
u0: gph.u0, v0: gph.v0, u1: gph.u1, v1: gph.v1,
x0, y0: y1 - gph.height * scale, x1: x0 + gph.width * scale, y1,
- pageId: gph.pageId, color,
+ pageId: gph.pageId, color, entry: gph,
});
}
penX += gph.advance * scale + spacing;
diff --git a/sdk/src/ui/text/text-renderer.ts b/sdk/src/ui/text/text-renderer.ts
index 62a325455..865e7b778 100644
--- a/sdk/src/ui/text/text-renderer.ts
+++ b/sdk/src/ui/text/text-renderer.ts
@@ -202,6 +202,57 @@ function addUnderlines(layout: TextLayout, atlas: GlyphAtlas, fontFamily: string
}
}
+/** Glyphs grouped by the atlas page (texture) they sample, each group cut to one
+ * batch's worth — a string can reference glyphs across several pages. */
+function pageChunks(glyphs: readonly LaidGlyph[]): Array<[number, readonly LaidGlyph[]]> {
+ const byPage = new Map<number, LaidGlyph[]>();
+ for (const g of glyphs) {
+ let arr = byPage.get(g.pageId);
+ if (!arr) { arr = []; byPage.set(g.pageId, arr); }
+ arr.push(g);
+ }
+ const chunks: Array<[number, readonly LaidGlyph[]]> = [];
+ for (const [pageId, list] of byPage) {
+ for (let start = 0; start < list.length; start += MAX_TEXT_BATCH_GLYPHS) {
+ chunks.push([pageId, list.length <= MAX_TEXT_BATCH_GLYPHS
+ ? list : list.slice(start, start + MAX_TEXT_BATCH_GLYPHS)]);
+ }
+ }
+ return chunks;
+}
+
+/**
+ * The outline of laid-out coverage glyphs: each glyph's own cell grown by
+ * @p widthPx (text px), placed over the glyph's box grown by the same amount.
+ * The radius is asked in rasterized texels, halved to 0.5-texel steps so labels
+ * of one size share cells. A quad cut from no glyph (an underline bar) is solid,
+ * and grows by simply being drawn larger. Null when any glyph cannot be grown —
+ * the caller then has one fallback for the whole label, never a mixed ring.
+ */
+export function outlineGlyphs(atlas: GlyphAtlas, glyphs: readonly LaidGlyph[], widthPx: number): LaidGlyph[] | null {
+ const out: LaidGlyph[] = [];
+ for (const g of glyphs) {
+ const entry = g.entry;
+ if (!entry) {
+ out.push({ ...g, color: undefined, x0: g.x0 - widthPx, y0: g.y0 - widthPx, x1: g.x1 + widthPx, y1: g.y1 + widthPx });
+ continue;
+ }
+ if (entry.width <= 0) return null;
+ const perTexel = (g.x1 - g.x0) / entry.width; // text px per rasterized texel
+ if (!(perTexel > 0)) return null;
+ const radius = Math.max(0.5, Math.round((widthPx / perTexel) * 2) / 2);
+ const grown = atlas.outlined(entry, radius);
+ if (!grown) return null;
+ const grow = ((grown.width - entry.width) / 2) * perTexel;
+ out.push({
+ u0: grown.u0, v0: grown.v0, u1: grown.u1, v1: grown.v1,
+ x0: g.x0 - grow, y0: g.y0 - grow, x1: g.x1 + grow, y1: g.y1 + grow,
+ pageId: grown.pageId,
+ });
+ }
+ return out;
+}
+
export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTextParams): number {
if (atlas.metricsOnly) throw new Error('Measurement atlases cannot submit text.');
const opacity = p.opacity ?? 1;
@@ -239,21 +290,8 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTex
boxHeight, layout.lineHeight, fontSizePx, p.verticalAlign, lineHeightPx, ascent,
);
- // A string can reference glyphs across several atlas pages; each page is a
- // distinct texture. Split oversized pages once, before emitting effects.
- const byPage = new Map<number, LaidGlyph[]>();
- for (const g of layout.glyphs) {
- let arr = byPage.get(g.pageId);
- if (!arr) { arr = []; byPage.set(g.pageId, arr); }
- arr.push(g);
- }
- const chunks: Array<[number, readonly LaidGlyph[]]> = [];
- for (const [pageId, glyphs] of byPage) {
- for (let start = 0; start < glyphs.length; start += MAX_TEXT_BATCH_GLYPHS) {
- chunks.push([pageId, glyphs.length <= MAX_TEXT_BATCH_GLYPHS
- ? glyphs : glyphs.slice(start, start + MAX_TEXT_BATCH_GLYPHS)]);
- }
- }
+ // Split oversized pages once, before emitting effects.
+ const chunks = pageChunks(layout.glyphs);
const baseX = (p.originX ?? 0) + textBlockOffsetX(p.align, boxWidth, layout.width);
// Emit the glyph set once per page, recolored + offset. All passes are SDF
@@ -263,8 +301,9 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTex
// that is a shape — shadow, the outline ring — and Fill for the glyph. The page's own colours never show, so the ring is
// whatever colour the outline asks for, and without an outline there is no ring at all.
const baked = bitmapFontOf(p.fontFamily)?.outlineInAlpha === true;
- const emitPass = (color: RGBA, dx: number, dy: number, bias = 0, useGlyphColors = false, mode?: TextGlyphMode): void => {
- for (const [pageId, glyphs] of chunks) {
+ const emitChunks = (set: ReadonlyArray<readonly [number, readonly LaidGlyph[]]>, color: RGBA, dx: number, dy: number,
+ bias = 0, useGlyphColors = false, mode?: TextGlyphMode): void => {
+ for (const [pageId, glyphs] of set) {
const { vertices, indices } = buildGlyphVertices(glyphs, color, baseX + dx, originY + dy, bias, useGlyphColors);
if (opacity !== 1) {
for (let i = 7; i < vertices.length; i += TEXT_VERTEX_FLOATS) vertices[i] *= opacity;
@@ -272,6 +311,9 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTex
sink(vertices, indices, pageId, mode);
}
};
+ const emitPass = (color: RGBA, dx: number, dy: number, bias = 0, useGlyphColors = false, mode?: TextGlyphMode): void =>
+ emitChunks(chunks, color, dx, dy, bias, useGlyphColors, mode);
+ const emitGlyphs = (glyphs: readonly LaidGlyph[], color: RGBA): void => emitChunks(pageChunks(glyphs), color, 0, 0);
// A label's shadow and outline belong to it: they fade with its own alpha, so
// a text faded out by its colour leaves no shadow behind (Unity's rule; CSS
@@ -295,10 +337,11 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTex
emitPass(color, dx, -dy, 0, false, baked ? TextGlyphMode.Mask : undefined);
}
}
- // Outline. On a distance-field atlas this is the glyph drawn once more with
- // its edge pushed out — a real dilation, so the shape survives any width. The
- // bitmap atlas has no distance to push, so it keeps the eight-way stamp, which
- // is only ever asked for hairlines there.
+ // Outline: the glyphs grown by the width, drawn once behind the fill. On a
+ // distance-field atlas the shader grows them (the edge it reads is moved), so
+ // the shape survives any width. A coverage atlas has no distance to move, so
+ // it places each glyph grown into its own cell (GlyphAtlas.outlined) — a ring,
+ // where stamping eight offset copies drew the label eight more times.
const outlineColor = p.outline ? decoration(p.outline.color) : null;
if (baked) {
// The page has the ring already: it is drawn, not grown, so the width only says whether there is one.
@@ -306,7 +349,10 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTex
} else if (p.outline && p.outline.width > 0 && outlineColor![3] > 0) {
const w = p.outline.width;
const bias = outlineBias(atlas, fontSizePx, w);
+ const ring = bias > 0 ? null : outlineGlyphs(atlas, layout.glyphs, w);
if (bias > 0) emitPass(outlineColor!, 0, 0, bias);
+ else if (ring) emitGlyphs(ring, outlineColor!);
+ // A glyph the atlas cannot grow (a bitmap font without a baked ring) keeps the stamp.
else for (const [ox, oy] of OUTLINE_OFFSETS) emitPass(outlineColor!, ox * w, oy * w);
}
// Fill (on top).
diff --git a/sdk/tests/glyph-dilate.test.ts b/sdk/tests/glyph-dilate.test.ts
new file mode 100644
index 000000000..208d1df25
--- /dev/null
+++ b/sdk/tests/glyph-dilate.test.ts
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { dilateCoverage, GlyphAtlas, type AtlasPageStore, type GlyphRasterizer } from '../src/ui/text/glyph-atlas';
+
+describe('growing a coverage glyph into its outline', () => {
+ it('reaches the radius solid, fades over its last texel, and goes no further', () => {
+ // One lit texel in a 1x1 tile, grown by 3.
+ const { alpha, width, height, margin } = dilateCoverage(new Uint8Array([255]), 1, 1, 3);
+ expect(margin).toBe(4);
+ expect(width).toBe(9);
+ expect(height).toBe(9);
+ const at = (x: number, y: number) => alpha[(y + margin) * width + (x + margin)];
+ expect(at(0, 0)).toBe(255);
+ expect(at(2, 0)).toBe(255); // inside the disk
+ expect(at(3, 0)).toBe(128); // the edge texel, half covered
+ expect(at(4, 0)).toBe(0); // past it
+ expect(at(2, 2)).toBe(171); // diagonal: distance 2.83, inside r + 0.5 by 0.67 → weighted
+ expect(at(3, 3)).toBe(0);
+ });
+
+ it('keeps the glyph its own strength where it is weaker than full', () => {
+ const { alpha, width, margin } = dilateCoverage(new Uint8Array([100]), 1, 1, 1);
+ expect(alpha[margin * width + margin]).toBe(100);
+ expect(alpha[margin * width + margin + 1]).toBe(50); // on the radius: half
+ });
+
+ it('places a grown glyph as its own cell, and repaints it grown', () => {
+ const ink = new Uint8Array(4 * 4 * 4);
+ for (let i = 3; i < ink.length; i += 4) ink[i] = 255;
+ const rasterizer: GlyphRasterizer = {
+ renderSize: 16, spread: 0,
+ rasterize: () => ({ pixels: ink, width: 4, height: 4, advance: 5, bearingX: 0, bearingY: 4 }),
+ };
+ let paint: ((pixels: Uint8Array) => void) | null = null;
+ const store: AtlasPageStore = {
+ createPage: (_size, p) => { paint = p; return 1; },
+ uploadSubRegion: () => {},
+ };
+ const atlas = new GlyphAtlas(rasterizer, store, { pageSize: 64, padding: 1, sdf: false });
+ const glyph = atlas.getGlyph(65, 'Arial', 0, 16)!;
+ const ring = atlas.outlined(glyph, 2)!;
+ expect(ring.width).toBe(4 + 2 * 3);
+ expect(ring.bearingX).toBe(glyph.bearingX - 3);
+ expect(ring.bearingY).toBe(glyph.bearingY + 3);
+ expect(atlas.outlined(glyph, 2)).toBe(ring); // cached by glyph, size and radius
+ // A lost page comes back with the ring grown again, not the bare glyph in its cell.
+ const page = new Uint8Array(64 * 64 * 4);
+ paint!(page);
+ const ringX = Math.round(ring.u0 * 64), ringY = Math.round(ring.v0 * 64);
+ expect(page[((ringY + 3) * 64 + ringX + 2) * 4 + 3]).toBe(255); // grown texel one left of the ink
+ });
+
+ it('answers null on a distance-field atlas, which the shader grows instead', () => {
+ const rasterizer: GlyphRasterizer = {
+ renderSize: 16, spread: 4,
+ rasterize: () => ({ pixels: new Uint8Array(16 * 4), width: 4, height: 4, advance: 5, bearingX: 0, bearingY: 4 }),
+ };
+ const store: AtlasPageStore = { createPage: () => 1, uploadSubRegion: () => {} };
+ const atlas = new GlyphAtlas(rasterizer, store, { pageSize: 64, padding: 1, sdf: true });
+ expect(atlas.outlined(atlas.getGlyph(65, 'Arial')!, 2)).toBeNull();
+ });
+});
diff --git a/sdk/tests/ui-text-renderer.test.ts b/sdk/tests/ui-text-renderer.test.ts
index 974be07a1..a18859f88 100644
--- a/sdk/tests/ui-text-renderer.test.ts
+++ b/sdk/tests/ui-text-renderer.test.ts
@@ -193,9 +193,40 @@ describe('REARCH_GUI P1.3b: drawTextWith', () => {
expect(fill[8]).toBe(0);
});
- it('falls back to the stamp fan when the glyphs are coverage, not distance', () => {
- // A bitmap atlas has no distance to move, so the only way to widen a glyph
- // is still to draw it around itself.
+ it('outlines coverage glyphs with one pass of grown cells, not eight stamped copies', () => {
+ // A bitmap atlas has no distance to move. Stamping the glyph around itself
+ // drew the label eight more times, and at a game label's width (#104: 3-8px)
+ // that reads as ghosts, not a ring — so each glyph is grown into a cell of its own.
+ const ink = new Uint8Array(10 * 12 * 4);
+ for (let i = 3; i < ink.length; i += 4) ink[i] = 255;
+ const rasterizer: GlyphRasterizer = {
+ renderSize: 48,
+ spread: 0,
+ rasterize: (): RasterGlyph =>
+ ({ pixels: ink, width: 10, height: 12, advance: 11, bearingX: 1, bearingY: 10 }),
+ };
+ let next = 2000;
+ const uploads: Array<{ w: number; h: number }> = [];
+ const store: AtlasPageStore = { createPage: () => next++, uploadSubRegion: (_p, _x, _y, w, h) => { uploads.push({ w, h }); } };
+ const atlas = new GlyphAtlas(rasterizer, store, { pageSize: 1024, padding: 1, sdf: false });
+ const sink = vi.fn();
+ drawTextWith(atlas, sink, {
+ text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1],
+ outline: { color: [0, 0, 0, 1], width: 3 },
+ });
+ expect(sink).toHaveBeenCalledTimes(2); // the ring, then the fill
+ const [ring, fill] = sink.mock.calls.map((c) => c[0] as Float32Array);
+ // Same glyph count, each ring quad wider than its glyph by the outline on both sides.
+ expect(ring.length).toBe(fill.length);
+ const widthOf = (v: Float32Array) => v[TEXT_VERTEX_FLOATS] - v[0];
+ expect(widthOf(ring) - widthOf(fill)).toBeGreaterThanOrEqual(2 * 3);
+ // The ring was placed as cells of its own: two glyphs, and each grown once.
+ expect(uploads.length).toBe(4);
+ });
+
+ it('keeps the stamp for glyphs it cannot grow', () => {
+ // A quad cut from no atlas entry of this atlas (here: every glyph comes from
+ // an atlas whose outlined() answers null) still gets an outline.
const rasterizer: GlyphRasterizer = {
renderSize: 48,
spread: 0,
@@ -205,6 +236,7 @@ describe('REARCH_GUI P1.3b: drawTextWith', () => {
let next = 2000;
const store: AtlasPageStore = { createPage: () => next++, uploadSubRegion: () => {} };
const atlas = new GlyphAtlas(rasterizer, store, { pageSize: 1024, padding: 1, sdf: false });
+ atlas.outlined = () => null;
const sink = vi.fn();
drawTextWith(atlas, sink, {
text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1],