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
perf(text): wrap native measurements with ordered advances
yhh1ba04c64df5d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cb6ab1d1c..4e1d3714b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Native text measurement wraps without rescanning growing prefixes.** The public measurement path appends ordered glyph advances through the shared greedy wrapper, avoiding quadratic cache queries and repeated host rasterization when long text exceeds the bounded working set. Whitespace, supplementary characters and signed spacing keep existing line breaks and metrics; Canvas retains whole-string measurement for non-additive typography.+- **Public native text measurement retains a bounded advance cache.** Historical font revisions, sizes and missing-glyph estimates retire from a 4096-entry working set. A second-chance clock keeps recently queried advances reusable without reinserting Map entries on every character; failed host measurements leave retained entries intact. Widths, wrapping and the Canvas measurement path retain their existing behavior.### Addeddiff --git a/sdk/src/ui/text/layout.ts b/sdk/src/ui/text/layout.tsindex 439b6be0a..23008d392 100644--- a/sdk/src/ui/text/layout.ts+++ b/sdk/src/ui/text/layout.ts@@ -268,8 +268,11 @@ export function measurePrefixWidths(* atlas-backed {@link wrapLine} and the Canvas2D-backed `measureText` both call* it, so measured heights match rendered wraps.*/-export function wrapByMeasure(text: string, measure: (s: string) => number, maxWidth: number): string[] {- return wrapMeasured(text, measure, maxWidth);+export function wrapByMeasure(+ text: string, measure: (s: string) => number, maxWidth: number,+ appendWidth?: (width: number, suffix: string) => number,+): string[] {+ return wrapMeasured(text, measure, maxWidth, appendWidth);}function wrapMeasured(diff --git a/sdk/src/ui/text/measure-text.ts b/sdk/src/ui/text/measure-text.tsindex eef6e4d23..c2634028d 100644--- a/sdk/src/ui/text/measure-text.ts+++ b/sdk/src/ui/text/measure-text.ts@@ -42,7 +42,10 @@ export interface TextMetrics {height: number;}-type Measurer = (s: string) => number;+type Measurer = {+ (s: string): number;+ append?: (width: number, suffix: string) => number;+};let ctx_: CanvasRenderingContext2D | null | undefined;@@ -111,11 +114,13 @@ function measurer(opts: MeasureTextOptions): Measurer {}if (platformHasGlyphRasterizer()) {const style = (opts.bold ? FONT_STYLE_BOLD : 0) | (opts.italic ? FONT_STYLE_ITALIC : 0);- return (s) => {- let width = 0;- for (const ch of s) width += platformAdvance(ch.codePointAt(0)!, family, style, opts.fontSize) + spacing;+ const append = (width: number, suffix: string): number => {+ for (const ch of suffix) width += platformAdvance(ch.codePointAt(0)!, family, style, opts.fontSize) + spacing;return width;};+ const measure: Measurer = s => append(0, s);+ measure.append = append;+ return measure;}// Headless fallback: a wide-ish average so wraps don't under-count.const avg = opts.fontSize * 0.6 + spacing;@@ -132,7 +137,7 @@ export function measureText(text: string, opts: MeasureTextOptions): TextMetricsconst wrap = opts.maxWidth && opts.maxWidth > 0;const lines: string[] = [];for (const para of text.split('\n')) {- if (wrap) lines.push(...wrapByMeasure(para, measure, opts.maxWidth!));+ if (wrap) lines.push(...wrapByMeasure(para, measure, opts.maxWidth!, measure.append));else lines.push(para);}let width = 0;diff --git a/sdk/tests/measure-text-cache.test.ts b/sdk/tests/measure-text-cache.test.tsindex e9f20d02f..69b24fa11 100644--- a/sdk/tests/measure-text-cache.test.ts+++ b/sdk/tests/measure-text-cache.test.ts@@ -81,3 +81,42 @@ it('keeps retained measurements available after a host rasterization error', asyexpect(measure('replacement')).toBe(10);expect(host.rasterize).toHaveBeenCalledTimes(calls + 1);});++it('wraps a long distinct-character token without repeatedly evicting and rasterizing its prefixes', async () => {+ const { measureText } = await import('../src/ui/text/measure-text');+ host.rasterize.mockReturnValue({ advance: 1 });+ const value = Array.from({ length: 4100 }, (_, i) => String.fromCodePoint(0x4e00 + i)).join('');+ const metrics = measureText(value, { fontSize: 20, maxWidth: 4099 });+ expect(metrics).toEqual({ width: 4099, lineCount: 2, height: 48 });+ expect(host.rasterize.mock.calls.length).toBeLessThanOrEqual(value.length * 3);+}, 10000);++it('preserves greedy wrap metrics with whitespace, supplementary characters and signed spacing', async () => {+ const { measureText } = await import('../src/ui/text/measure-text');+ const { wrapByMeasure } = await import('../src/ui/text/layout');+ for (const value of ['', 'hello world', ' a b ', 'longwordwithoutspaces', '中文🙂 words', 'a\tb\nc', '🙂🙂🙂']) {+ for (const letterSpacing of [-12, -1, 0, 0.25]) {+ const measure = (text: string): number => {+ let width = 0;+ for (const ch of text) width += 10 + ch.codePointAt(0)! % 3 + letterSpacing;+ return width;+ };+ for (const maxWidth of [1, 12, 27, 100]) {+ const lines = value.split('\n').flatMap(line => wrapByMeasure(line, measure, maxWidth));+ expect(measureText(value, { fontSize: 20, letterSpacing, maxWidth })).toEqual({+ width: Math.max(0, ...lines.map(measure)),+ lineCount: lines.length,+ height: lines.length * 24,+ });+ }+ }+ }+});++it('continues measuring whole Canvas strings when advances are not additive', async () => {+ const context = { font: '', measureText: (text: string) => ({ width: text === 'AV' ? 12 : text.length * 8 }) };+ vi.stubGlobal('document', { createElement: () => ({ getContext: () => context }) });+ const { measureText } = await import('../src/ui/text/measure-text');+ expect(measureText('AV AV', { fontSize: 20, maxWidth: 12 })).toEqual({ width: 12, lineCount: 2, height: 48 });+ expect(host.rasterize).not.toHaveBeenCalled();+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 7d070afc9..d690edd63 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'perf(text): wrap native measurements with ordered advances':+ { note: 'Native text measurement wraps without rescanning growing prefixes.' },'fix(text): bound native measurement advance history':{ note: 'Public native text measurement retains a bounded advance cache.' },'fix(text): isolate font reload ownership and glyph caches':