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.

fix(editor): preserve engine-computed transform fields + unify text alignment

esengine68abe4202bcc
diff --git a/desktop/src/engine/Reconciler.ts b/desktop/src/engine/Reconciler.ts
index 8b35431e6..367196978 100644
--- a/desktop/src/engine/Reconciler.ts
+++ b/desktop/src/engine/Reconciler.ts
@@ -6,7 +6,7 @@ import type { EntityId } from '@/types';
import { EngineHost } from './EngineHost';
import { PerfMonitor } from './PerfMonitor';
import { SceneModel, SceneModelImpl, type ModelEvent } from './SceneModel';
-import { assetFieldType, spineSlotType, componentByName, componentDefaults, isRenderComponent, componentEnable, type AnyComp, type WorldT } from './schema';
+import { assetFieldType, spineSlotType, componentByName, componentDefaults, isRenderComponent, componentEnable, readonlyFieldsFor, type AnyComp, type WorldT } from './schema';
/**
* Projects the model into the World.
@@ -236,8 +236,20 @@ export class ReconcilerImpl {
// edit on a hidden entity doesn't quietly un-hide it in the viewport.
const src = this.model.isHidden(sourceId) ? foldHidden(comp) : comp;
const data = this.projectData(type, def, src.data as Record<string, unknown>);
- if (world.has(rt, def)) world.set(rt, def, data as Parameters<WorldT['set']>[2]);
- else world.insert(rt, def, data as never);
+ if (world.has(rt, def)) {
+ // Readonly fields (Transform's world-space transform) are ENGINE-computed each
+ // frame; the model carries a stale zero for them, and the value-object marshalling
+ // needs every field present — so re-use the World's live-composed value instead of
+ // clobbering it to the origin (which is what made a moving gizmo snap to 0,0).
+ const readonly = readonlyFieldsFor(type);
+ if (readonly.length) {
+ const live = world.get(rt, def) as Record<string, unknown>;
+ for (const k of readonly) if (k in live) data[k] = live[k];
+ }
+ world.set(rt, def, data as Parameters<WorldT['set']>[2]);
+ } else {
+ world.insert(rt, def, data as never);
+ }
}
/** Re-project an entity's render components when its editor visibility flips. */
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index 48a8781c5..4265c34e9 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -826,6 +826,31 @@ export class SceneCommandsImpl {
if (op) this.history.record(`Add ${prettyLabel(compName)}`, op.forward, op.reverse);
}
+ /**
+ * Give an entity a UI layout box: add a px-sized UINode and reparent it under `parent`
+ * (a Canvas / UI root) so the UI layout resolves a box. This is the one-click path from
+ * a boxless Text — whose align/verticalAlign only anchor to the origin — to box-aligned
+ * UI text. One undo step; a no-op if the entity already has a UINode.
+ */
+ attachUINodeBox(sourceId: EntityId, parent: EntityId, width: number, height: number): void {
+ const entity = this.model.entityBySource(sourceId);
+ if (!entity || entity.components.some((c) => c.type === 'UINode')) return;
+ const before = entity.parent ?? null;
+ const data = { ...this.defaultDataFor('UINode'), width: { value: width, unit: 0 }, height: { value: height, unit: 0 } };
+ this.model.setComponent(sourceId, 'UINode', structuredClone(data));
+ this.model.setParent(sourceId, parent);
+ this.history.batch('Add Layout Box', [
+ {
+ forward: () => this.model.setComponent(sourceId, 'UINode', structuredClone(data)),
+ reverse: () => this.model.removeComponent(sourceId, 'UINode'),
+ },
+ {
+ forward: () => this.model.setParent(sourceId, parent),
+ reverse: () => this.model.setParent(sourceId, before),
+ },
+ ]);
+ }
+
/** Remove a component from an entity (Transform / Name are protected). Undoable. */
removeComponent(sourceId: EntityId, compName: string): void {
const op = this.removeComponentOp(sourceId, compName);
diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.ts
index 51412d944..57c0e110f 100644
--- a/desktop/src/engine/schema.ts
+++ b/desktop/src/engine/schema.ts
@@ -294,6 +294,14 @@ export function animatableFieldsFor(compType: string): readonly string[] {
return userSchema(compType)?.animatableFields ?? [];
}
+/** Engine-COMPUTED output fields (authored `readonly` at the C++ ES_PROPERTY site —
+ * e.g. Transform's worldPosition/worldRotation/worldScale). The reconciler must not
+ * push the model's stale value for these: the engine composes them each frame, so a
+ * write clobbers the live value. User components have none. */
+export function readonlyFieldsFor(compType: string): readonly string[] {
+ return getComponent(compType)?.readonlyFields ?? [];
+}
+
// — Per-entity dynamic enums —
// Some string fields are really a choice from a list that depends on the entity's
// runtime state, not a static enum (e.g. a spine animation/skin name from the loaded
@@ -570,6 +578,19 @@ const POSITIONAL_LIGHT_TYPES = new Set([Light2DType.Point, Light2DType.Spot]);
* explainable (e.g. the render path skips a positional light with no Transform).
*/
export function componentNotice(compType: string, entity: SceneEntityLike): string | null {
+ // Text align/verticalAlign resolve against a layout box, which only a UINode (laid
+ // out under a Canvas) provides. Without one the text anchors to the entity origin —
+ // surfaced when the user has actually set an alignment, so the behavior is explained.
+ if (compType === 'Text') {
+ if (!entity.components.some((c) => c.type === 'UINode')) {
+ const d = entity.components.find((c) => c.type === 'Text')?.data as
+ | { align?: number; verticalAlign?: number }
+ | undefined;
+ if ((d?.align ?? 0) !== 0 || (d?.verticalAlign ?? 0) !== 0)
+ return 'No layout box — align anchors the text to the entity origin. To align within a fixed area, add a UINode and place this Text under a Canvas.';
+ }
+ return null;
+ }
const hasTransform = entity.components.some((c) => c.type === 'Transform');
if (hasTransform) return null;
if (compType === 'Light2D') {
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index 6d6ca7d0a..2a8420b3f 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -42,6 +42,7 @@ import { SceneQuery, buildEntityInfo, buildInspector } from '@/engine/SceneQuery
import { SceneModel } from '@/engine/SceneModel';
import { InspectorClipboard } from '@/engine/inspectorClipboard';
import { SceneCommands, toModelValue } from '@/engine/SceneCommands';
+import { ENTITY_SOURCES, createFromSource } from '@/engine/entitySources';
import { PlayInspect } from '@/engine/PlayInspect';
import { DimensionUnit } from 'esengine';
import type { SceneData, InputMapAsset, ActionType, Binding } from 'esengine';
@@ -1076,6 +1077,30 @@ function Fold({ label, open, onToggle, children }: { label: string; open: boolea
const ADVANCED_FOLD = '__advanced__';
+/** Give a boxless Text a UI layout box: ensure a Canvas (create one if the scene has
+ * none), then add a sized UINode + reparent under it so align/verticalAlign resolve
+ * within a box instead of anchoring to the origin. */
+async function addTextLayoutBox(sourceId: EntityId): Promise<void> {
+ let canvas = SceneCommands.findCanvas();
+ if (canvas == null) {
+ const src = ENTITY_SOURCES.find((s) => s.id === 'canvas');
+ canvas = src ? await createFromSource(src, { parent: null }) : null;
+ }
+ if (canvas != null) SceneCommands.attachUINodeBox(sourceId, canvas, 240, 80);
+}
+
+/** The one-click "Add layout box" action for a boxless Text (no UINode), else undefined. */
+function textBoxAction(comp: InspectorComponent, sourceId: EntityId): { label: string; title: string; run: () => void } | undefined {
+ if (comp.name !== 'Text') return undefined;
+ const e = SceneModel.entityBySource(sourceId);
+ if (!e || e.components.some((c) => c.type === 'UINode')) return undefined;
+ return {
+ label: 'Add layout box',
+ title: 'Add a UINode and place this Text under a Canvas so align / vertical align resolve within a fixed box.',
+ run: () => void addTextLayoutBox(sourceId),
+ };
+}
+
function ComponentSection({
entities,
comp,
@@ -1083,6 +1108,7 @@ function ComponentSection({
onToggle,
onMore,
write,
+ action,
}: {
entities: EntityId[];
comp: InspectorComponent;
@@ -1090,6 +1116,7 @@ function ComponentSection({
onToggle: () => void;
onMore?: (e: React.MouseEvent, name: string) => void;
write?: FieldWrite;
+ action?: { label: string; title: string; run: () => void };
}) {
const Icon = componentIcon(comp.name);
const overridden = comp.fields.some(isModified);
@@ -1162,6 +1189,11 @@ function ComponentSection({
<div className="comp-body">
<div className="cinner">
{comp.notice && <div className="comp-notice">{comp.notice}</div>}
+ {action && (
+ <button type="button" className="comp-action" title={action.title} onClick={action.run}>
+ {action.label}
+ </button>
+ )}
<div className="comp-fields">
{ungrouped.map(row)}
{[...groups].map(([cat, fields]) => (
@@ -1228,6 +1260,7 @@ function GameDetails() {
comp={comp}
collapsed={collapsed.has(comp.name)}
onToggle={() => toggle(comp.name)}
+ action={textBoxAction(comp, selection)}
write={(key, type, value) =>
PlayInspect.setField(selection, comp.name, key, toModelValue(compData(comp.name), type, key, value as never))
}
diff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.css
index f79bcc2f9..8eb69300b 100644
--- a/desktop/src/theme/inspector.css
+++ b/desktop/src/theme/inspector.css
@@ -73,6 +73,8 @@
.comp-fields { padding: 5px 8px 8px; }
/* contextual heads-up under a component header (silently-inert state, not an error) */
.comp-notice { margin: 6px 8px 0; padding: 5px 8px; font-size: var(--fs-2xs); line-height: 1.45; color: var(--warn); background: rgba(214, 166, 90, 0.10); border: 1px solid rgba(214, 166, 90, 0.25); border-radius: var(--r-sm); }
+.comp-action { margin: 6px 8px 0; padding: 4px 8px; width: calc(100% - 16px); font-size: var(--fs-2xs); color: var(--text); background: var(--srf-3); border: 1px solid var(--border); border-radius: var(--r-sm); cursor: pointer; transition: background var(--t-fast), border-color var(--t-fast); }
+.comp-action:hover { background: var(--srf-4); border-color: var(--acc); }
/* property rows (label col + value col, reset on right) */
.prop { display: grid; grid-template-columns: 38% 1fr 18px; align-items: center; gap: 4px; min-height: var(--h-prop); padding: 1px 0; position: relative; }
diff --git a/desktop/tests/engine-model-sync.test.ts b/desktop/tests/engine-model-sync.test.ts
index 467e03d59..adb8c9612 100644
--- a/desktop/tests/engine-model-sync.test.ts
+++ b/desktop/tests/engine-model-sync.test.ts
@@ -27,7 +27,17 @@ vi.mock('@/engine/EngineHost', () => ({
}));
import { EditorSession } from '@/engine/EditorSession';
-import { inspectorFields } from '@/engine/schema';
+import { inspectorFields, readonlyFieldsFor } from '@/engine/schema';
+
+describe('readonly field metadata (C++ ES_PROPERTY(readonly) → COMPONENT_META)', () => {
+ it("exposes Transform's engine-computed world fields as readonly", () => {
+ expect([...readonlyFieldsFor('Transform')]).toEqual(['worldPosition', 'worldRotation', 'worldScale']);
+ });
+ it('reports no readonly fields for components that have none', () => {
+ expect(readonlyFieldsFor('Sprite')).toEqual([]);
+ expect(readonlyFieldsFor('NotAComponent')).toEqual([]);
+ });
+});
function sceneWithUnknown(): SceneData {
return {
@@ -95,6 +105,57 @@ describe.skipIf(!HAS_WASM)('Model-authoritative projection + lossless save', ()
expect((wave!.data as { amplitude: number }).amplitude).toBe(5);
});
+ it('a Transform edit preserves the engine-computed world fields (never clobbers them to the origin)', () => {
+ // worldPosition/worldRotation/worldScale are ES_PROPERTY(readonly) — engine
+ // outputs composed each frame, not authoring inputs. Seed a sentinel world
+ // transform (standing in for that composition), then edit a LOCAL field: the
+ // reconciler must re-use the live readonly values, not reset them to the model's
+ // zero default. That reset was the bug — a moving entity's gizmo snapped to 0,0.
+ host.world.set(runtime1, Transform, {
+ position: { x: 1, y: 2, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 },
+ worldPosition: { x: 7, y: 8, z: 9 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ worldScale: { x: 3, y: 3, z: 3 },
+ } as never);
+
+ S.commands.setField(1, 'Transform', 'position', 'vec3', [9, 8, 7]); // by source id
+
+ const t = host.world.get(runtime1, Transform) as {
+ position: { x: number };
+ worldPosition: { x: number; y: number; z: number };
+ worldScale: { x: number };
+ };
+ expect(t.position.x).toBe(9); // the local edit applied
+ expect(t.worldPosition).toMatchObject({ x: 7, y: 8, z: 9 }); // preserved, NOT zeroed
+ expect(t.worldScale.x).toBe(3);
+ });
+
+ it('attachUINodeBox adds a sized UINode + reparents under the Canvas as one undo step', () => {
+ const canvas = S.model.addEntity('Canvas', [{ type: 'Transform', data: {} }, { type: 'Canvas', data: {} }] as never);
+ const text = S.model.addEntity('Label', [{ type: 'Transform', data: {} }, { type: 'Text', data: { content: 'Hi' } }] as never);
+
+ S.commands.attachUINodeBox(text, canvas, 240, 80);
+ const e = S.model.entityBySource(text)!;
+ expect(e.parent).toBe(canvas);
+ const ui = e.components.find((c) => c.type === 'UINode')!.data as { width: { value: number; unit: number } };
+ expect(ui.width).toMatchObject({ value: 240, unit: 0 });
+
+ S.history.undo(); // a single step reverts BOTH the UINode add and the reparent
+ const u = S.model.entityBySource(text)!;
+ expect(u.components.some((c) => c.type === 'UINode')).toBe(false);
+ expect(u.parent ?? null).toBeNull();
+ });
+
+ it('attachUINodeBox is a no-op when the Text already has a UINode', () => {
+ const canvas = S.model.addEntity('Canvas', [{ type: 'Transform', data: {} }, { type: 'Canvas', data: {} }] as never);
+ const text = S.model.addEntity('Label', [{ type: 'Transform', data: {} }, { type: 'UINode', data: {} }, { type: 'Text', data: {} }] as never);
+
+ S.commands.attachUINodeBox(text, canvas, 240, 80);
+ expect(S.model.entityBySource(text)!.parent ?? null).toBeNull(); // left where it was
+ });
+
it('undo of a field edit reverts the model too', () => {
S.commands.setField(1, 'Transform', 'position', 'vec3', [9, 0, 0]); // by source id
S.history.undo();
diff --git a/desktop/tests/text-align-notice.test.ts b/desktop/tests/text-align-notice.test.ts
new file mode 100644
index 000000000..a85ac1911
--- /dev/null
+++ b/desktop/tests/text-align-notice.test.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Text align/verticalAlign resolve against a layout box (a UINode laid out
+ * under a Canvas); a boxless Text anchors to its origin instead. The inspector
+ * surfaces that ONLY when the user has set a non-default alignment, so the
+ * anchor behavior is explained rather than looking like a broken field.
+ */
+import { describe, it, expect } from 'vitest';
+import { componentNotice } from '@/engine/schema';
+
+const entity = (comps: { type: string; data?: unknown }[]) =>
+ ({
+ id: 1, name: 'T', parent: null, children: [],
+ components: comps.map((c) => ({ type: c.type, data: c.data ?? {} })),
+ }) as never;
+
+describe('Text alignment notice', () => {
+ it('explains anchor-to-origin when a boxless Text has a non-default alignment', () => {
+ const e = entity([{ type: 'Transform' }, { type: 'Text', data: { align: 1, verticalAlign: 0 } }]);
+ expect(componentNotice('Text', e)).toMatch(/anchors the text to the entity origin/);
+ });
+
+ it('stays silent for a default-aligned (Left/Top) boxless Text', () => {
+ const e = entity([{ type: 'Transform' }, { type: 'Text', data: { align: 0, verticalAlign: 0 } }]);
+ expect(componentNotice('Text', e)).toBeNull();
+ });
+
+ it('stays silent once the Text has a UINode layout box (alignment resolves within it)', () => {
+ const e = entity([{ type: 'Transform' }, { type: 'UINode' }, { type: 'Text', data: { align: 2, verticalAlign: 1 } }]);
+ expect(componentNotice('Text', e)).toBeNull();
+ });
+});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 2d4fde573..50cfc2fc5 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1057 stable · 44 beta · 1 deprecated
+Symbols: 1063 stable · 44 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -937,6 +937,7 @@ colorKeys: readonly string[]
discoverAssets: ((data: Record<string, unknown>) => AssetRef[]) | undefined
entityFields: readonly string[]
fieldMeta: Readonly<Record<string, FieldMeta>>
+readonlyFields: readonly string[]
replicatedFields: readonly string[]
spineFields: SpineFieldMeta | undefined
transient: boolean
@@ -1044,6 +1045,15 @@ startTime: number
target: number
```
+## CameraExtents — interface
+```
+cameraX: number
+cameraY: number
+entity: number
+halfH: number
+halfW: number
+```
+
## CameraPOV — interface
```
clearFlags: number
@@ -1103,6 +1113,13 @@ pixelsPerUnit: number
scaleMode: number
```
+## CanvasScale — interface
+```
+designResolution: { x: number; y: number; }
+matchWidthOrHeight: number
+scaleMode: number
+```
+
## CapsuleCollider — const
```
BuiltinComponentDef<CapsuleColliderData>
@@ -1331,6 +1348,7 @@ create: (data?: Partial<T>) => T
discoverAssets: ((data: Record<string, unknown>) => AssetRef[]) | undefined
entityFields: readonly string[]
fieldMeta: Readonly<Record<string, FieldMeta>>
+readonlyFields: readonly string[]
replicatedFields: readonly string[]
spineFields: SpineFieldMeta | undefined
transient: boolean
@@ -1343,6 +1361,7 @@ assetFields: AssetFieldMeta[] | undefined
discoverAssets: ((data: Record<string, unknown>) => AssetRef[]) | undefined
entityFields: string[] | undefined
fields: Record<string, FieldMeta> | undefined
+readonlyFields: string[] | undefined
replicatedFields: string[] | undefined
spineFields: SpineFieldMeta | undefined
transient: boolean | undefined
@@ -1854,6 +1873,11 @@ selectedIndex: number | undefined
world: World
```
+## EDITOR_VIEW_ENTITY — const
+```
+-1
+```
+
## ESEngineModule — interface
```
EstellaContext: new () => CppEngineContext
@@ -6758,6 +6782,14 @@ static new (): World
static prototype: World
```
+## WorldRect — interface
+```
+bottom: number
+left: number
+right: number
+top: number
+```
+
## WorldTransform — const
```
BuiltinComponentDef<TransformData>
@@ -7033,6 +7065,11 @@ BtPlugin
(graph: MaterialGraph): string
```
+## computeEffectiveOrthoSize — function
+```
+(baseOrthoSize: number, designAspect: number, actualAspect: number, scaleMode: number, matchWidthOrHeight: number): number
+```
+
## computeStreaming — function
```
(cells: readonly StreamCell[], focusX: number, focusY: number, loadRadius: number, unloadRadius: number, active: ReadonlySet<string>): StreamDecision
@@ -8488,6 +8525,11 @@ UIInteractionPlugin
UILayoutPlugin
```
+## uiLayoutRect — function
+```
+(cam: CameraExtents, canvas: CanvasScale | null, width: number, height: number): WorldRect
+```
+
## uiMaskPlugin — const
```
UIMaskPlugin
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 45e52ab2c..bc13236ab 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1056 stable · 46 beta · 1 deprecated
+Symbols: 1062 stable · 46 beta · 1 deprecated
## ActionDef — interface
```
@@ -932,6 +932,7 @@ colorKeys: readonly string[]
discoverAssets: ((data: Record<string, unknown>) => AssetRef[]) | undefined
entityFields: readonly string[]
fieldMeta: Readonly<Record<string, FieldMeta>>
+readonlyFields: readonly string[]
replicatedFields: readonly string[]
spineFields: SpineFieldMeta | undefined
transient: boolean
@@ -1039,6 +1040,15 @@ startTime: number
target: number
```
+## CameraExtents — interface
+```
+cameraX: number
+cameraY: number
+entity: number
+halfH: number
+halfW: number
+```
+
## CameraPOV — interface
```
clearFlags: number
@@ -1098,6 +1108,13 @@ pixelsPerUnit: number
scaleMode: number
```
+## CanvasScale — interface
+```
+designResolution: { x: number; y: number; }
+matchWidthOrHeight: number
+scaleMode: number
+```
+
## CapsuleCollider — const
```
BuiltinComponentDef<CapsuleColliderData>
@@ -1326,6 +1343,7 @@ create: (data?: Partial<T>) => T
discoverAssets: ((data: Record<string, unknown>) => AssetRef[]) | undefined
entityFields: readonly string[]
fieldMeta: Readonly<Record<string, FieldMeta>>
+readonlyFields: readonly string[]
replicatedFields: readonly string[]
spineFields: SpineFieldMeta | undefined
transient: boolean
@@ -1338,6 +1356,7 @@ assetFields: AssetFieldMeta[] | undefined
discoverAssets: ((data: Record<string, unknown>) => AssetRef[]) | undefined
entityFields: string[] | undefined
fields: Record<string, FieldMeta> | undefined
+readonlyFields: string[] | undefined
replicatedFields: string[] | undefined
spineFields: SpineFieldMeta | undefined
transient: boolean | undefined
@@ -1849,6 +1868,11 @@ selectedIndex: number | undefined
world: World
```
+## EDITOR_VIEW_ENTITY — const
+```
+-1
+```
+
## ESEngineModule — interface
```
EstellaContext: new () => CppEngineContext
@@ -6753,6 +6777,14 @@ static new (): World
static prototype: World
```
+## WorldRect — interface
+```
+bottom: number
+left: number
+right: number
+top: number
+```
+
## WorldTransform — const
```
BuiltinComponentDef<TransformData>
@@ -7028,6 +7060,11 @@ BtPlugin
(graph: MaterialGraph): string
```
+## computeEffectiveOrthoSize — function
+```
+(baseOrthoSize: number, designAspect: number, actualAspect: number, scaleMode: number, matchWidthOrHeight: number): number
+```
+
## computeStreaming — function
```
(cells: readonly StreamCell[], focusX: number, focusY: number, loadRadius: number, unloadRadius: number, active: ReadonlySet<string>): StreamDecision
@@ -8493,6 +8530,11 @@ UIInteractionPlugin
UILayoutPlugin
```
+## uiLayoutRect — function
+```
+(cam: CameraExtents, canvas: CanvasScale | null, width: number, height: number): WorldRect
+```
+
## uiMaskPlugin — const
```
UIMaskPlugin
diff --git a/sdk/src/component.generated.ts b/sdk/src/component.generated.ts
index ffe1a664a..9fe823799 100644
--- a/sdk/src/component.generated.ts
+++ b/sdk/src/component.generated.ts
@@ -49,6 +49,13 @@ export interface ComponentMetaEntry {
replicatedFields?: string[];
/** Fields authored `skip_serialize` — runtime-only state scene serialization omits. */
skipSerializeFields?: string[];
+ /**
+ * Fields authored `readonly` — engine-COMPUTED outputs (e.g. Transform's
+ * world-space fields), never authoring inputs. The editor must not project
+ * them back into the World: writing their (stale/zero) model value clobbers
+ * the value the engine composes each frame.
+ */
+ readonlyFields?: string[];
fields?: Record<string, FieldMeta>;
}
@@ -602,6 +609,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
colorFields: [],
animatableFields: ['position.x', 'position.y', 'position.z', 'rotation.z', 'scale.x', 'scale.y', 'scale.z'],
replicatedFields: ['position', 'rotation', 'scale'],
+ readonlyFields: ['worldPosition', 'worldRotation', 'worldScale'],
fields: {
position: { tooltip: "Local position in world units, relative to the parent." },
rotation: { tooltip: "Rotation about the Z axis, in degrees." },
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index a8fbca521..314e648d1 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -99,6 +99,12 @@ export interface ComponentMetadata {
* ES_PROPERTY site (`replicated`) instead — same single-source rule as fieldMeta.
*/
replicatedFields?: string[];
+ /**
+ * Engine-COMPUTED output fields (Transform's world-space fields), authored
+ * `readonly` at the C++ ES_PROPERTY site. Never authoring inputs — the editor
+ * must not project them into the World (it clobbers the composed value).
+ */
+ readonlyFields?: string[];
/**
* Custom asset discovery for scene preload. Authoritative when present:
* `assetFields` are NOT walked for discovery (they still drive editor
@@ -154,6 +160,8 @@ export interface ComponentDef<T> {
readonly animatableFields: readonly string[];
/** Fields the replication layer syncs; empty = never replicates. See {@link ComponentMetadata.replicatedFields}. */
readonly replicatedFields: readonly string[];
+ /** Engine-computed output fields the editor must never write back. See {@link ComponentMetadata.readonlyFields}. */
+ readonly readonlyFields: readonly string[];
readonly fieldMeta: Readonly<Record<string, FieldMeta>>;
readonly discoverAssets?: (data: Record<string, unknown>) => AssetRef[];
/** Runtime-only: omitted from scene serialization. See {@link ComponentMetadata.transient}. */
@@ -240,6 +248,7 @@ function createComponentDef<T extends object>(
colorKeys: detectColorKeys(defaults),
animatableFields: metadata?.animatableFields ?? numericAnimatableFields(defaults),
replicatedFields: metadata?.replicatedFields ?? [],
+ readonlyFields: metadata?.readonlyFields ?? [],
fieldMeta: metadata?.fields ?? {},
discoverAssets: metadata?.discoverAssets,
transient: metadata?.transient ?? false,
@@ -372,6 +381,8 @@ export interface BuiltinComponentDef<T> {
readonly animatableFields: readonly string[];
/** Fields authored `replicated` at the C++ ES_PROPERTY site (via COMPONENT_META). */
readonly replicatedFields: readonly string[];
+ /** Fields authored `readonly` (engine-computed outputs); the editor never writes them back. */
+ readonly readonlyFields: readonly string[];
readonly fieldMeta: Readonly<Record<string, FieldMeta>>;
readonly discoverAssets?: (data: Record<string, unknown>) => AssetRef[];
/** Runtime-only: omitted from scene serialization. See {@link ComponentMetadata.transient}. */
@@ -526,6 +537,7 @@ export function defineBuiltin<T>(name: string, defaults: T, metadata?: Component
colorKeys: meta?.colorFields ?? detectColorKeys(defaults),
animatableFields: meta?.animatableFields ?? [],
replicatedFields: meta?.replicatedFields ?? [],
+ readonlyFields: meta?.readonlyFields ?? [],
fieldMeta: mergeFieldMeta(meta?.fields ?? {}, metadata?.fields ?? {}),
discoverAssets: metadata?.discoverAssets,
// Builtins declare transience via the defineBuiltin metadata arg for now;
diff --git a/sdk/src/ui/core/text.ts b/sdk/src/ui/core/text.ts
index 578610a8d..7f54b35ae 100644
--- a/sdk/src/ui/core/text.ts
+++ b/sdk/src/ui/core/text.ts
@@ -82,8 +82,8 @@ export const Text = defineComponent<TextData>('Text', {
enabled: true,
}, {
fields: {
- align: { enum: enumOptions(TextAlign) },
- verticalAlign: { enum: enumOptions(TextVerticalAlign) },
+ align: { enum: enumOptions(TextAlign), tooltip: 'Horizontal alignment: within the layout box when the entity has a UINode, else it anchors the text to the entity origin (left/center/right edge).' },
+ verticalAlign: { enum: enumOptions(TextVerticalAlign), tooltip: 'Vertical alignment: within the layout box when the entity has a UINode, else it anchors the text to the entity origin (top/middle/bottom).' },
overflow: { enum: enumOptions(TextOverflow) },
renderMode: { enum: enumOptions(TextRenderMode) },
},
diff --git a/sdk/src/ui/text/layout.ts b/sdk/src/ui/text/layout.ts
index 44091ac2e..938673d0b 100644
--- a/sdk/src/ui/text/layout.ts
+++ b/sdk/src/ui/text/layout.ts
@@ -154,6 +154,12 @@ export interface MultilineTextOptions extends TextLayoutOptions {
color?: RGBA;
/** Word-wrap width in display px (plain text only). 0/undefined = no wrap. */
maxWidth?: number;
+ /**
+ * Width (display px) each line is horizontally aligned within — the layout box.
+ * Defaults to `maxWidth`, else the widest line. Separating it from `maxWidth` lets
+ * horizontal align work inside a fixed box even when word-wrap is off.
+ */
+ boxWidth?: number;
}
/** Sum of glyph advances for a string at the given size (display px). Pure. */
@@ -237,8 +243,11 @@ export function layoutText(
: layoutLine(line, atlas, fontFamily, opts, style)));
const contentWidth = lineLayouts.reduce((m, l) => Math.max(m, l.width), 0);
- // Align within the wrap/rect box when one is given, else within the widest line.
- const alignWidth = (opts.maxWidth && opts.maxWidth > 0) ? opts.maxWidth : contentWidth;
+ // Align within the layout box when one is given (independent of word-wrap), then
+ // the wrap width, else the widest line.
+ const alignWidth = (opts.boxWidth && opts.boxWidth > 0) ? opts.boxWidth
+ : (opts.maxWidth && opts.maxWidth > 0) ? opts.maxWidth
+ : contentWidth;
const glyphs: LaidGlyph[] = [];
for (let i = 0; i < lineLayouts.length; i++) {
diff --git a/sdk/src/ui/text/plugin.ts b/sdk/src/ui/text/plugin.ts
index c603db2f2..beecedd4d 100644
--- a/sdk/src/ui/text/plugin.ts
+++ b/sdk/src/ui/text/plugin.ts
@@ -113,6 +113,7 @@ export class TextPlugin implements Plugin {
let originX: number | undefined;
let originY: number | undefined;
let maxWidth: number | undefined;
+ let boxWidth: number | undefined;
let boxHeight: number | undefined;
let layer = 0;
let w = 0, h = 0, hasBox = false;
@@ -125,8 +126,9 @@ export class TextPlugin implements Plugin {
const box = rectTextBox(0.5, 0.5, w, h, t.fontSize);
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;
+ if (t.wordWrap) maxWidth = box.maxWidth; // wrap only when enabled
const order = module.ui_getRenderOrder
? module.ui_getRenderOrder(registry, entity as number)
@@ -160,6 +162,7 @@ export class TextPlugin implements Plugin {
verticalAlign: t.verticalAlign,
lineHeight: lineHeightPx,
maxWidth,
+ boxWidth,
boxHeight,
originX,
originY,
diff --git a/sdk/src/ui/text/text-renderer.ts b/sdk/src/ui/text/text-renderer.ts
index 30b3756b3..89a8c3a38 100644
--- a/sdk/src/ui/text/text-renderer.ts
+++ b/sdk/src/ui/text/text-renderer.ts
@@ -38,9 +38,11 @@ export interface DrawTextParams {
letterSpacing?: number;
/** Word-wrap width in px (plain text); 0/undefined = no wrap. */
maxWidth?: number;
+ /** Box width (px) horizontal align positions the block within; 0/undefined = boxless (anchor to origin). */
+ boxWidth?: number;
/** Vertical alignment within boxHeight: 0 top | 1 middle | 2 bottom. */
verticalAlign?: number;
- /** Box height (px) for vertical alignment; omit for top-anchored. */
+ /** Box height (px) for vertical alignment; 0/undefined = boxless (anchor to origin). */
boxHeight?: number;
/** Drop shadow: an offset, recolored copy of the glyphs drawn behind the fill. */
shadow?: { color: RGBA; dx: number; dy: number };
@@ -69,14 +71,21 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTex
rich: p.richText,
color: p.color,
maxWidth: p.maxWidth,
+ boxWidth: p.boxWidth,
}, p.style ?? 0);
if (layout.glyphs.length === 0) return;
- // Vertical alignment within the box: shift the whole block down (y-up) by the
- // slack between the box and the content. layout.lineHeight is total block height.
+ // Position the block within its box: [originX .. originX+boxWidth] × [originY .. -boxHeight].
+ // A boxless label (box 0×0) collapses the box to the entity origin, so align/verticalAlign
+ // ANCHOR the whole block to it rather than silently doing nothing — one rule, both cases.
+ const boxHeight = p.boxHeight ?? 0;
+ const boxWidth = p.boxWidth ?? 0;
+
+ // Vertical: shift the block down (y-up) by the slack between box and content. With a
+ // zero-height box the slack is -blockHeight, which anchors the block to the origin.
let originY = p.originY ?? 0;
- if (p.boxHeight && p.boxHeight > 0 && p.verticalAlign) {
- const slack = p.boxHeight - layout.lineHeight;
+ if (p.verticalAlign) {
+ const slack = boxHeight - layout.lineHeight;
originY -= p.verticalAlign === 1 ? slack / 2 : slack; // 1 middle, 2 bottom
}
@@ -89,7 +98,13 @@ export function drawTextWith(atlas: GlyphAtlas, sink: GlyphBatchSink, p: DrawTex
arr.push(g);
}
- const baseX = p.originX ?? 0;
+ // Horizontal: layoutText aligned each LINE within the box width (boxed) or the
+ // widest line (boxless). For a boxless label, anchor the whole block to the origin
+ // per align — left = left edge at origin, center = centered, right = right edge.
+ let baseX = p.originX ?? 0;
+ if (boxWidth <= 0 && p.align) {
+ baseX -= p.align === 1 ? layout.width / 2 : layout.width; // 1 center, 2 right
+ }
// Emit the glyph set once per page, recolored + offset. All passes are SDF
// glyphs in the same atlas/layer, so they batch and draw in submit order —
// shadow + outline first (behind), fill last (on top).
diff --git a/sdk/tests/ui-text-renderer.test.ts b/sdk/tests/ui-text-renderer.test.ts
index 2bb01cb45..5ade999fa 100644
--- a/sdk/tests/ui-text-renderer.test.ts
+++ b/sdk/tests/ui-text-renderer.test.ts
@@ -83,4 +83,37 @@ describe('REARCH_GUI P1.3b: drawTextWith', () => {
drawTextWith(atlas, sink, { text: ' ', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1] });
expect(sink).not.toHaveBeenCalled();
});
+
+ // The first vertex x/y of the fill (last) pass — the block's anchor moves it.
+ const drawFirst = (extra: Record<string, unknown>): { x: number; y: number } => {
+ const sink = vi.fn();
+ drawTextWith(makeAtlas(1024), sink, { text: 'AB', fontFamily: 'Arial', fontSizePx: 24, color: [1, 1, 1, 1], ...extra });
+ const verts = sink.mock.calls.at(-1)![0] as Float32Array;
+ return { x: verts[0], y: verts[1] };
+ };
+
+ it('a boxless label anchors the block to the origin by horizontal align (no UINode box)', () => {
+ // No boxWidth ⇒ world-space label: align shifts the whole block, not silently a no-op.
+ const left = drawFirst({ align: 0 }).x;
+ const center = drawFirst({ align: 1 }).x;
+ const right = drawFirst({ align: 2 }).x;
+ expect(center).toBeLessThan(left); // centered → block moved left of the origin
+ expect(right).toBeLessThan(center); // right edge on the origin → moved further left
+ });
+
+ it('a boxless label anchors the block to the origin by vertical align', () => {
+ const top = drawFirst({ verticalAlign: 0 }).y;
+ const middle = drawFirst({ verticalAlign: 1 }).y;
+ const bottom = drawFirst({ verticalAlign: 2 }).y;
+ expect(middle).toBeGreaterThan(top); // y-up: middle raises the block toward the origin
+ expect(bottom).toBeGreaterThan(middle);
+ });
+
+ it('horizontal align works inside a fixed box even with word-wrap off (boxWidth, no maxWidth)', () => {
+ // boxWidth aligns within the box independently of maxWidth (wrap). The block was
+ // previously left-anchored whenever wrap was off — align silently did nothing.
+ const leftInBox = drawFirst({ align: 0, boxWidth: 400 }).x;
+ const rightInBox = drawFirst({ align: 2, boxWidth: 400 }).x;
+ expect(rightInBox).toBeGreaterThan(leftInBox + 100); // pushed toward the box's right edge
+ });
});
diff --git a/tools/eht/generators/metadata.py b/tools/eht/generators/metadata.py
index 879e8f0a4..bce38e1c0 100644
--- a/tools/eht/generators/metadata.py
+++ b/tools/eht/generators/metadata.py
@@ -155,6 +155,9 @@ class MetadataGenerator:
def _get_skip_serialize_fields(self, comp: Component) -> List[str]:
return [p.name for p in comp.properties if 'skip_serialize' in p.annotations]
+ def _get_readonly_fields(self, comp: Component) -> List[str]:
+ return [p.name for p in comp.properties if 'readonly' in p.annotations]
+
def _get_animatable_fields(self, comp: Component) -> List[str]:
fields = []
for prop in comp.properties:
@@ -311,6 +314,13 @@ class MetadataGenerator:
' replicatedFields?: string[];',
' /** Fields authored `skip_serialize` — runtime-only state scene serialization omits. */',
' skipSerializeFields?: string[];',
+ ' /**',
+ ' * Fields authored `readonly` — engine-COMPUTED outputs (e.g. Transform\'s',
+ ' * world-space fields), never authoring inputs. The editor must not project',
+ ' * them back into the World: writing their (stale/zero) model value clobbers',
+ ' * the value the engine composes each frame.',
+ ' */',
+ ' readonlyFields?: string[];',
' fields?: Record<string, FieldMeta>;',
'}',
'',
@@ -384,6 +394,10 @@ class MetadataGenerator:
if skip_serialize:
parts = ', '.join(f"'{f}'" for f in skip_serialize)
lines.append(f' skipSerializeFields: [{parts}],')
+ readonly = self._get_readonly_fields(comp)
+ if readonly:
+ parts = ', '.join(f"'{f}'" for f in readonly)
+ lines.append(f' readonlyFields: [{parts}],')
field_meta = self._get_field_meta(comp)
if field_meta: