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
feat(text): Text has letter spacing - Text.letterSpacing is extra px after every glyph and a negative value draws them closer; the layout always took one and no path handed it over. Retained labels, the per-frame fallback and inline images read a Text through one derivation, which gives the fallback the underline it never drew
yhh1311422439c2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5e8c98dd2..80e1af365 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **Text has letter spacing.** `Text.letterSpacing` is extra space after every glyph, in the same px as `fontSize`; a negative value draws the glyphs closer. The layout always took a spacing, and `measureText` did, but the component had no field for it and nothing handed one over, so a label could not be spaced. Wrapping, alignment, `Ellipsis` and `Shrink` measure with it, `Shrink` scales it with the type, and it is in the Details panel beside Line Height. The default, 0, is the text as it was.- **A cliff's beds can wander.** A terrain layer seen from the side is read by height, so the beds of a cliff texture lie level, and ran dead straight along a whole wall like lines on ruled paper. The Terrain Layers material's `u_strataWarp` is how far they wander up and down, by slow noise `u_strataSpan` wide. At 0, the default, they are straight as before.- **The tonemap has the fitted ACES curve too.** The `tonemap` effect ran one curve, the engine's (Narkowicz's fit). A picture made for the other ACES fit in wide use (Hill's RRT and ODT, what three.js calls ACES Filmic) came out with shadows about a third brighter at the same mid tones, and with the hue kept in bright colours that curve sends to white. **Fitted ACES** (`u_curve` 1) runs that fit; off, which is the default, nothing changes.- **An anchor on a waterfall.** A `Waterfall` lands wherever the ground or the water under it is, and nothing said where that was, so the mist at its foot had to be placed by hand and stayed behind when the fall moved. A child of the fall's with a `WaterfallAnchor` is kept on the middle of its path: at the foot (`at` 1), at the lip (0) or a share of the time down, `lift` above it. A `ParticleEmitter` on that child is the mist.diff --git a/docs/astro/src/content/docs/ui/text.mdx b/docs/astro/src/content/docs/ui/text.mdxindex 6a56273e3..41e622c26 100644--- a/docs/astro/src/content/docs/ui/text.mdx+++ b/docs/astro/src/content/docs/ui/text.mdx@@ -93,6 +93,7 @@ Defaults below are the component defaults (what the inspector shows).| `boxWidth` / `boxHeight` | number | `0` | The layout box of a `Text` with **no** `UINode`, in px. `0` means no box (the entity origin is the box). With a box, alignment, wrapping and overflow work inside it while the text stays world content, sorted by `layer`. A `UINode`, when present, decides the box instead. || `boxPivot` | Vec2 | `(0.5, 0.5)` | Where the entity origin sits in that box, as a fraction from its left and bottom edges: `(0.5, 0.5)` is the centre, `(0, 1)` the top-left corner. It is the anchor point of a Cocos or Unity rect transform. || `lineHeight` | number | `1.2` | Line spacing as a **ratio of `fontSize`** (baseline-to-baseline = `lineHeight × fontSize`). |+| `letterSpacing` | number | `0` | Extra space after every glyph, in the same px as `fontSize`; negative draws the glyphs closer. Wrapping, alignment and overflow measure with it. It is CSS's `letter-spacing` and a Cocos Label's `spacingX`. || `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. 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)). |diff --git a/docs/astro/src/content/docs/zh-cn/ui/text.mdx b/docs/astro/src/content/docs/zh-cn/ui/text.mdxindex 81c8c687f..9dffa02ca 100644--- a/docs/astro/src/content/docs/zh-cn/ui/text.mdx+++ b/docs/astro/src/content/docs/zh-cn/ui/text.mdx@@ -84,6 +84,7 @@ const pulseBanner = defineSystem([Query(Mut(Transform), Text), Res(Time)], (q, t| `boxWidth` / `boxHeight` | number | `0` | **没有** `UINode` 的 `Text` 的排版盒,单位 px。`0` 表示没有盒(实体原点就是盒)。有盒时对齐、换行、溢出都在盒内工作,而文本仍是世界内容,按 `layer` 排序。存在 `UINode` 时由它决定盒。 || `boxPivot` | Vec2 | `(0.5, 0.5)` | 实体原点在这个盒里的位置,按距盒左边、下边的比例:`(0.5, 0.5)` 是中心,`(0, 1)` 是左上角。相当于 Cocos / Unity 矩形变换的锚点。 || `lineHeight` | number | `1.2` | 行距,为 **`fontSize` 的比率**(基线间距 = `lineHeight × fontSize`)。 |+| `letterSpacing` | number | `0` | 字间距:每个字形后面多出的间隔,单位与 `fontSize` 相同(px);负值让字靠得更近。换行、对齐和溢出都按加了间距的宽度计算。相当于 CSS 的 `letter-spacing`、Cocos Label 的 `spacingX`。 || `bold` / `italic` | boolean | `false` | 基础字体样式(富文本 `<b>`/`<i>` 在其上叠加)。 || `strokeColor` | Color | `{0,0,0,1}` | 描边颜色。 || `strokeWidth` | number | `0` | 描边宽度(px);`0` 关闭。SDF 字形把自己的边缘向外推,位图字形则把字形长大,所以任意宽度下描出来的仍是这个字的形状([见下文](#描边))。 |diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 191b54dcd..333578be8 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -8394,6 +8394,12 @@"type": "number","default": "1.2"},+ {+ "key": "letterSpacing",+ "type": "number",+ "default": "0",+ "doc": "Extra space after every glyph, in the same px as Font Size. Negative draws the glyphs closer. Wrapping, alignment and overflow measure with it."+ },{"key": "bold","type": "boolean",@@ -8496,6 +8502,7 @@"verticalAlign","overflow","lineHeight",+ "letterSpacing","strokeColor.r","strokeColor.g","strokeColor.b",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 2f5eb5e50..ba8f67926 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -11745,6 +11745,7 @@ fontSize: numberi18nKey: stringitalic: booleanlayer: number+letterSpacing: number | undefinedlineHeight: numberoverflow: TextOverflowrenderMode: TextRenderMode@@ -11776,6 +11777,7 @@ fontSize: number | undefinedi18nKey: string | undefineditalic: boolean | undefinedlayer: number | undefined+letterSpacing: number | undefinedlineHeight: number | undefinedoverflow: TextOverflow | undefinedrenderMode: TextRenderMode | undefineddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 5e4ffe971..81737411c 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -11967,6 +11967,7 @@ fontSize: numberi18nKey: stringitalic: booleanlayer: number+letterSpacing: number | undefinedlineHeight: numberoverflow: TextOverflowrenderMode: TextRenderMode@@ -11998,6 +11999,7 @@ fontSize: number | undefinedi18nKey: string | undefineditalic: boolean | undefinedlayer: number | undefined+letterSpacing: number | undefinedlineHeight: number | undefinedoverflow: TextOverflow | undefinedrenderMode: TextRenderMode | undefineddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex cd326ce32..c9f58d8d7 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -11740,6 +11740,7 @@ fontSize: numberi18nKey: stringitalic: booleanlayer: number+letterSpacing: number | undefinedlineHeight: numberoverflow: TextOverflowrenderMode: TextRenderMode@@ -11771,6 +11772,7 @@ fontSize: number | undefinedi18nKey: string | undefineditalic: boolean | undefinedlayer: number | undefined+letterSpacing: number | undefinedlineHeight: number | undefinedoverflow: TextOverflow | undefinedrenderMode: TextRenderMode | undefineddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 998a7ec3e..7c275eccf 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -12037,6 +12037,7 @@ fontSize: numberi18nKey: stringitalic: booleanlayer: number+letterSpacing: number | undefinedlineHeight: numberoverflow: TextOverflowrenderMode: TextRenderMode@@ -12068,6 +12069,7 @@ fontSize: number | undefinedi18nKey: string | undefineditalic: boolean | undefinedlayer: number | undefined+letterSpacing: number | undefinedlineHeight: number | undefinedoverflow: TextOverflow | undefinedrenderMode: TextRenderMode | undefineddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 46851c0f6..37205402f 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -11747,6 +11747,7 @@ fontSize: numberi18nKey: stringitalic: booleanlayer: number+letterSpacing: number | undefinedlineHeight: numberoverflow: TextOverflowrenderMode: TextRenderMode@@ -11778,6 +11779,7 @@ fontSize: number | undefinedi18nKey: string | undefineditalic: boolean | undefinedlayer: number | undefined+letterSpacing: number | undefinedlineHeight: number | undefinedoverflow: TextOverflow | undefinedrenderMode: TextRenderMode | undefineddiff --git a/sdk/src/ui/core/text.ts b/sdk/src/ui/core/text.tsindex 43cd8bdb6..239c07f2c 100644--- a/sdk/src/ui/core/text.ts+++ b/sdk/src/ui/core/text.ts@@ -97,6 +97,12 @@ export interface TextData {wordWrap: boolean;overflow: TextOverflow;lineHeight: number;+ /**+ * Extra space after every glyph, in the same px as `fontSize`; negative draws them closer. It is CSS's+ * `letter-spacing` and a Cocos Label's `spacingX`. Wrapping, alignment, `Ellipsis` and `Shrink` all measure+ * with it, and `Shrink` scales it with the size. Absent is 0.+ */+ letterSpacing?: number;bold: boolean;italic: boolean;strokeColor: Color;@@ -161,6 +167,7 @@ export const Text = defineComponent<TextData>('Text', {wordWrap: true,overflow: TextOverflow.Visible,lineHeight: 1.2,+ letterSpacing: 0,bold: false,italic: false,strokeColor: { r: 0, g: 0, b: 0, a: 1 },@@ -196,6 +203,7 @@ export const Text = defineComponent<TextData>('Text', {enum: enumOptions(TextOverflow),tooltip: 'What text too big for its box does. Needs a layout box: Clip and Ellipsis drop the lines past its height and trim a line past its width; Shrink sets the text smaller until it fits both.',},+ letterSpacing: { tooltip: 'Extra space after every glyph, in the same px as Font Size. Negative draws the glyphs closer. Wrapping, alignment and overflow measure with it.' },underline: { tooltip: 'Draw a line under each line of text, using the underscore of the font.' },renderMode: { enum: enumOptions(TextRenderMode) },boxWidth: { tooltip: 'Layout box width for a text with no UINode (0 = no box: the origin is the box). Alignment, wrapping and overflow work inside it. A UINode, if present, decides the box instead.' },diff --git a/sdk/src/ui/text/inline-image-plugin.ts b/sdk/src/ui/text/inline-image-plugin.tsindex 3c17d1f06..d4f51a967 100644--- a/sdk/src/ui/text/inline-image-plugin.ts+++ b/sdk/src/ui/text/inline-image-plugin.ts@@ -26,7 +26,8 @@ import { UINode, UIPositionType, type UINodeData } from '../core/ui-node';import { UIVisual, UIVisualType, type UIVisualData } from '../core/ui-visual';import { SdfTextRenderer } from './text-renderer';import { layoutText, type LaidImage } from './layout';-import { rectTextBox, UI_TEXT_BOLD, UI_TEXT_ITALIC } from './text-transform';+import { rectTextBox } from './text-transform';+import { textLetterSpacingPx, textLineHeightPx, textStyleBits } from './text-params';import { spawnUIEntity } from '../core/compose';import { px } from '../core/dimension';import { getUINodeWidth, getUINodeHeight } from '../util/helpers';@@ -114,16 +115,16 @@ export class InlineImagePlugin implements Plugin {if (w <= 0 || h <= 0) continue; // inline images need a laid-out boxconst box = rectTextBox(0.5, 0.5, w, h, t.fontSize);- const style = (t.bold ? UI_TEXT_BOLD : 0) | (t.italic ? UI_TEXT_ITALIC : 0);const layout = layoutText(t.content, atlas(), resolveTextFamily(t.font, t.fontFamily), {fontSizePx: t.fontSize,- lineHeight: t.lineHeight > 0 ? t.lineHeight * t.fontSize : undefined,+ lineHeight: textLineHeightPx(t),+ letterSpacing: textLetterSpacingPx(t),align: t.align,rich: true,color: [1, 1, 1, 1],maxWidth: t.wordWrap ? box.maxWidth : undefined,boxWidth: box.maxWidth,- }, style);+ }, textStyleBits(t));const images = layout.images ?? [];if (images.length === 0) { reap(e); continue; }@@ -133,7 +134,7 @@ export class InlineImagePlugin implements Plugin {// same shift `drawTextWith` applies to the glyphs (mirror it so the// images track the text).const slack = h - layout.lineHeight;- const perLine = t.lineHeight > 0 ? t.lineHeight * t.fontSize : t.fontSize * 1.2;+ const perLine = textLineHeightPx(t) ?? t.fontSize * 1.2;// …including the half-leading it charges above the first baseline,// or an image floats where the glyph beside it no longer is.const halfLeading = Math.max(0, (perLine - t.fontSize) / 2);diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.tsindex dc6d4d22d..63b63646e 100644--- a/sdk/src/ui/text/plugin.ts+++ b/sdk/src/ui/text/plugin.ts@@ -17,11 +17,11 @@ import type { ESEngineModule, CppRegistry } from '../../wasm';import type { Entity } from '../../types';import type { World } from '../../ecs/world';import { SdfTextRenderer } from './text-renderer';-import type { RGBA } from './layout';-import { composeTRS, DEFAULT_ASCENT, rectTextBox, UI_TEXT_BOLD, UI_TEXT_ITALIC } from './text-transform';+import { composeTRS } from './text-transform';+import { textDrawParams, textStyleBits } from './text-params';import { Text, TextOverflow, TextRenderMode, type TextData } from '../core/text';import { ContentRect } from '../core/content-rect';-import { bitmapFontOf, fontAscent } from './bitmap-font';+import { bitmapFontOf } from './bitmap-font';import { UINode } from '../core/ui-node';import { Localization } from '../../i18n/Localization';import { applyTextLocalization, type TextWorldView } from './localize';@@ -143,7 +143,7 @@ export function textFrame(world: World, entity: Entity, t: TextData): TextFrame/** 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; renderMode: number;- align: number; verticalAlign: number; wordWrap: boolean; overflow: number; lineHeight: number; layer: number; underline: boolean;+ align: number; verticalAlign: number; wordWrap: boolean; overflow: number; lineHeight: number; letterSpacing: number; layer: number; underline: boolean;boxW: number; boxH: number; boxPx: number; boxPy: number;cr: number; cg: number; cb: number; ca: number;strokeWidth: number; sr: number; sg: number; sb: number; sa: number;@@ -162,7 +162,7 @@ interface RetainedLabel {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, renderMode: t.renderMode,- align: t.align, verticalAlign: t.verticalAlign, wordWrap: !!t.wordWrap, overflow: t.overflow, lineHeight: t.lineHeight, layer: t.layer | 0, underline: !!t.underline,+ align: t.align, verticalAlign: t.verticalAlign, wordWrap: !!t.wordWrap, overflow: t.overflow, lineHeight: t.lineHeight, letterSpacing: t.letterSpacing || 0, layer: t.layer | 0, underline: !!t.underline,boxW: t.boxWidth || 0, boxH: t.boxHeight || 0, boxPx: t.boxPivot?.x ?? 0.5, boxPy: t.boxPivot?.y ?? 0.5,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,@@ -175,7 +175,7 @@ export function sameSnapshot(s: TextSnapshot, t: TextData, family: string): boolreturn s.content === t.content && s.family === family && s.fontSize === t.fontSize&& 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.underline === !!t.underline+ && s.overflow === t.overflow && s.lineHeight === t.lineHeight && s.letterSpacing === (t.letterSpacing || 0) && s.layer === (t.layer | 0) && s.underline === !!t.underline&& s.boxW === (t.boxWidth || 0) && s.boxH === (t.boxHeight || 0) && s.boxPx === (t.boxPivot?.x ?? 0.5) && s.boxPy === (t.boxPivot?.y ?? 0.5)&& s.cr === t.color.r && s.cg === t.color.g && s.cb === t.color.b && s.ca === t.color.a&& s.strokeWidth === t.strokeWidth@@ -457,62 +457,12 @@ export class TextPlugin implements Plugin {const previous = appState.retained.get(entity as number);if (previous && previous.renderer !== renderer) previous.renderer.forget(entity as number);- const style = (t.bold ? UI_TEXT_BOLD : 0) | (t.italic ? UI_TEXT_ITALIC : 0);- // Text.lineHeight is a ratio of fontSize (legacy convention).- const lineHeightPx = t.lineHeight > 0 ? t.lineHeight * t.fontSize : undefined;- let originX: number | undefined;- let originY: number | undefined;- let maxWidth: number | undefined;- let boxWidth: number | undefined;- let boxHeight: number | undefined;const frame = textFrame(world, entity, t);const w = frame.w, h = frame.h;const hasBox = w > 0 || h > 0;- if (hasBox) {- const box = rectTextBox(frame.px, frame.py, w, h, t.fontSize, fontAscent(family, DEFAULT_ASCENT));- originX = box.originX;- originY = box.originY;- boxWidth = box.maxWidth; // align within the box regardless of word-wrap- boxHeight = box.boxHeight;- if (t.wordWrap) maxWidth = box.maxWidth; // wrap only when enabled- }- const shadow = t.shadowColor.a > 0- && (t.shadowOffsetX !== 0 || t.shadowOffsetY !== 0 || t.shadowBlur > 0)- ? {- color: [t.shadowColor.r, t.shadowColor.g, t.shadowColor.b, t.shadowColor.a] as RGBA,- dx: t.shadowOffsetX,- dy: t.shadowOffsetY,- blur: t.shadowBlur,- }- : undefined;- const outline = t.strokeWidth > 0 && t.strokeColor.a > 0- ? {- color: [t.strokeColor.r, t.strokeColor.g, t.strokeColor.b, t.strokeColor.a] as RGBA,- width: t.strokeWidth,- }- : undefined;const blockHeight = renderer.retain(api,- {- text: t.content,- fontFamily: family,- fontSizePx: t.fontSize,- color: [t.color.r, t.color.g, t.color.b, t.color.a],- style,- richText: t.richText,- align: t.align,- verticalAlign: t.verticalAlign,- lineHeight: lineHeightPx,- maxWidth,- boxWidth,- boxHeight,- overflow: t.overflow,- underline: !!t.underline,- originX,- originY,- shadow,- outline,- },+ textDrawParams(t, family, frame),// The engine orders a boxed label by the UI tree and re-lays it out when the node's size changes; a box// that is the Text's own is neither, so it is reported as no box (its size reaches layout above).entity as number, screen, hasBox && frame.ui, t.layer | 0, frame.ui ? w : 0, frame.ui ? h : 0,@@ -559,85 +509,30 @@ export class TextPlugin implements Plugin {seen.add(entity as number);const tr = world.get(entity, Transform) as TransformData;+ const family = resolveTextFamily(t.font, t.fontFamily);const renderer = this.rendererFor(app, state,- glyphKind(t, tr, resolveTextFamily(t.font, t.fontFamily), view, dpr),+ glyphKind(t, tr, family, view, dpr),view.contentScale,dpr,);if (!readMatrix) composeTRS(appState.matrix, tr.worldPosition, tr.worldRotation, tr.worldScale);- const style = (t.bold ? UI_TEXT_BOLD : 0) | (t.italic ? UI_TEXT_ITALIC : 0);- // Text.lineHeight is a ratio of fontSize (legacy convention).- const lineHeightPx = t.lineHeight > 0 ? t.lineHeight * t.fontSize : undefined;-// The layout box: a UINode (CSS box, pivot-centered), which places,// aligns and wraps the text and sorts it by UI render order. No box ⇒// a world label at the entity origin, sorted by Text.layer.- let originX: number | undefined;- let originY: number | undefined;- let maxWidth: number | undefined;- let boxWidth: number | undefined;- let boxHeight: number | undefined;let layer = t.layer | 0;const frame = textFrame(world, entity, t);- const hasBox = frame.w > 0 || frame.h > 0;- if (hasBox) {- const box = rectTextBox(frame.px, frame.py, frame.w, frame.h, t.fontSize, fontAscent(resolveTextFamily(t.font, t.fontFamily), DEFAULT_ASCENT));- originX = box.originX;- originY = box.originY;- boxWidth = box.maxWidth; // align within the box regardless of word-wrap- boxHeight = box.boxHeight;- if (t.wordWrap) maxWidth = box.maxWidth; // wrap only when enabled-- if (frame.ui) {- const order = api?.ui_getRenderOrder?.(registry, entity as number) ?? -1;- layer = order >= 0 ? UI_BASE_LAYER + order : UI_BASE_LAYER;- }+ if ((frame.w > 0 || frame.h > 0) && frame.ui) {+ const order = api?.ui_getRenderOrder?.(registry, entity as number) ?? -1;+ layer = order >= 0 ? UI_BASE_LAYER + order : UI_BASE_LAYER;}- // A blur with no offset is still a shadow — a halo centred on the- // glyphs — so it counts as one for the "is there a shadow" test.- const shadow = t.shadowColor.a > 0- && (t.shadowOffsetX !== 0 || t.shadowOffsetY !== 0 || t.shadowBlur > 0)- ? {- color: [t.shadowColor.r, t.shadowColor.g, t.shadowColor.b, t.shadowColor.a] as RGBA,- dx: t.shadowOffsetX,- dy: t.shadowOffsetY,- blur: t.shadowBlur,- }- : undefined;- const outline = t.strokeWidth > 0 && t.strokeColor.a > 0- ? {- color: [t.strokeColor.r, t.strokeColor.g, t.strokeColor.b, t.strokeColor.a] as RGBA,- width: t.strokeWidth,- }- : undefined;-renderer.drawText(- {- text: t.content,- fontFamily: resolveTextFamily(t.font, t.fontFamily),- fontSizePx: t.fontSize,- // Subtree opacity (UINode.opacity) is resolved in C++ by the- // layout pass; text is drawn here, so it multiplies the same- // inherited alpha in and fades with its panel like visuals do.- color: [t.color.r, t.color.g, t.color.b, t.color.a],- opacity: groupAlpha,- style,- richText: t.richText,- align: t.align,- verticalAlign: t.verticalAlign,- lineHeight: lineHeightPx,- maxWidth,- boxWidth,- boxHeight,- overflow: t.overflow,- originX,- originY,- shadow,- outline,- },+ // Subtree opacity (UINode.opacity) is resolved in C++ by the+ // layout pass; text is drawn here, so it multiplies the same+ // inherited alpha in and fades with its panel like visuals do.+ { ...textDrawParams(t, family, frame), opacity: groupAlpha },appState.matrix,entity as number,layer,@@ -705,7 +600,7 @@ export class TextPlugin implements Plugin {const appState = this.stateFor(app);const renderer = this.rendererFor(app, screen ? appState.screen : appState.world, glyphKind(t, tr, family, view, dpr), view.contentScale, dpr);run.renderer = renderer;- const style = (t.bold ? UI_TEXT_BOLD : 0) | (t.italic ? UI_TEXT_ITALIC : 0);+ const style = textStyleBits(t);run.job.step((codepoint) => renderer.preloadGlyph(run, codepoint, family, style, t.fontSize), platformNow);}diff --git a/sdk/src/ui/text/text-params.ts b/sdk/src/ui/text/text-params.tsnew file mode 100644index 000000000..3da2ce59a--- /dev/null+++ b/sdk/src/ui/text/text-params.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ui/text/text-params.ts+ * @brief What a `Text` component asks of the text renderer, derived in one place.+ *+ * Every path that lays a Text out (the retained labels, the per-frame fallback, the inline images that must+ * track the glyphs) reads the component through here. A field a Text gains is threaded once; written out per+ * path, each new field reached some of them and not others.+ */+import type { TextData } from '../core/text';+import type { RGBA } from './layout';+import type { DrawTextParams } from './text-renderer';+import { fontAscent } from './bitmap-font';+import { DEFAULT_ASCENT, rectTextBox, UI_TEXT_BOLD, UI_TEXT_ITALIC } from './text-transform';++/** The box a Text is laid out in, and where the entity origin sits in it (see `textFrame`). */+export interface TextBoxFrame {+ w: number;+ h: number;+ /** Pivot as a fraction from the box's left / bottom edge. */+ px: number;+ py: number;+}++/** Bold and italic as the style bits the glyph atlas keys on. */+export function textStyleBits(t: Pick<TextData, 'bold' | 'italic'>): number {+ return (t.bold ? UI_TEXT_BOLD : 0) | (t.italic ? UI_TEXT_ITALIC : 0);+}++/** `Text.lineHeight` is a ratio of the font size; layout wants px. Undefined leaves layout its default. */+export function textLineHeightPx(t: Pick<TextData, 'lineHeight' | 'fontSize'>): number | undefined {+ return t.lineHeight > 0 ? t.lineHeight * t.fontSize : undefined;+}++/** `Text.letterSpacing` in px, or undefined for none: data saved before the field, and a value that is no number, are none. */+export function textLetterSpacingPx(t: Pick<TextData, 'letterSpacing'>): number | undefined {+ const spacing = t.letterSpacing;+ return typeof spacing === 'number' && Number.isFinite(spacing) && spacing !== 0 ? spacing : undefined;+}++/** The part of a layout request that is where the box is and how wide a line may run. */+export interface TextBoxPlacement {+ originX?: number;+ originY?: number;+ maxWidth?: number;+ boxWidth?: number;+ boxHeight?: number;+}++/** Where the text block starts and what it aligns and wraps inside. A frame of no size is no box: the entity origin is the anchor. */+export function textBoxPlacement(t: Pick<TextData, 'fontSize' | 'wordWrap'>, family: string, frame: TextBoxFrame): TextBoxPlacement {+ if (!(frame.w > 0 || frame.h > 0)) return {};+ const box = rectTextBox(frame.px, frame.py, frame.w, frame.h, t.fontSize, fontAscent(family, DEFAULT_ASCENT));+ return {+ originX: box.originX,+ originY: box.originY,+ boxWidth: box.maxWidth, // align within the box regardless of word-wrap+ boxHeight: box.boxHeight,+ maxWidth: t.wordWrap ? box.maxWidth : undefined, // wrap only when enabled+ };+}++/**+ * Everything the renderer needs to lay out and colour one Text, except the opacity it inherits from its subtree.+ *+ * @param family the resolved family (`resolveTextFamily`), since a shipped font and a named one arrive differently.+ * @param frame the box from `textFrame`.+ */+export function textDrawParams(t: TextData, family: string, frame: TextBoxFrame): DrawTextParams {+ // A blur with no offset is still a shadow (a halo centred on the glyphs), so it counts as one.+ const shadow = t.shadowColor.a > 0 && (t.shadowOffsetX !== 0 || t.shadowOffsetY !== 0 || t.shadowBlur > 0)+ ? {+ color: [t.shadowColor.r, t.shadowColor.g, t.shadowColor.b, t.shadowColor.a] as RGBA,+ dx: t.shadowOffsetX,+ dy: t.shadowOffsetY,+ blur: t.shadowBlur,+ }+ : undefined;+ const outline = t.strokeWidth > 0 && t.strokeColor.a > 0+ ? { color: [t.strokeColor.r, t.strokeColor.g, t.strokeColor.b, t.strokeColor.a] as RGBA, width: t.strokeWidth }+ : undefined;+ return {+ text: t.content,+ fontFamily: family,+ fontSizePx: t.fontSize,+ color: [t.color.r, t.color.g, t.color.b, t.color.a],+ style: textStyleBits(t),+ richText: t.richText,+ align: t.align,+ verticalAlign: t.verticalAlign,+ lineHeight: textLineHeightPx(t),+ letterSpacing: textLetterSpacingPx(t),+ overflow: t.overflow,+ underline: !!t.underline,+ ...textBoxPlacement(t, family, frame),+ shadow,+ outline,+ };+}diff --git a/sdk/tests/ui-text-letter-spacing.test.ts b/sdk/tests/ui-text-letter-spacing.test.tsnew file mode 100644index 000000000..5d6d2c3ec--- /dev/null+++ b/sdk/tests/ui-text-letter-spacing.test.ts@@ -0,0 +1,136 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ui-text-letter-spacing.test.ts: Text.letterSpacing reaches the layout.+ *+ * The layout always took a spacing; the component had no field for it and no path handed one over, so a label+ * could not be spaced. These hold the field to the glyphs: what the component says is what the layout is asked,+ * on the one derivation every path shares.+ */+import { describe, it, expect } from 'vitest';+import {+ GlyphAtlas, type GlyphRasterizer, type AtlasPageStore, type RasterGlyph,+} from '../src/ui/text/glyph-atlas';+import { layoutText } from '../src/ui/text/layout';+import { textBoxPlacement, textDrawParams, textLetterSpacingPx, textLineHeightPx, textStyleBits } from '../src/ui/text/text-params';+import { Text, TextOverflow, type TextData } from '../src/ui/core/text';++function makeAtlas(): GlyphAtlas {+ const rasterizer: GlyphRasterizer = {+ renderSize: 48,+ spread: 6,+ rasterize: (cp: number): RasterGlyph => {+ if (cp === 32) return { pixels: new Uint8Array(0), width: 0, height: 0, advance: 6, bearingX: 0, bearingY: 0 };+ return { pixels: new Uint8Array(10 * 12 * 4), width: 10, height: 12, advance: 11, bearingX: 1, bearingY: 10 };+ },+ };+ let next = 1;+ const store: AtlasPageStore = { createPage: () => next++, uploadSubRegion: () => {} };+ return new GlyphAtlas(rasterizer, store, { pageSize: 256, padding: 1 });+}++// scale 0.5 at this size: every letter advances 5.5px, a space 3px.+const F = 24;+const ADVANCE = 5.5;+const NO_BOX = { w: 0, h: 0, px: 0.5, py: 0.5 };++const text = (over: Partial<TextData> = {}): TextData => ({ ...structuredClone(Text._default), content: 'abcd', fontSize: F, ...over });++/** The glyphs a Text lays out to, through the params every draw path uses. */+function laid(t: TextData, frame = NO_BOX) {+ const p = textDrawParams(t, 'Arial', frame);+ return layoutText(p.text, makeAtlas(), p.fontFamily, {+ fontSizePx: p.fontSizePx, letterSpacing: p.letterSpacing, lineHeight: p.lineHeight, align: p.align, rich: p.richText,+ maxWidth: p.maxWidth, boxWidth: p.boxWidth, boxHeight: p.boxHeight, overflow: p.overflow,+ }, p.style ?? 0);+}++const lefts = (l: { glyphs: { x0: number }[] }) => l.glyphs.map((g) => g.x0);+const rows = (l: { glyphs: { y0: number }[] }) => new Set(l.glyphs.map((g) => Math.round(g.y0))).size;++describe('Text.letterSpacing', () => {+ it('is a field of the component, and none by default', () => {+ expect(Text._default.letterSpacing).toBe(0);+ expect(textDrawParams(text(), 'Arial', NO_BOX).letterSpacing).toBeUndefined();+ });++ it('moves each glyph one spacing further than the one before', () => {+ const plain = lefts(laid(text()));+ const spaced = lefts(laid(text({ letterSpacing: 3 })));+ expect(spaced.map((x, i) => x - plain[i]!)).toEqual([0, 3, 6, 9]);+ expect(laid(text({ letterSpacing: 3 })).width).toBeCloseTo(4 * (ADVANCE + 3));+ });++ it('draws glyphs closer when negative', () => {+ const plain = lefts(laid(text()));+ const tight = lefts(laid(text({ letterSpacing: -1 })));+ expect(tight.map((x, i) => x - plain[i]!)).toEqual([0, -1, -2, -3]);+ });++ it('spaces rich text as it does plain', () => {+ const plain = lefts(laid(text({ richText: true, content: 'ab<b>cd</b>' })));+ const spaced = lefts(laid(text({ richText: true, content: 'ab<b>cd</b>', letterSpacing: 2 })));+ expect(spaced.map((x, i) => x - plain[i]!)).toEqual([0, 2, 4, 6]);+ });++ it('wraps by the spaced width', () => {+ // 'aa aa' is 25px unspaced and fits a 26px box on one line; at 4px a glyph it is 45px and does not.+ const frame = { w: 26, h: 100, px: 0.5, py: 0.5 };+ expect(rows(laid(text({ content: 'aa aa' }), frame))).toBe(1);+ expect(rows(laid(text({ content: 'aa aa', letterSpacing: 4 }), frame))).toBe(2);+ });++ it('is scaled with the type when Shrink sets it smaller', () => {+ const frame = { w: 30, h: 0, px: 0.5, py: 0.5 };+ const l = laid(text({ content: 'aaaa', letterSpacing: 6, wordWrap: false, overflow: TextOverflow.Shrink }), frame);+ const size = l.fontSizePx!;+ expect(size).toBeLessThan(F);+ expect(l.glyphs[1]!.x0 - l.glyphs[0]!.x0).toBeCloseTo((ADVANCE + 6) * size / F);+ expect(l.width).toBeLessThanOrEqual(30 + 1e-6);+ });++ it('reads a missing or broken value as none', () => {+ expect(textLetterSpacingPx({})).toBeUndefined();+ expect(textLetterSpacingPx({ letterSpacing: Number.NaN })).toBeUndefined();+ expect(textLetterSpacingPx({ letterSpacing: 'wide' as never })).toBeUndefined();+ expect(textLetterSpacingPx({ letterSpacing: -2 })).toBe(-2);+ });+});++describe('what a Text asks of the renderer', () => {+ it('carries every style the component has', () => {+ const p = textDrawParams(text({+ bold: true, italic: true, underline: true, lineHeight: 1.5, letterSpacing: 2, richText: true, align: 1, verticalAlign: 2,+ overflow: TextOverflow.Ellipsis, strokeWidth: 2, shadowOffsetX: 1,+ }), 'Georgia', NO_BOX);+ expect(p).toMatchObject({+ text: 'abcd', fontFamily: 'Georgia', fontSizePx: F, style: 3, underline: true, lineHeight: 36, letterSpacing: 2,+ richText: true, align: 1, verticalAlign: 2, overflow: TextOverflow.Ellipsis,+ });+ expect(p.outline?.width).toBe(2);+ expect(p.shadow?.dx).toBe(1);+ expect(p.opacity).toBeUndefined();+ });++ it('has no shadow or outline to draw when they would not show', () => {+ const p = textDrawParams(text(), 'Arial', NO_BOX);+ expect(p.shadow).toBeUndefined();+ expect(p.outline).toBeUndefined();+ expect(textDrawParams(text({ shadowBlur: 3 }), 'Arial', NO_BOX).shadow?.blur).toBe(3);+ });++ it('anchors a boxless label at the origin and a boxed one in its box', () => {+ expect(textBoxPlacement(text(), 'Arial', NO_BOX)).toEqual({});+ const frame = { w: 100, h: 40, px: 0.5, py: 0.5 };+ const boxed = textBoxPlacement(text(), 'Arial', frame);+ expect(boxed).toMatchObject({ boxWidth: 100, boxHeight: 40, maxWidth: 100, originX: -50 });+ expect(textBoxPlacement(text({ wordWrap: false }), 'Arial', frame).maxWidth).toBeUndefined();+ });++ it('turns the line height ratio into px, and bold and italic into style bits', () => {+ expect(textLineHeightPx({ lineHeight: 1.5, fontSize: 20 })).toBe(30);+ expect(textLineHeightPx({ lineHeight: 0, fontSize: 20 })).toBeUndefined();+ expect(textStyleBits({ bold: true, italic: false })).toBe(1);+ expect(textStyleBits({ bold: false, italic: true })).toBe(2);+ });+});diff --git a/sdk/tests/ui-text-retained.test.ts b/sdk/tests/ui-text-retained.test.tsindex 59acacfc9..8c9ea98da 100644--- a/sdk/tests/ui-text-retained.test.ts+++ b/sdk/tests/ui-text-retained.test.ts@@ -10,7 +10,7 @@ import { GlyphAtlas } from '../src/ui/text/glyph-atlas';import { SdfTextRenderer, drawTextWith, type DrawTextParams } from '../src/ui/text/text-renderer';import { resolveTextRenderMode, sameSnapshot, snapshotOf } from '../src/ui/text/plugin';import { rectTextBox } from '../src/ui/text/text-transform';-import type { TextData } from '../src/ui/core/text';+import { Text, type TextData } from '../src/ui/core/text';import type { EngineApi } from '../src/ecs/bridge/engineApi';import { TEXT_VERTEX_FLOATS } from '../src/ui/text/submit';@@ -19,14 +19,9 @@ vi.mock('../src/platform', () => ({platformCreateCanvas: (width: number, height: number) => ({ width, height, getContext: () => null }),}));+// From the component itself, so a field Text gains is a key here without anyone remembering to add it.function freshText(): TextData {- return {- content: 'hello', i18nKey: '', font: 0, fontFamily: 'Arial', fontSize: 24, color: { r: 1, g: 1, b: 1, a: 1 },- align: 0, verticalAlign: 0, wordWrap: true, overflow: 0, lineHeight: 1.2, bold: false, italic: false,- strokeColor: { r: 0, g: 0, b: 0, a: 1 }, strokeWidth: 0, shadowColor: { r: 0, g: 0, b: 0, a: 1 }, shadowBlur: 0,- shadowOffsetX: 0, shadowOffsetY: 0, richText: false, renderMode: 0, layer: 0, enabled: true,- boxWidth: 0, boxHeight: 0, boxPivot: { x: 0.5, y: 0.5 },- } as TextData;+ return { ...structuredClone(Text._default), content: 'hello', fontFamily: 'Arial' };}describe('which Text fields make a retained label laid out again', () => {@@ -42,6 +37,8 @@ describe('which Text fields make a retained label laid out again', () => {['wordWrap', t => { t.wordWrap = false; }],['overflow', t => { t.overflow = 1; }],['lineHeight', t => { t.lineHeight = 1.5; }],+ ['letterSpacing', t => { t.letterSpacing = 2; }],+ ['underline', t => { t.underline = true; }],['bold', t => { t.bold = true; }],['italic', t => { t.italic = true; }],['strokeColor', t => { t.strokeColor = { r: 1, g: 0, b: 0, a: 1 }; }],diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex a34d44e96..fd0aed2b9 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4566,6 +4566,8 @@ export const NOTED = {{"note": "2D lighting works out only the lights that reach a pixel."},"feat(tilemap): a tilemap layer can be lit - TilemapLayer.lit draws its tiles with the program a lit sprite uses, and which of the loop's lights a flat lit pixel works out is its screen tile's say, so strips stay on the GPU while lights move; four lit layers under sixteen local lamps cost 0.71 ms where working every light out cost 2.58":{"note": "A tilemap layer can be lit."},+ "feat(text): Text has letter spacing - Text.letterSpacing is extra px after every glyph and a negative value draws them closer; the layout always took one and no path handed it over. Retained labels, the per-frame fallback and inline images read a Text through one derivation, which gives the fallback the underline it never drew":+ {"note": "Text has letter spacing."},"feat(sky): a sky of your own shades the ground under its clouds - defineSkyEffect takes groundShadow and a second function, skyShadow(world, sun), what is left of the light at a world position, and the sky pass multiplies every surface it finds by it, as Sky Atmosphere does with its own clouds":{"note": "A sky of your own shades the ground under its clouds."},"fix(terrain): a colour map and an occlusion map lie the way the heightmap does - Terrain.colorMap, Terrain.occlusionMap and Foliage.colorMap were sampled with their rows turned over, so a picture painted to match a heightmap, a splatmap or a density map came out mirrored north to south under them; an image over an area now has its first row along the least z whoever reads it":