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.

test(ui): add paired browser text cache CPU measurements (#88)

YHHbeab2d70e37b
diff --git a/examples/ui-localization-debug/README.md b/examples/ui-localization-debug/README.md
index 0e3e9400c..52145f4b6 100644
--- a/examples/ui-localization-debug/README.md
+++ b/examples/ui-localization-debug/README.md
@@ -141,3 +141,15 @@ Visible may still be clipped by the fixture's actual ancestor mask.
Press K twice while the game has focus to change Inside from `A|B` / `Arial`
to `A` / `B|Arial`. Text and font family change together; the canvas must show
only `A` after the second press. Elements → Inside → Text exposes both values.
+
+For a repeatable CPU cache comparison, run `node tools/ui-text-cache-benchmark.mjs`,
+open `http://127.0.0.1:5196/__text-cache-benchmark` in the built-in browser and
+press Run comparison. The same 200 bilingual labels run with the real SDK
+renderer cache retained or cleared each frame, at 0/1/10/100% update rates.
+The warmed Canvas bitmap atlas uses an in-memory page store and submission sink.
+This isolates CPU geometry/cache work; GPU uploads, WASM copies, Yoga reflow,
+complex shaping and full game-frame acceptance are excluded. The page checks
+exact submitted geometry outside timing and exposes raw paired samples and
+environment metadata. Statistics describe ten batch-average frame times, not
+individual-frame P95. A representative run is saved in
+`cache-cpu-web-2026-10-09.json`; timings vary with JIT and background load.
diff --git a/examples/ui-localization-debug/VALIDATION.md b/examples/ui-localization-debug/VALIDATION.md
index 080bd4859..5904dfde9 100644
--- a/examples/ui-localization-debug/VALIDATION.md
+++ b/examples/ui-localization-debug/VALIDATION.md
@@ -408,3 +408,25 @@ snapshot; live-game-only dialogs and scripts need runtime acceptance separately.
16px depth steps, including Runtime dialog host and its Runtime button child.
- Selecting the truncated Runtime dialog host shows its full name/path and
real component values. Editor typecheck passes. No desktop runner launched.
+
+## Paired CPU cache measurement — 2026-10-09
+
+- Added a browser-only, reproducible measurement page using the real SDK
+ CanvasGlyphRasterizer, GlyphAtlas, SdfTextRenderer and submission interface.
+ An in-memory atlas store and submission sink deliberately exclude GPU/WASM.
+ This is a cache-on versus cache-cleared comparison, not a historical code
+ before/after comparison or a newly shipped runtime optimization.
+- Both paths use 200 identical bilingual labels, prewarmed glyphs and text
+ variants; ten paired batches of ten frames alternate execution order.
+ Exactly 0/2/20/200 labels change each frame. Exact vertex/index/entity geometry
+ comparison passes for all four cases, outside the timed section.
+- Built-in Chrome 155 on Windows, devicePixelRatio 1.25: median batch-average
+ frame milliseconds, rebuilt → cached: static 4.290 → 0.070; 1% changes
+ 3.990 → 0.110; 10% 3.690 → 0.480; 100% 4.010 → 4.060.
+ All-changing text offers no measured cache benefit. Raw samples and execution
+ metadata are in cache-cpu-web-2026-10-09.json. P95 refers to batch averages;
+ it does not describe individual frame tail latency. No speed threshold.
+- GPU/WASM submission, Yoga reflow, end-to-end frame timing, SDF rasterization,
+ complex shaping and target devices remain unmeasured. Warm-up/JIT/background
+ load affect results; do not convert these ratios into a game FPS claim.
+ RM-009 remains In Progress. No local Electron/native runner launched.
diff --git a/examples/ui-localization-debug/cache-cpu-web-2026-10-09.json b/examples/ui-localization-debug/cache-cpu-web-2026-10-09.json
new file mode 100644
index 000000000..4c3188f8a
--- /dev/null
+++ b/examples/ui-localization-debug/cache-cpu-web-2026-10-09.json
@@ -0,0 +1,144 @@
+{
+ "schema": 1,
+ "labels": 200,
+ "rounds": 10,
+ "frames": 10,
+ "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36",
+ "hardwareConcurrency": 20,
+ "dpr": 1.25,
+ "date": "2026-10-10T01:57:08.118Z",
+ "submissions": 176000,
+ "vertices": 21632160,
+ "results": [
+ {
+ "rate": 0,
+ "samples": {
+ "cached": [
+ 0.13999999761581422,
+ 0.05999999046325684,
+ 0.07999999523162842,
+ 0.17000000476837157,
+ 0.06999999284744263,
+ 0.07000000476837158,
+ 0.06000000238418579,
+ 0.05999999046325684,
+ 0.06000000238418579,
+ 0.12000000476837158
+ ],
+ "rebuilt": [
+ 4.889999997615814,
+ 4.460000002384186,
+ 4.289999997615814,
+ 4.3699999928474424,
+ 4.4,
+ 4.239999997615814,
+ 3.739999997615814,
+ 3.7700000047683715,
+ 4.25,
+ 6.989999997615814
+ ]
+ },
+ "cachedMedian": 0.06999999284744263,
+ "rebuiltMedian": 4.289999997615814,
+ "geometryEqual": true
+ },
+ {
+ "rate": 0.01,
+ "samples": {
+ "cached": [
+ 0.1100000023841858,
+ 0.13999999761581422,
+ 0.1899999976158142,
+ 0.12000000476837158,
+ 0.21000000238418579,
+ 0.13000000715255738,
+ 0.10999999046325684,
+ 0.1,
+ 0.1,
+ 0.0899999976158142
+ ],
+ "rebuilt": [
+ 4.270000004768372,
+ 3.8899999976158144,
+ 5.360000002384186,
+ 3.769999992847443,
+ 4.069999992847443,
+ 4.329999995231629,
+ 3.990000009536743,
+ 4.5,
+ 3.6200000047683716,
+ 3.5200000047683715
+ ]
+ },
+ "cachedMedian": 0.1100000023841858,
+ "rebuiltMedian": 3.990000009536743,
+ "geometryEqual": true
+ },
+ {
+ "rate": 0.1,
+ "samples": {
+ "cached": [
+ 0.4799999952316284,
+ 0.5399999976158142,
+ 0.5,
+ 0.5199999928474426,
+ 0.5399999976158142,
+ 0.4299999952316284,
+ 0.4399999976158142,
+ 0.5,
+ 0.4799999952316284,
+ 0.42000000476837157
+ ],
+ "rebuilt": [
+ 3.7,
+ 3.410000002384186,
+ 3.7200000047683717,
+ 3.760000002384186,
+ 3.689999997615814,
+ 3.6700000047683714,
+ 3.7200000047683717,
+ 3.5599999904632567,
+ 3.6299999952316284,
+ 3.760000002384186
+ ]
+ },
+ "cachedMedian": 0.4799999952316284,
+ "rebuiltMedian": 3.689999997615814,
+ "geometryEqual": true
+ },
+ {
+ "rate": 1,
+ "samples": {
+ "cached": [
+ 4.35,
+ 4.1,
+ 4.189999997615814,
+ 3.95,
+ 4,
+ 4,
+ 4.1,
+ 4.060000002384186,
+ 4.65,
+ 3.980000007152557
+ ],
+ "rebuilt": [
+ 4.110000002384186,
+ 3.810000002384186,
+ 4.1300000071525576,
+ 3.7199999928474425,
+ 4.010000002384186,
+ 3.9600000023841857,
+ 4.019999992847443,
+ 4.410000002384185,
+ 5.080000007152558,
+ 3.8799999952316284
+ ]
+ },
+ "cachedMedian": 4.060000002384186,
+ "rebuiltMedian": 4.010000002384186,
+ "geometryEqual": true
+ }
+ ],
+ "statistic": "median and nearest-rank P95 of 10 batch-average frame times",
+ "scope": "CPU geometry/cache only; warm Canvas bitmap atlas; no GPU/WASM/Yoga; not historical before/after or device acceptance"
+}
diff --git a/tools/ui-text-cache-benchmark.mjs b/tools/ui-text-cache-benchmark.mjs
new file mode 100644
index 000000000..e9fc99ad9
--- /dev/null
+++ b/tools/ui-text-cache-benchmark.mjs
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: Apache-2.0
+// Browser-only CPU benchmark; never launches a desktop runner.
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const { createServer } = await import(pathToFileURL(path.join(root, 'desktop/node_modules/vite/dist/node/index.js')).href);
+const server = await createServer({ configFile: false, root,
+ optimizeDeps: { noDiscovery: true, entries: [] },
+ server: { host: '127.0.0.1', port: 5196, strictPort: true },
+ plugins: [{ name: 'text-cache-benchmark', configureServer(server) {
+ server.middlewares.use((req, res, next) => {
+ if (req.url !== '/__text-cache-benchmark') return next();
+ server.transformIndexHtml(req.url, '<html lang="zh"><head><meta charset="utf-8"><title>文字缓存 CPU 对照</title></head><body><main id="root"></main><script type="module" src="/tools/ui-text-cache-benchmark.ts"></script></body></html>')
+ .then(html => { res.setHeader('Content-Type', 'text/html'); res.end(html); });
+ });
+ } }],
+});
+await server.listen();
+console.log('Text cache CPU benchmark: http://127.0.0.1:5196/__text-cache-benchmark');
diff --git a/tools/ui-text-cache-benchmark.ts b/tools/ui-text-cache-benchmark.ts
new file mode 100644
index 000000000..500a5f660
--- /dev/null
+++ b/tools/ui-text-cache-benchmark.ts
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: Apache-2.0
+import { setPlatform, webAdapter } from '../sdk/src/platform';
+import { CanvasGlyphRasterizer } from '../sdk/src/ui/text/glyph-rasterizer';
+import { GlyphAtlas } from '../sdk/src/ui/text/glyph-atlas';
+import { SdfTextRenderer, type DrawTextParams } from '../sdk/src/ui/text/text-renderer';
+import { setNativeTextSubmit } from '../sdk/src/ui/text/submit';
+
+setPlatform(webAdapter);
+const root = document.getElementById('root')!;
+root.innerHTML = `<style>
+body{margin:0;background:#15181e;color:#e3e8ef;font:14px system-ui}main{max-width:1050px;margin:auto;padding:28px}
+h1{font-size:22px}p{line-height:1.7;color:#bac3d1}button{padding:9px 18px;background:#307ed4;color:white;border:0;border-radius:6px;cursor:pointer}
+button:disabled{opacity:.5}table{border-collapse:collapse;width:100%;margin-top:22px}th,td{text-align:left;padding:12px;border-bottom:1px solid #333d4d}
+th{color:#9db2cc}details{margin-top:24px}pre{white-space:pre-wrap;word-break:break-all;font-size:11px}
+</style><h1>2D 文字缓存 · CPU 对照</h1>
+<p>同一浏览器、同一批 200 个中英文标签。比较缓存开启与每帧清空布局缓存;字形图集在计时前预热。
+每项 10 轮 × 10 帧,交替执行顺序。表中统计的是每批平均帧耗时的中位数/P95,非单帧尾延迟。
+计时包含缓存键、布局与几何、提交接口;不包含 GPU、WASM 拷贝或 Yoga 重排。</p>
+<button id="run">运行对照</button><p id="status" role="status">等待运行</p>
+<table><thead><tr><th>更新比例</th><th>每帧重建 批均帧中位 / P95 ms</th><th>缓存开启 批均帧中位 / P95 ms</th><th>中位比值</th><th>几何一致</th></tr></thead><tbody id="rows"></tbody></table>
+<details><summary>原始数据与运行环境</summary><pre id="raw"></pre></details>`;
+const run = document.getElementById('run') as HTMLButtonElement;
+const status = document.getElementById('status')!;
+const labels = 200, rounds = 10, frames = 10;
+const transform = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+const empty = new Set<number>();
+const tick = () => new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
+const percentile = (values: number[], p: number) => [...values].sort((a, b) => a - b)[Math.ceil(values.length * p) - 1];
+
+function harness() {
+ let page = 0;
+ // Actual Canvas rasterization and SDK atlas/layout/cache; in-memory page store
+ // deliberately excludes GPU uploads. Never install this sink in a game realm.
+ const atlas = new GlyphAtlas(new CanvasGlyphRasterizer(null, { sdf: false, renderSize: 24 }),
+ { createPage: () => ++page, uploadSubRegion: () => {} }, { sdf: false, pageSize: 1024 });
+ const renderer = Object.assign(Object.create(SdfTextRenderer.prototype), {
+ atlas, sdf: false, module: null, cache_: new Map(),
+ }) as SdfTextRenderer;
+ const params = Array.from({ length: labels }, (_, i): DrawTextParams => ({
+ text: `设置 Settings ${i} 音量 Volume 0123456789`, fontFamily: 'Arial', fontSizePx: 24,
+ color: [1, 1, 1, 1], boxWidth: 320, boxHeight: 64, maxWidth: 320,
+ }));
+ return { renderer, params };
+}
+
+run.onclick = async () => {
+ run.disabled = true;
+ document.getElementById('rows')!.replaceChildren();
+ const results: unknown[] = [];
+ const cached = harness(), rebuilt = harness();
+ let submissions = 0, vertices = 0;
+ setNativeTextSubmit((_v, count) => { submissions++; vertices += count; });
+ const draw = (h: ReturnType<typeof harness>, changed: number, frame: number, clear: boolean) => {
+ if (clear) h.renderer.retainOnly(empty);
+ for (let i = 0; i < labels; i++) {
+ const base = h.params[i];
+ h.renderer.drawText(i < changed ? { ...base, text: `${base.text} ${frame % 2}` } : base, transform, i, 0, 0);
+ }
+ };
+ try {
+ await document.fonts.ready;
+ for (const rate of [0, 0.01, 0.1, 1]) {
+ status.textContent = `正在测量 ${rate * 100}% 标签更新…`;
+ const changed = Math.round(labels * rate);
+ // Prewarm both text variants and JIT before collecting paired samples.
+ for (let f = 0; f < 10; f++) { draw(cached, changed, f, false); draw(rebuilt, changed, f, true); }
+ const samples = { cached: [] as number[], rebuilt: [] as number[] };
+ for (let round = 0; round < rounds; round++) {
+ await tick();
+ for (const kind of round % 2 ? ['cached', 'rebuilt'] as const : ['rebuilt', 'cached'] as const) {
+ const start = performance.now();
+ for (let f = 0; f < frames; f++) draw(kind === 'cached' ? cached : rebuilt, changed, f, kind === 'rebuilt');
+ samples[kind].push((performance.now() - start) / frames);
+ }
+ }
+ // Exact geometry comparison outside timing, including every vertex/index.
+ const capture = (h: ReturnType<typeof harness>, clear: boolean) => {
+ const batches: unknown[] = [];
+ setNativeTextSubmit((v, count, indices, _texture, _transform, entity) => batches.push({ entity, count,
+ vertices: Array.from(v), indices: Array.from(indices) }));
+ draw(h, changed, 1, clear);
+ return JSON.stringify(batches);
+ };
+ const equal = capture(cached, false) === capture(rebuilt, true);
+ setNativeTextSubmit((_v, count) => { submissions++; vertices += count; });
+ if (!equal) throw Error('Cached and rebuilt geometry differ');
+ const c = percentile(samples.cached, .5), b = percentile(samples.rebuilt, .5);
+ results.push({ rate, samples, cachedMedian: c, rebuiltMedian: b, geometryEqual: equal });
+ const row = document.createElement('tr');
+ row.innerHTML = `<td>${rate * 100}% (${changed}/${labels})</td><td>${b.toFixed(3)} / ${percentile(samples.rebuilt, .95).toFixed(3)}</td><td>${c.toFixed(3)} / ${percentile(samples.cached, .95).toFixed(3)}</td><td>${(b / c).toFixed(2)}×</td><td>通过</td>`;
+ document.getElementById('rows')!.append(row);
+ }
+ document.getElementById('raw')!.textContent = JSON.stringify({ schema: 1, labels, rounds, frames,
+ userAgent: navigator.userAgent, hardwareConcurrency: navigator.hardwareConcurrency, dpr: devicePixelRatio,
+ date: new Date().toISOString(), submissions, vertices, results, statistic: 'median and nearest-rank P95 of 10 batch-average frame times',
+ scope: 'CPU geometry/cache only; warm Canvas bitmap atlas; no GPU/WASM/Yoga; not historical before/after or device acceptance' }, null, 2);
+ status.textContent = '完成:4 项几何对照一致。性能数字仅适用于本次环境,无自动速度门槛。';
+ } catch (error) { status.textContent = `失败:${String(error)}`; }
+ finally { setNativeTextSubmit(null); run.disabled = false; }
+};