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.

perf(ui): the engine watches the world scale an automatic label picks its glyph pipeline from

yhh03957b9a4605
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 17ea02d0b..6b874f124 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -47,6 +47,7 @@ published separately; it ships inside the editor.
### Changed
+- **A label's glyph pipeline no longer costs a transform read per label per frame.** An automatic label draws with hinted bitmaps near 1:1 and with SDF past 2% of it, so script read every label's world scale every frame to see whether the choice had changed, a `Transform` converted through embind each time: about two thirds of what the script still spent on 600 static labels. The engine now holds the choice it was laid out with and watches the scale itself in `renderer_retainedTextStale`, by the same rule (pinned by one table on each side). 600 static labels go from 1.6 ms to 1.1 ms of CPU a frame, and the script's own per-frame loop to about 0.05 ms. Evaluated and not taken: driving the check from the change tracker (a script component written in place through `world.get` is not reported, and that is documented and tested behaviour), and making `Text` an engine component (an in-place write to one is dropped, which would end that behaviour for user code).
- **UI text is laid out when it changes and submitted by the engine every frame, instead of handed over by script every frame.** Every label cost script an embind round trip for each of its domain, hidden state, opacity, matrix, size, order and cull bit, a JSON signature to find out nothing had changed, and a copy of its quads into the engine: 4.3 microseconds a label, which is 2.7 ms a frame for 600 labels that never change. The glyph quads are now handed to the engine once, in `renderer_retainedTextBegin/Batch`, and the engine reads everything else off the entity itself, clips against the view as the script did, and submits them (`renderer_retainedTextSubmit`). Script compares the fields a label was laid out from and lays it out again only when one differs; the engine reports the labels whose box was resized or that moved between the world and the screen (`renderer_retainedTextStale`). 600 static labels go from 2.7 ms to 1.6 ms of CPU a frame, with the same draws and triangles, and a pixel-identical picture once the page has settled. A host without the new entry points keeps the old path. The engine's culling and the script's are checked quad for quad on 120 random cases (`test_retained_text`).
- **A frame of 2D sprites is not sorted again when its draw keys are the last frame's.** The draw list sorted every command each frame, 0.15 ms for 4,000 sprites and growing as n log n, although a 2D key holds the layer, shader, blend and material and no position: sprites that move, or do not, give the same keys frame after frame. The order is a function of the key sequence alone (ties break on emit index), so a frame with the same keys takes the last frame's order and skips the sort. The draw list's finalize in a 4,000-sprite scene goes from 0.30 ms to 0.10 ms. The sort result is the same bit for bit; a frame whose keys differ is sorted as before.
- **The sky's clouds are worked out at a quarter of the size, 0.9 ms cheaper.** The cloud layer marches sixteen steps a pixel, each with three octaves of noise and three more samples toward the sun, and the surfaces' shadow from it costs almost nothing: all of the 1.6 ms of the `sky_clouds` pass in the terrain-water example was the layer over the sky. The clouds are smooth, so the pass now runs at a quarter of the width and height (half before) and the composite reads it back as it did. In a cloud scene no pixel is more than 2 of 255 from the half-size picture; in the example the difference is below what two runs of the same build differ by. 1.6 ms to 0.7 ms of a 1080p frame.
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index 2ba7abefc..38ab05a89 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -208,7 +208,7 @@ export interface NativeEngineApi {
renderer_replayToDrawCall?(drawCallIndex: number): void;
renderer_resize?(width: number, height: number): void;
renderer_retainedTextBatch?(entity: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, pageId: number): void;
- renderer_retainedTextBegin?(entity: number, sdf: number, screen: number, hasBox: number, layer: number, boxWidth: number, boxHeight: number): void;
+ renderer_retainedTextBegin?(entity: number, sdf: number, screen: number, hasBox: number, layer: number, boxWidth: number, boxHeight: number, autoKind: number): void;
renderer_retainedTextClear?(entity: number): void;
renderer_retainedTextStale?(registry: unknown, outPtr: number, capacity: number): number;
renderer_retainedTextSubmit?(registry: unknown, screen: number, projectionPtr: number): void;
diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.ts
index b9de310f4..d96094635 100644
--- a/sdk/src/ui/text/plugin.ts
+++ b/sdk/src/ui/text/plugin.ts
@@ -82,7 +82,7 @@ export function glyphContentScale(projScaleX: number, vpW: number, dpr: number):
/** The Text fields a retained label's geometry was laid out from; a label is rebuilt when any of them differs, and not otherwise. */
export interface TextSnapshot {
- content: string; family: string; fontSize: number; bold: boolean; italic: boolean; richText: boolean;
+ content: string; family: string; fontSize: number; bold: boolean; italic: boolean; richText: boolean; renderMode: number;
align: number; verticalAlign: number; wordWrap: boolean; overflow: number; lineHeight: number; layer: number;
cr: number; cg: number; cb: number; ca: number;
strokeWidth: number; sr: number; sg: number; sb: number; sa: number;
@@ -93,14 +93,13 @@ export interface TextSnapshot {
interface RetainedLabel {
snap: TextSnapshot;
screen: boolean;
- kind: 'bitmap' | 'sdf';
gen: number;
renderer: SdfTextRenderer;
}
export function snapshotOf(t: TextData, family: string): TextSnapshot {
return {
- content: t.content, family, fontSize: t.fontSize, bold: !!t.bold, italic: !!t.italic, richText: !!t.richText,
+ content: t.content, family, fontSize: t.fontSize, bold: !!t.bold, italic: !!t.italic, richText: !!t.richText, renderMode: t.renderMode,
align: t.align, verticalAlign: t.verticalAlign, wordWrap: !!t.wordWrap, overflow: t.overflow, lineHeight: t.lineHeight, layer: t.layer | 0,
cr: t.color.r, cg: t.color.g, cb: t.color.b, ca: t.color.a,
strokeWidth: t.strokeWidth, sr: t.strokeColor.r, sg: t.strokeColor.g, sb: t.strokeColor.b, sa: t.strokeColor.a,
@@ -111,7 +110,7 @@ export function snapshotOf(t: TextData, family: string): TextSnapshot {
export function sameSnapshot(s: TextSnapshot, t: TextData, family: string): boolean {
return s.content === t.content && s.family === family && s.fontSize === t.fontSize
- && s.bold === !!t.bold && s.italic === !!t.italic && s.richText === !!t.richText
+ && s.bold === !!t.bold && s.italic === !!t.italic && s.richText === !!t.richText && s.renderMode === t.renderMode
&& s.align === t.align && s.verticalAlign === t.verticalAlign && s.wordWrap === !!t.wordWrap
&& s.overflow === t.overflow && s.lineHeight === t.lineHeight && s.layer === (t.layer | 0)
&& s.cr === t.color.r && s.cg === t.color.g && s.cb === t.color.b && s.ca === t.color.a
@@ -289,11 +288,10 @@ export class TextPlugin implements Plugin {
if (!t.content || t.enabled === false) continue; // not seen: swept below
if (!label && api.ui_isScreenDomain!(registry, entity as number) !== screen) continue;
const family = resolveTextFamily(t.font, t.fontFamily);
- const kind = t.renderMode === TextRenderMode.Bitmap ? 'bitmap'
- : t.renderMode === TextRenderMode.Sdf ? 'sdf'
- : resolveTextRenderMode(t.renderMode, (world.get(entity, Transform) as TransformData).worldScale.x);
seen.add(entity as number);
- if (label && label.kind === kind && label.gen === label.renderer.atlas.generation && sameSnapshot(label.snap, t, family)) {
+ // Which glyph pipeline an automatic label gets follows its world scale, which the engine watches (renderer_retainedTextStale): the
+ // transform is not read here every frame for every label to find out.
+ if (label && label.gen === label.renderer.atlas.generation && sameSnapshot(label.snap, t, family)) {
label.renderer.markDrawn(entity as number);
continue;
}
@@ -421,8 +419,9 @@ export class TextPlugin implements Plugin {
outline,
},
entity as number, screen, hasBox, t.layer | 0, w, h,
+ t.renderMode !== TextRenderMode.Bitmap && t.renderMode !== TextRenderMode.Sdf,
);
- appState.retained.set(entity as number, { snap: snapshotOf(t, family), screen, kind, gen: renderer.atlas.generation, renderer });
+ appState.retained.set(entity as number, { snap: snapshotOf(t, family), screen, gen: renderer.atlas.generation, renderer });
}
private drawDomainWithMatrix(app: App, screen: boolean, readMatrix?: (entity: number) => boolean, projection?: Float32Array): void {
diff --git a/sdk/src/ui/text/text-renderer.ts b/sdk/src/ui/text/text-renderer.ts
index 651e7e8e2..a336e6a08 100644
--- a/sdk/src/ui/text/text-renderer.ts
+++ b/sdk/src/ui/text/text-renderer.ts
@@ -401,12 +401,12 @@ export class SdfTextRenderer {
*/
retain(
api: EngineApi, p: DrawTextParams, entity: number,
- screen: boolean, hasBox: boolean, layer: number, boxWidth: number, boxHeight: number,
+ screen: boolean, hasBox: boolean, layer: number, boxWidth: number, boxHeight: number, autoKind: boolean,
): void {
if (this.atlas.metricsOnly) throw new Error('Measurement atlases cannot submit text.');
const batches: Array<{ vertices: Float32Array; indices: Uint16Array; pageId: number }> = [];
drawTextWith(this.atlas, (vertices, indices, pageId) => { batches.push({ vertices, indices, pageId }); }, { ...p, opacity: 1 });
- api.renderer_retainedTextBegin!(entity, this.sdf ? 1 : 0, screen ? 1 : 0, hasBox ? 1 : 0, layer, boxWidth, boxHeight);
+ api.renderer_retainedTextBegin!(entity, this.sdf ? 1 : 0, screen ? 1 : 0, hasBox ? 1 : 0, layer, boxWidth, boxHeight, autoKind ? 1 : 0);
for (const b of batches) {
const vertexCount = (b.vertices.length / TEXT_VERTEX_FLOATS) | 0;
if (vertexCount <= 0 || b.indices.length <= 0) continue;
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index e0c33ebe3..7beb7c658 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -441,7 +441,7 @@ export interface ESEngineModule {
* domain or box no longer matches what they were laid out for, and `Submit` draws one domain's labels into the open list.
*/
renderer_retainedTextBegin?(
- entity: number, sdf: number, screen: number, hasBox: number, layer: number, boxWidth: number, boxHeight: number
+ entity: number, sdf: number, screen: number, hasBox: number, layer: number, boxWidth: number, boxHeight: number, autoKind: number
): void;
renderer_retainedTextBatch?(
entity: number, verticesPtr: number, vertexCount: number,
diff --git a/sdk/tests/ui-text-retained.test.ts b/sdk/tests/ui-text-retained.test.ts
index 10a46c0f5..7ef3a72f4 100644
--- a/sdk/tests/ui-text-retained.test.ts
+++ b/sdk/tests/ui-text-retained.test.ts
@@ -8,7 +8,7 @@
import { describe, expect, it, vi } from 'vitest';
import { GlyphAtlas } from '../src/ui/text/glyph-atlas';
import { SdfTextRenderer, drawTextWith, type DrawTextParams } from '../src/ui/text/text-renderer';
-import { sameSnapshot, snapshotOf } from '../src/ui/text/plugin';
+import { resolveTextRenderMode, sameSnapshot, snapshotOf } from '../src/ui/text/plugin';
import type { TextData } from '../src/ui/core/text';
import type { EngineApi } from '../src/ecs/bridge/engineApi';
import { TEXT_VERTEX_FLOATS } from '../src/ui/text/submit';
@@ -49,11 +49,12 @@ describe('which Text fields make a retained label laid out again', () => {
['shadowOffsetX', t => { t.shadowOffsetX = 2; }],
['shadowOffsetY', t => { t.shadowOffsetY = 2; }],
['richText', t => { t.richText = true; }],
+ ['renderMode', t => { t.renderMode = 1; }],
['layer', t => { t.layer = 3; }],
];
- // font is resolved to the family and compared as that; renderMode picks the glyph pipeline, compared as `kind`; enabled and an empty
- // content decide whether the label exists at all; i18nKey only ever changes `content`.
- const elsewhere = ['font', 'renderMode', 'enabled', 'i18nKey'];
+ // font is resolved to the family and compared as that; enabled and an empty content decide whether the label exists at all; i18nKey only
+ // ever changes `content`.
+ const elsewhere = ['font', 'enabled', 'i18nKey'];
it('accounts for every field of the component', () => {
const all = Object.keys(freshText()).sort();
@@ -75,6 +76,15 @@ describe('which Text fields make a retained label laid out again', () => {
});
});
+describe('the glyph pipeline an automatic label gets', () => {
+ // The engine decides it from the world scale (RetainedText.hpp, retainedTextAutoIsSdf) and this table is pinned there too: float32 values,
+ // as the engine holds them.
+ const table: Array<[number, 'bitmap' | 'sdf']> = [[1.0, 'bitmap'], [1.02, 'bitmap'], [0.98, 'bitmap'], [1.021, 'sdf'], [0.97, 'sdf'], [2.0, 'sdf'], [0.5, 'sdf'], [0.0, 'bitmap'], [-1.0, 'bitmap'], [Infinity, 'bitmap'], [NaN, 'bitmap']];
+ it.each(table)('scale %s draws with %s', (scale, kind) => {
+ expect(resolveTextRenderMode(undefined, Math.fround(scale))).toBe(kind);
+ });
+});
+
describe('handing a label to the engine', () => {
function engine() {
const heap = new Uint8Array(1 << 20);
@@ -117,8 +127,8 @@ describe('handing a label to the engine', () => {
const atlas = makeAtlas();
const renderer = rendererWith(atlas);
const { api, batches, calls } = engine();
- renderer.retain(api, params, 42, true, true, 7, 120, 30);
- expect(calls[0]).toBe('begin 42,0,1,1,7,120,30');
+ renderer.retain(api, params, 42, true, true, 7, 120, 30, true);
+ expect(calls[0]).toBe('begin 42,0,1,1,7,120,30,1');
const expected: Array<{ v: number[]; i: number[]; page: number }> = [];
drawTextWith(atlas, (v, i, page) => expected.push({ v: Array.from(v), i: Array.from(i), page }), { ...params, opacity: 1 });
expect(batches.map(b => ({ v: b.vertices, i: b.indices, page: b.pageId }))).toEqual(expected);
@@ -130,7 +140,7 @@ describe('handing a label to the engine', () => {
const renderer = rendererWith(atlas);
const retain = vi.spyOn(atlas, 'retainPages');
const { api, batches } = engine();
- renderer.retain(api, params, 5, false, false, 0, 0, 0);
+ renderer.retain(api, params, 5, false, false, 0, 0, 0, false);
const pages = new Set(batches.map(b => b.pageId));
expect(pages.size).toBeGreaterThan(0);
// Frames that do not draw it again (an Update with no render, a frame the label is unchanged) must not release its pages.
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index c13ef5cd2..a04f96d73 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -200,10 +200,10 @@ void renderer_submitTextBatch(
}
void renderer_retainedTextBegin(
- u32 entity, i32 sdf, i32 screen, i32 hasBox, i32 layer, f32 boxWidth, f32 boxHeight
+ u32 entity, i32 sdf, i32 screen, i32 hasBox, i32 layer, f32 boxWidth, f32 boxHeight, i32 autoKind
) {
if (!g_initialized || !g_renderFrame) return;
- g_renderFrame->retainedText().begin(entity, sdf != 0, screen != 0, hasBox != 0, layer, boxWidth, boxHeight);
+ g_renderFrame->retainedText().begin(entity, sdf != 0, screen != 0, hasBox != 0, layer, boxWidth, boxHeight, autoKind != 0);
}
void renderer_retainedTextBatch(
@@ -241,9 +241,15 @@ i32 renderer_retainedTextStale(ecs::Registry& registry, uintptr_t outPtr, i32 ca
const f32 width = node ? node->computed_size_.x : 0.0f;
const f32 height = node ? node->computed_size_.y : 0.0f;
const bool screen = ui && ui->isScreenDomain(registry, it->first);
- if ((width != text.boxWidth || height != text.boxHeight || screen != text.screen) && written < capacity) {
- out[written++] = it->first;
+ bool stale = width != text.boxWidth || height != text.boxHeight || screen != text.screen;
+ if (!stale && text.autoKind) {
+ // The pipeline was chosen from the world scale: the script no longer reads the transform every frame to see whether it moved.
+ if (auto* transform = registry.tryGet<ecs::Transform>(entity)) {
+ transform->ensureDecomposed();
+ stale = retainedTextAutoIsSdf(transform->worldScale.x) != text.sdf;
+ }
}
+ if (stale && written < capacity) out[written++] = it->first;
++it;
}
return written;
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index ab67e69c1..3636ddfd2 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -97,9 +97,10 @@ void renderer_submitTextBatch(
* @brief Glyph quads handed over once and submitted by the engine each frame (see RetainedText.hpp).
* @{
*/
-/// Starts (or replaces) an entity's retained text: the layout's domain, box and order, with its batches to follow.
+/// Starts (or replaces) an entity's retained text: the layout's domain, box and order, with its batches to follow. @p autoKind says the glyph
+/// pipeline (@p sdf) was picked from the entity's world scale, which the engine then watches in place of the script.
void renderer_retainedTextBegin(
- u32 entity, i32 sdf, i32 screen, i32 hasBox, i32 layer, f32 boxWidth, f32 boxHeight
+ u32 entity, i32 sdf, i32 screen, i32 hasBox, i32 layer, f32 boxWidth, f32 boxHeight, i32 autoKind
);
/// One batch of glyph quads of the entity begun last: TEXT_VERTEX_FLOATS floats a vertex, whole quads, drawn from atlas page @p pageId.
void renderer_retainedTextBatch(
@@ -110,7 +111,7 @@ void renderer_retainedTextBatch(
void renderer_retainedTextClear(u32 entity);
/**
* @brief The entities whose retained text no longer matches the world, written to @p outPtr as u32s.
- * @details Stale means the entity's domain or box is not the one it was laid out for. An entity that is gone is dropped here and not reported.
+ * @details Stale means the entity's domain or box is not the one it was laid out for, or its world scale now picks the other glyph pipeline. An entity that is gone is dropped here and not reported.
* @return How many were written, at most @p capacity.
*/
i32 renderer_retainedTextStale(ecs::Registry& registry, uintptr_t outPtr, i32 capacity);
diff --git a/src/esengine/renderer/draw/RetainedText.hpp b/src/esengine/renderer/draw/RetainedText.hpp
index e2c8c58cd..9c24b9777 100644
--- a/src/esengine/renderer/draw/RetainedText.hpp
+++ b/src/esengine/renderer/draw/RetainedText.hpp
@@ -38,6 +38,7 @@ struct RetainedText {
bool sdf = false;
bool screen = false; ///< The domain the geometry was laid out for.
bool hasBox = false; ///< Laid out in a UINode box, so ordered by the UI tree rather than by `layer`.
+ bool autoKind = false; ///< The glyph pipeline was chosen from the entity's world scale, so a changed scale can change it.
i32 layer = 0; ///< Text.layer, for a label with no box.
f32 boxWidth = 0.0f; ///< The box the layout used: a label whose box has since changed is stale.
f32 boxHeight = 0.0f;
@@ -47,12 +48,13 @@ struct RetainedText {
class RetainedTextStore {
public:
/// Replaces any geometry the entity held, with none yet: batches follow through add().
- void begin(u32 entity, bool sdf, bool screen, bool hasBox, i32 layer, f32 boxWidth, f32 boxHeight) {
+ void begin(u32 entity, bool sdf, bool screen, bool hasBox, i32 layer, f32 boxWidth, f32 boxHeight, bool autoKind = false) {
RetainedText& text = entries_[entity];
text = RetainedText{};
text.sdf = sdf;
text.screen = screen;
text.hasBox = hasBox;
+ text.autoKind = autoKind;
text.layer = layer;
text.boxWidth = boxWidth;
text.boxHeight = boxHeight;
@@ -95,6 +97,15 @@ private:
std::map<u32, RetainedText> entries_;
};
+/// Which glyph pipeline a label of automatic render mode draws with at a world scale: hinted bitmaps while the scale is within 2% of 1:1, SDF past
+/// it. The same rule, in the same precision, as resolveTextRenderMode in sdk/src/ui/text/plugin.ts. True for SDF.
+inline bool retainedTextAutoIsSdf(f32 worldScaleX) {
+ constexpr double BITMAP_SCALE_EPSILON = 0.02;
+ const double scale = worldScaleX;
+ if (!std::isfinite(scale) || scale <= 0.0) return false;
+ return std::abs(scale - 1.0) > BITMAP_SCALE_EPSILON;
+}
+
// ---- Clipping a label's quads against a view ------------------------------------------------------------------------------------------------
// The same arithmetic, in the same precision, as sdk/src/ui/text/text-culling.ts, which the unretained path still runs: the two must agree on
// which quads a view keeps.
diff --git a/tests/renderer/test_retained_text.cpp b/tests/renderer/test_retained_text.cpp
index d116c8d2b..dcfe0db8a 100644
--- a/tests/renderer/test_retained_text.cpp
+++ b/tests/renderer/test_retained_text.cpp
@@ -115,6 +115,24 @@ int main(int argc, char** argv) {
}
++cases;
}
+ // Which glyph pipeline an automatic label gets at a world scale: the same table is pinned on the script side (ui-text-retained.test.ts).
+ {
+ const struct { f32 scale; bool sdf; } table[] = {
+ {1.0f, false},
+ {1.02f, false},
+ {0.98f, false},
+ {1.021f, true},
+ {0.97f, true},
+ {2.0f, true},
+ {0.5f, true},
+ {0.0f, false},
+ {-1.0f, false},
+ {INFINITY, false}, {NAN, false}
+ };
+ bool same = true;
+ for (const auto& row : table) same = same && retainedTextAutoIsSdf(row.scale) == row.sdf;
+ CHECK(same, "the automatic glyph pipeline follows the world scale as the script says");
+ }
CHECK(cases >= 100, "the cases file has its cases");
CHECK(none > 0 && all > 0 && subset > 0, "the cases cover nothing, all and some");
std::printf("%d cases: %d none, %d all, %d some quads kept\n", cases, none, all, subset);
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index d573ce4e1..e67201e9b 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3082,4 +3082,6 @@ export const NOTED = {
{"note":"A frame of sprites is not sorted again when its draw keys have not changed"},
"perf(ui): UI text is laid out when it changes and submitted by the engine every frame":
{"note":"UI text costs less: labels are laid out when they change and submitted by the engine"},
+ "perf(ui): the engine watches the world scale an automatic label picks its glyph pipeline from":
+ {"note":"UI text costs a third less again"},
};