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
fix(text): world text under a perspective camera draws as SDF, and no bitmap glyph is rasterized past half an atlas page
yhhf6f55a4a389e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a71121f14..ce5703332 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ published separately; it ships inside the editor.### Fixed+- **World text under a perspective camera no longer eats the memory.** A `Text` left on `renderMode: Auto` in world space, seen through a perspective camera, was rasterized as if the camera were orthographic: a 32 px label asked for glyphs tens of thousands of pixels high. On a phone the native heap swung between 2.4 and 4.2 GB and the game drew about one frame in two seconds. Auto now draws world text under a perspective camera as SDF, since no single bitmap size lands 1:1 at every depth; the same eight floating labels hold the heap at about 45 MB and 60 fps. A bitmap glyph is also never rasterized larger than half an atlas page (512 px), which also covers an orthographic camera zoomed far in and a forced `Bitmap`; past that it is drawn from 512 px and the log says so once.- **Sound comes back when a device's audio dies on its own.** On the Android and iOS hosts, a game whose audio device did not start again on returning from the background, or whose output stream was dropped while it was away, stayed silent until it was restarted. The host now checks every frame that the device is still taking sound while the game wants it; after half a second of nothing it restarts the device, and from the third try rebuilds it, retrying at growing intervals of up to 5 seconds. Sounds that were playing carry on where they were, and the log says each time it acts.- **A render target works on a native device.** On the Android and iOS hosts `RenderTexture.create` handed back 0 for its handle and its texture, so a camera's `renderTarget` and anything painted into a texture drew nothing, and nothing was logged. The SDK asked only the web's engine module for a target; it now asks whichever engine core is running, and a device names the target's texture for a `Sprite` as the web does. A target that cannot be made is now reported once in the log.- **A `#pragma lighting direct` surface takes a sun's shadow.** Under a directional light with a size (any `sourceAngle` above 0, the default 0.53 included) such a shader drew no shadow at all; it now draws the hard shadow the directive promises.diff --git a/docs/astro/src/content/docs/ui/text.mdx b/docs/astro/src/content/docs/ui/text.mdxindex a77894ec0..9507757d5 100644--- a/docs/astro/src/content/docs/ui/text.mdx+++ b/docs/astro/src/content/docs/ui/text.mdx@@ -41,7 +41,9 @@ Every glyph is rasterized once into a shared atlas and drawn as textured quads.- **`Auto`** (default) — bitmap while the entity's own world scale is 1 (within±2%; the canvas fit is already compensated in the bitmap path), SDF the momentthe entity scales. DOM-crisp static UI *and* zoom-stable animated text with no- configuration.+ configuration. Under a perspective camera world text is always SDF: a world+ unit covers a different number of pixels at every depth, so there is no size a+ bitmap glyph could be drawn at to land 1:1.So a pulsing "LEVEL UP!" banner needs nothing special — `Auto` switches it toSDF while it scales:@@ -62,9 +64,11 @@ const pulseBanner = defineSystem([Query(Mut(Transform), Text), Res(Time)], (q, t});```-Force `Sdf` when text is *born* scaled or lives in world space at arbitrary-camera zoom; force `Bitmap` when you know the text never scales and want-hinting even under tiny per-frame scale noise.+Force `Sdf` when text is *born* scaled or lives in world space under an+orthographic camera that zooms freely; force `Bitmap` when you know the text+never scales and want hinting even under tiny per-frame scale noise. A bitmap+glyph is never rasterized larger than half an atlas page (512 px): past that it+is drawn from 512 px and the log says once that the text reads better as `Sdf`.## `Text` propertiesdiff --git a/docs/astro/src/content/docs/zh-cn/ui/text.mdx b/docs/astro/src/content/docs/zh-cn/ui/text.mdxindex 84e7fa546..81c4e5c3c 100644--- a/docs/astro/src/content/docs/zh-cn/ui/text.mdx+++ b/docs/astro/src/content/docs/zh-cn/ui/text.mdx@@ -37,7 +37,8 @@ addStartupSystem(buildHud);会糊或闪。- **`Auto`**(默认)—— 实体自身世界缩放为 1 时(±2% 以内;画布适配已在位图路径中补偿)用位图,一旦实体缩放立即切 SDF。静态 UI 如 DOM 般锐利,动画文本缩放- 稳定,零配置。+ 稳定,零配置。透视相机下的世界文本一律用 SDF:每个深度上一个世界单位占的像素都+ 不同,不存在一个能让位图字形 1:1 落到屏幕上的尺寸。所以一个脉动的 "LEVEL UP!" 横幅什么都不用设——`Auto` 会在它缩放时切到 SDF:@@ -57,8 +58,9 @@ const pulseBanner = defineSystem([Query(Mut(Transform), Text), Res(Time)], (q, t});```-文本*生来*就带缩放、或活在任意相机变焦的世界空间时,强制 `Sdf`;确定文本永不-缩放、且想在微小的逐帧缩放噪声下也保住 hinting 时,强制 `Bitmap`。+文本*生来*就带缩放、或活在可以随意变焦的正交相机下的世界空间时,强制 `Sdf`;确定文本永不+缩放、且想在微小的逐帧缩放噪声下也保住 hinting 时,强制 `Bitmap`。位图字形的栅格化尺寸+不会超过图集页的一半(512 像素):超过时按 512 像素绘制,并在日志里提示一次改用 `Sdf` 更清晰。## `Text` 属性diff --git a/sdk/src/ui/text/glyph-atlas.ts b/sdk/src/ui/text/glyph-atlas.tsindex 6d60a81f1..f778de014 100644--- a/sdk/src/ui/text/glyph-atlas.ts+++ b/sdk/src/ui/text/glyph-atlas.ts@@ -307,11 +307,19 @@ export class GlyphAtlas {// A bitmap font has one size: the one it was drawn at, which the layout scales from.const bitmap = fontFamily === undefined ? null : bitmapFontOf(fontFamily);if (bitmap) return bitmap.size;- return this.sdf- ? this.renderSize- : Math.max(1, Math.round(displaySize * this.dpr * this.contentScale_));+ if (this.sdf) return this.renderSize;+ const wanted = Math.max(1, Math.round(displaySize * this.dpr * this.contentScale_));+ const cap = this.pageSize >> 1;+ if (wanted <= cap) return wanted;+ if (!this.warnedOversize_) {+ this.warnedOversize_ = true;+ log.warn('text', `A bitmap glyph asked for ${wanted} px, more than an atlas page holds; drawn from ${cap} px. Text this large on screen reads better with renderMode Sdf.`);+ }+ return cap;}+ private warnedOversize_ = false;+/** Reported families with non-drawable glyphs still in the bounded CPU cache. */private readonly mute_ = new Set<string>();diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.tsindex 44a0304a9..38b74e019 100644--- a/sdk/src/ui/text/plugin.ts+++ b/sdk/src/ui/text/plugin.ts@@ -54,9 +54,11 @@ const BITMAP_SCALE_EPSILON = 0.02;export function resolveTextRenderMode(mode: TextRenderMode | undefined,effectiveScale: number,+ perspective = false,): 'bitmap' | 'sdf' {if (mode === TextRenderMode.Bitmap) return 'bitmap';if (mode === TextRenderMode.Sdf) return 'sdf';+ if (perspective) return 'sdf';if (!Number.isFinite(effectiveScale) || effectiveScale <= 0) return 'bitmap';return Math.abs(effectiveScale - 1) <= BITMAP_SCALE_EPSILON ? 'bitmap' : 'sdf';}@@ -77,6 +79,28 @@ export function resolveTextRenderMode(* @param projScaleX element 0 of the projection: 2 / the span it shows.* @param vpW the pixel width that span lands in.*/+export function projectionIsPerspective(viewProjection: ArrayLike<number> | undefined): boolean {+ if (!viewProjection || viewProjection.length < 16) return false;+ return Math.abs(viewProjection[3]) + Math.abs(viewProjection[7]) + Math.abs(viewProjection[11]) > 1e-6;+}++export interface DomainView {+ contentScale: number;+ perspective: boolean;+}++const FLAT_VIEW: DomainView = { contentScale: 1, perspective: false };++export function domainViewOf(viewProjection: ArrayLike<number> | undefined, vpW: number, dpr: number): DomainView {+ if (projectionIsPerspective(viewProjection)) return { contentScale: 1, perspective: true };+ return { contentScale: glyphContentScale(viewProjection?.[0] ?? 0, vpW, dpr), perspective: false };+}++export function glyphKind(t: Pick<TextData, 'renderMode'>, tr: Pick<TransformData, 'worldScale'>, family: string, view: DomainView): 'bitmap' | 'sdf' {+ if (bitmapFontOf(family)) return 'bitmap';+ return resolveTextRenderMode(t.renderMode, tr.worldScale.x, view.perspective);+}+export function glyphContentScale(projScaleX: number, vpW: number, dpr: number): number {if (!(dpr > 0) || !(vpW > 0)) return 1;if (!Number.isFinite(projScaleX) || projScaleX === 0) return 1;@@ -317,7 +341,7 @@ export class TextPlugin implements Plugin {const world = app.world;const registry = world.getCppRegistry() as CppRegistry;const dpr = platformDevicePixelRatio();- const contentScale = screen ? this.screenContentScale(app, dpr) : this.worldContentScale(app, dpr);+ const contentScale = this.domainView(app, screen, dpr).contentScale;const state = screen ? appState.screen : appState.world;const retained = appState.retained;// The atlas rasterizes for the projection that draws it: bring each existing renderer up to this pass's before asking whether its@@ -402,13 +426,12 @@ export class TextPlugin implements Plugin {const appState = this.stateFor(app);const world = app.world;const dpr = platformDevicePixelRatio();- const contentScale = screen ? this.screenContentScale(app, dpr) : this.worldContentScale(app, dpr);+ const view = this.domainView(app, screen, dpr);const state = screen ? appState.screen : appState.world;const tr = world.get(entity, Transform) as TransformData;const family = resolveTextFamily(t.font, t.fontFamily);- // A bitmap font has no distance field and one size, so it draws as a bitmap whatever the scale.- const kind = bitmapFontOf(family) ? 'bitmap' : resolveTextRenderMode(t.renderMode, tr.worldScale.x);- const renderer = this.rendererFor(app, state, kind, contentScale, dpr);+ const kind = glyphKind(t, tr, family, view);+ const renderer = this.rendererFor(app, state, kind, view.contentScale, dpr);const previous = appState.retained.get(entity as number);if (previous && previous.renderer !== renderer) previous.renderer.forget(entity as number);@@ -496,9 +519,7 @@ export class TextPlugin implements Plugin {if (screen && !api?.ui_isScreenDomain) return;const dpr = platformDevicePixelRatio();- const contentScale = screen- ? this.screenContentScale(app, dpr)- : this.worldContentScale(app, dpr);+ const view = this.domainView(app, screen, dpr);const state = screen ? appState.screen : appState.world;const seen = new Set<number>();@@ -518,8 +539,8 @@ export class TextPlugin implements Plugin {const tr = world.get(entity, Transform) as TransformData;const renderer = this.rendererFor(app, state,- bitmapFontOf(resolveTextFamily(t.font, t.fontFamily)) ? 'bitmap' : resolveTextRenderMode(t.renderMode, tr.worldScale.x),- contentScale,+ glyphKind(t, tr, resolveTextFamily(t.font, t.fontFamily), view),+ view.contentScale,dpr,);if (!readMatrix) composeTRS(appState.matrix, tr.worldPosition, tr.worldRotation, tr.worldScale);@@ -656,11 +677,10 @@ export class TextPlugin implements Plugin {const t = world.get(run.entity, Text) as TextData;const tr = world.get(run.entity, Transform) as TransformData;const family = resolveTextFamily(t.font, t.fontFamily);- const kind = bitmapFontOf(family) ? 'bitmap' : resolveTextRenderMode(t.renderMode, tr.worldScale.x);const dpr = platformDevicePixelRatio();- const contentScale = screen ? this.screenContentScale(app, dpr) : this.worldContentScale(app, dpr);+ const view = this.domainView(app, screen, dpr);const appState = this.stateFor(app);- const renderer = this.rendererFor(app, screen ? appState.screen : appState.world, kind, contentScale, dpr);+ const renderer = this.rendererFor(app, screen ? appState.screen : appState.world, glyphKind(t, tr, family, view), view.contentScale, dpr);run.renderer = renderer;const style = (t.bold ? UI_TEXT_BOLD : 0) | (t.italic ? UI_TEXT_ITALIC : 0);run.job.step((codepoint) => renderer.preloadGlyph(run, codepoint, family, style, t.fontSize), platformNow);@@ -671,20 +691,14 @@ export class TextPlugin implements Plugin {return !!(app.getResource(UICameraInfo) as UICameraData | undefined)?.valid;}- /** World text rasterizes for the camera showing it — zoom in, get sharper. */- private worldContentScale(app: App, dpr: number): number {+ private domainView(app: App, screen: boolean, dpr: number): DomainView {+ if (screen) {+ if (!app.hasResource(ScreenOverlay)) return FLAT_VIEW;+ const overlay = app.getResource(ScreenOverlay);+ return overlay.active ? domainViewOf(overlay.projection, overlay.vpW, dpr) : FLAT_VIEW;+ }const cam = app.getResource(UICameraInfo) as UICameraData | undefined;- if (!cam?.valid) return 1;- return glyphContentScale(cam.viewProjection?.[0] ?? 0, cam.vpW, dpr);- }-- /** Screen text rasterizes for the overlay that draws it, which is the one- * projection with no camera in it. */- private screenContentScale(app: App, dpr: number): number {- if (!app.hasResource(ScreenOverlay)) return 1;- const overlay = app.getResource(ScreenOverlay);- if (!overlay.active) return 1;- return glyphContentScale(overlay.projection[0] ?? 0, overlay.vpW, dpr);+ return cam?.valid ? domainViewOf(cam.viewProjection, cam.vpW, dpr) : FLAT_VIEW;}/** The two glyph pipelines of one domain, created lazily; they share layout,diff --git a/sdk/tests/ui-text-render-mode.test.ts b/sdk/tests/ui-text-render-mode.test.tsindex 2d6466afa..00f7fa23c 100644--- a/sdk/tests/ui-text-render-mode.test.ts+++ b/sdk/tests/ui-text-render-mode.test.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi } from 'vitest';import { Text, TextRenderMode, resolveTextRenderMode, glyphContentScale, buildText } from '../src/ui';describe('TextRenderMode', () => {@@ -139,3 +139,47 @@ describe('glyphContentScale (what size to rasterize FOR)', () => {expect(glyphContentScale(projFor(1920), 1920, 0)).toBe(1);});});++describe('world text under a perspective camera', () => {+ const ortho = (span: number) => { const m = new Float32Array(16); m[0] = 2 / span; m[5] = 2 / span; m[10] = -1; m[15] = 1; return m; };+ const perspective = (fovDeg: number, aspect: number) => {+ const f = 1 / Math.tan((fovDeg * Math.PI) / 360);+ const m = new Float32Array(16);+ m[0] = f / aspect; m[5] = f; m[10] = -1.0002; m[11] = -1; m[14] = -0.2;+ return m;+ };++ it('has no single scale to rasterize for, and says it is a perspective', async () => {+ const { domainViewOf } = await import('../src/ui/text/plugin');+ expect(domainViewOf(perspective(55, 2670 / 1200), 2670, 2.75)).toEqual({ contentScale: 1, perspective: true });+ const flat = domainViewOf(ortho(960), 1920, 1);+ expect(flat.perspective).toBe(false);+ expect(flat.contentScale).toBeCloseTo(2, 5);+ });++ it('draws Auto text as SDF there, at any scale, and keeps a forced mode', async () => {+ const { domainViewOf, glyphKind } = await import('../src/ui/text/plugin');+ const view = domainViewOf(perspective(55, 16 / 9), 1920, 1);+ const at = (scale: number, renderMode = TextRenderMode.Auto) =>+ glyphKind({ renderMode }, { worldScale: { x: scale, y: scale, z: scale } }, 'sans-serif', view);+ expect(at(1)).toBe('sdf');+ expect(at(1.5)).toBe('sdf');+ expect(at(1, TextRenderMode.Bitmap)).toBe('bitmap');+ const flat = domainViewOf(ortho(1920), 1920, 1);+ expect(glyphKind({ renderMode: TextRenderMode.Auto }, { worldScale: { x: 1, y: 1, z: 1 } }, 'sans-serif', flat)).toBe('bitmap');+ });++ it('never rasterizes a bitmap glyph larger than half an atlas page, and says so once', async () => {+ const { GlyphAtlas } = await import('../src/ui/text/glyph-atlas');+ const { log } = await import('../src/util/logger');+ const warn = vi.spyOn(log, 'warn').mockImplementation(() => {});+ const atlas = new GlyphAtlas({ renderSize: 48, rasterize: () => null } as never, { createPage: () => 1, uploadRegion: () => {} } as never, { sdf: false, dpr: 2.75 });+ atlas.setContentScale(380);+ expect(atlas.pixelSizeFor(32)).toBe(512);+ expect(atlas.pixelSizeFor(48)).toBe(512);+ expect(warn).toHaveBeenCalledTimes(1);+ atlas.setContentScale(1);+ expect(atlas.pixelSizeFor(32)).toBe(88);+ warn.mockRestore();+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex dc2e7496c..6073b7c45 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4122,4 +4122,6 @@ export const NOTED = {{"note": "A render target works on a native device."},"fix(native): the audio device is watched and brought back when it stops taking sound, so a game is not left silent after the background":{"note": "Sound comes back when a device's audio dies on its own."},+ "fix(text): world text under a perspective camera draws as SDF, and no bitmap glyph is rasterized past half an atlas page":+ {"note": "World text under a perspective camera no longer eats the memory."},};