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(editor): what the editor authors in is space, not a plane
esengine78ff6c8def06
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.tsindex a918384b2..77dbfe926 100644--- a/desktop/src/commands/editorCommands.ts+++ b/desktop/src/commands/editorCommands.ts@@ -317,8 +317,8 @@ function nudgeSelection(ux: number, uy: number, big: boolean): void {SceneCommands.transact('Nudge', () => {for (const sid of ids) {const rt = SceneModel.runtimeFor(sid);- const pos = rt != null ? ViewportController.getEntityWorldXY(rt) : null;- if (pos) SceneCommands.setEntityXY(sid, pos.x + ux * step, pos.y + uy * step);+ const pos = rt != null ? ViewportController.getEntityWorldPos(rt) : null;+ if (pos) SceneCommands.setEntityWorldPos(sid, pos.x + ux * step, pos.y + uy * step);}});}diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.tsindex b59abbff5..31fe97158 100644--- a/desktop/src/engine/EditorControlSurface.ts+++ b/desktop/src/engine/EditorControlSurface.ts@@ -596,7 +596,7 @@ export class EditorControlSurfaceImpl {this.s.commands.removeComponent(entity, component);}setEntityXY(id: EntityId, x: number, y: number): void {- this.s.commands.setEntityXY(id, x, y);+ this.s.commands.setEntityWorldPos(id, x, y);}/** Coalesce a burst of setField writes (a drag) into one undo step. */beginGesture(label: string): void {diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 179c33d51..84f7ce911 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -195,7 +195,7 @@ export type EditHook = (export class SceneCommandsImpl {// — Field-edit gesture: coalesce a focus→blur / drag into a single undo step. —// Undo recording is INTERNAL: the only public write door is `setField` (and- // `setEntityXY`, which routes through it), and it always records. Outside a+ // `setEntityWorldPos`, which routes through it), and it always records. Outside a// gesture, one `setField` = one undo step. Inside a gesture, writes coalesce —// the BEFORE model value is captured on first touch of each field, the AFTER// value read at `endGesture`, and the pair recorded as one model-op step.@@ -552,19 +552,21 @@ export class SceneCommandsImpl {}/**- * Move an entity to a world position. `Transform.position` is parent-local, so a- * parented entity's world target is re-expressed in its parent's live frame:- * viewport tools speak world space, the model invariant stays local. `z` is the- * LOCAL depth (as a rotate writes it); omitting it keeps what the entity has.+ * Move an entity to a world position — all three coordinates world, all three+ * through the parent's one inverse (`Transform.position` is parent-local, and+ * viewport tools speak world). Omitting `z` keeps the depth the entity has,+ * read off the same composed transform the caller's x/y came from.*/- setEntityXY(sourceId: EntityId, x: number, y: number, z?: number): void {+ setEntityWorldPos(sourceId: EntityId, x: number, y: number, z?: number): void {if (this.setUINodeXY_(sourceId, x, y)) return;const entity = this.model.entityBySource(sourceId);const pos = this.modelFieldValue(sourceId, 'Transform', 'position') as { z?: number } | undefined;if (pos === undefined && !entity) return;+ const rt = this.model.runtimeFor(sourceId);+ const worldZ = z ?? (rt != null ? ViewportController.entityPlaneZ(rt) : (pos?.z ?? 0));const parentRt = entity?.parent != null ? this.model.runtimeFor(entity.parent) : undefined;- const local = ViewportController.worldToParentLocalXY(parentRt, x, y);- this.setField(sourceId, 'Transform', 'position', 'vec3', [local.x, local.y, z ?? pos?.z ?? 0]);+ const local = ViewportController.worldToParentLocal(parentRt, { x, y, z: worldZ });+ this.setField(sourceId, 'Transform', 'position', 'vec3', [local.x, local.y, local.z]);}/**@@ -946,7 +948,7 @@ export class SceneCommandsImpl {*/create(prefab: PrefabData,- opts: { parent: EntityId | null; position?: { x: number; y: number }; linkPrefabRef?: string; name?: string },+ opts: { parent: EntityId | null; position?: { x: number; y: number; z?: number }; linkPrefabRef?: string; name?: string },): EntityId | null {if (!this.model.current) return null;const ref = opts.linkPrefabRef ?? '';@@ -974,6 +976,9 @@ export class SceneCommandsImpl {const p = ((tf.data as Record<string, unknown>).position ??= { x: 0, y: 0, z: 0 }) as { x: number; y: number; z: number };p.x = opts.position.x;p.y = opts.position.y;+ // A drop point in a 3D view has a depth of its own; without one the template+ // keeps the depth it was authored at, which is what every 2D caller means.+ if (opts.position.z !== undefined) p.z = opts.position.z;}}@@ -1027,7 +1032,7 @@ export class SceneCommandsImpl {prefab: PrefabData,ref: string,parent: EntityId | null,- position?: { x: number; y: number },+ position?: { x: number; y: number; z?: number },name?: string,): EntityId | null {return this.create(prefab, { parent, position, linkPrefabRef: ref, name });diff --git a/desktop/src/engine/StatsStore.ts b/desktop/src/engine/StatsStore.tsindex cf8eccc7b..d941283d0 100644--- a/desktop/src/engine/StatsStore.ts+++ b/desktop/src/engine/StatsStore.ts@@ -68,7 +68,7 @@ const vramEq = (a: VramReadout | null, b: VramReadout | null): boolean =>class StatsStoreImpl {private readonly store = createStore<StatsSnapshot>(() => ({ fps: 0, entities: 0, selection: null, vram: null }));// Pointer-rate churn stays out of the slow-stats subscribers.- private readonly cursorStore = createStore<{ x: number; y: number } | null>(() => null);+ private readonly cursorStore = createStore<{ x: number; y: number; axes: [string, string] } | null>(() => null);// The hovered tile cell (coords + id) while painting a tilemap, or null.private readonly tileStore = createStore<{ tx: number; ty: number; id: number } | null>(() => null);@@ -123,13 +123,18 @@ class StatsStoreImpl {this.windowStart = 0;}- /** Report the viewport cursor world position (rounded; ignores no-op moves). */- setCursor(x: number, y: number) {- const cx = Math.round(x);- const cy = Math.round(y);+ /**+ * Report where the cursor is on the plane the view works on (rounded; ignores+ * no-op moves). `axes` names the two world axes those numbers are, because on a+ * ground plane they are x and z — a readout that always says x/y is telling the+ * user the wrong two.+ */+ setCursor(u: number, v: number, axes: readonly [string, string]) {+ const cu = Math.round(u);+ const cv = Math.round(v);const cur = this.cursorStore.getState();- if (cur && cur.x === cx && cur.y === cy) return;- this.cursorStore.setState({ x: cx, y: cy }, true);+ if (cur && cur.x === cu && cur.y === cv && cur.axes[0] === axes[0] && cur.axes[1] === axes[1]) return;+ this.cursorStore.setState({ x: cu, y: cv, axes: [axes[0], axes[1]] }, true);}clearCursor() {@@ -150,7 +155,7 @@ class StatsStoreImpl {subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);getSnapshot = (): StatsSnapshot => this.store.getState();subscribeCursor = (fn: () => void): (() => void) => this.cursorStore.subscribe(fn);- getCursor = (): { x: number; y: number } | null => this.cursorStore.getState();+ getCursor = (): { x: number; y: number; axes: [string, string] } | null => this.cursorStore.getState();subscribeTile = (fn: () => void): (() => void) => this.tileStore.subscribe(fn);getTile = (): { tx: number; ty: number; id: number } | null => this.tileStore.getState();}diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.tsindex 24c40243c..316d63084 100644--- a/desktop/src/engine/ViewportController.ts+++ b/desktop/src/engine/ViewportController.ts@@ -19,6 +19,7 @@ import {pickEntitiesByRay, editorViewIsOrbited,moveEditorViewFocus, editorViewBoxExtent,editorViewAxes, editorViewAxisAngles, cameraFrustumCorners, type ScreenAxis,+ editorViewWorkPlane, worldAxisVector,lightAimOf,rayPlaneHit, type WorldRay, type Vec3,type TilesetModel, type TileCollisionPiece, type TileGridParams,@@ -34,7 +35,7 @@ import {obbCorners,rectsIntersect,screenAABB,- worldToLocal2D,+ worldToLocal3D,} from './viewportMath';// Half-length of a 3D joint's axis marker, in world units — long enough to read@@ -232,11 +233,35 @@ export const ViewportController = {return ray ? rayPlaneHit(ray, point, normal) : null;},- /** The world z an entity sits on — the plane its picking and dragging happen on. */+ /** The two world axes the view's work plane runs in, as their letters — what a+ * coordinate readout on that plane is naming. */+ workPlaneAxes(): [string, string] {+ const view = editorView();+ const plane = editorViewWorkPlane(view ?? { perspective: false } as EditorViewData);+ const letter = ['x', 'y', 'z'];+ return [letter[plane.u]!, letter[plane.v]!];+ },++ /**+ * Where the cursor lands on {@link editorViewWorkPlane} — the ground under a+ * perspective eye, the 2D plane under an orthographic one, and where a thing+ * dropped here goes. {@link canvasToWorld} answers for a z plane instead, which+ * asks about an entity already somewhere, not about where a new one belongs.+ */+ canvasToWorkPlane(clientX: number, clientY: number): Vec3 | null {+ const view = editorView();+ if (!view) return null;+ const plane = editorViewWorkPlane(view);+ const normal = worldAxisVector(plane.normal);+ // Through the world origin, which is the plane the GRID draws: a drop lands on+ // the surface the person can see, and panning the eye does not carry the floor+ // along with it.+ return this.canvasToWorldOnPlane(clientX, clientY, { x: 0, y: 0, z: 0 }, normal);+ },++ /** The world z an entity sits on — the plane its overlays and drags happen on. */entityPlaneZ(e: EntityId): number {- const world = EngineHost.world;- if (!world || !world.has(e, Transform)) return 0;- return (world.get(e, Transform) as { position?: { z?: number } }).position?.z ?? 0;+ return this.getEntityWorldPos(e)?.z ?? 0;},/**@@ -404,16 +429,16 @@ export const ViewportController = {},/**- * The entity's world-space position — parent-composed, the same value the- * renderer places it at. For UI nodes this is the laid-out box center (the- * Yoga pass writes local `position`; the transform pass composes it), so the- * gizmo lands on the element, not on its parent-relative offset.+ * Where the entity is — parent-composed, the same value the renderer places it+ * at. For UI nodes that is the laid-out box center, so a gizmo lands on the+ * element rather than on its parent-relative offset. All three components come+ * from the SAME composed transform; the LOCAL `position.z` is a different plane.*/- getEntityWorldXY(id: EntityId): { x: number; y: number } | null {+ getEntityWorldPos(id: EntityId): Vec3 | null {const world = EngineHost.world;if (!world || !world.valid(id) || !world.has(id, Transform)) return null;const t = world.get(id, Transform);- return { x: t.worldPosition.x, y: t.worldPosition.y };+ return { x: t.worldPosition.x, y: t.worldPosition.y, z: t.worldPosition.z };},/** The entity's world rotation about Z (radians) — drives the local-space gizmo frame. */@@ -435,21 +460,21 @@ export const ViewportController = {/*** A world point re-expressed in `parentId`'s live world frame — the local- * `Transform.position` a child at that world spot must hold. No/invalid- * parent ⇒ the point is already root-local.+ * `Transform.position` a child at that world spot must hold. No/invalid parent+ * ⇒ the point is already root-local. The parent's WHOLE frame inverts: a 2D+ * inverse plus an untouched z holds only while the chain lies flat.*/- worldToParentLocalXY(parentId: EntityId | null | undefined, wx: number, wy: number): { x: number; y: number } {+ worldToParentLocal(parentId: EntityId | null | undefined, w: Vec3): Vec3 {const world = EngineHost.world;if (parentId == null || !world || !world.valid(parentId) || !world.has(parentId, Transform)) {- return { x: wx, y: wy };+ return { x: w.x, y: w.y, z: w.z };}const t = world.get(parentId, Transform);- return worldToLocal2D(wx, wy, {- x: t.worldPosition.x,- y: t.worldPosition.y,- rot: quatAngleZ(t.worldRotation as { w: number; x: number; y: number; z: number }),- sx: t.worldScale.x,- sy: t.worldScale.y,+ const q = t.worldRotation as { w: number; x: number; y: number; z: number };+ return worldToLocal3D(w, {+ pos: { x: t.worldPosition.x, y: t.worldPosition.y, z: t.worldPosition.z },+ rot: { x: q.x, y: q.y, z: q.z, w: q.w },+ scale: { x: t.worldScale.x, y: t.worldScale.y, z: t.worldScale.z },});},@@ -1407,11 +1432,8 @@ export const ViewportController = {} | undefined;if (!d?.cellSize) return null;const rt = SceneModel.runtimeFor(id);- const xy = rt != null ? this.getEntityWorldXY(rt) : null;- if (!xy || rt == null) return null;- // The origin is a point in space, not on a plane: the overlay draws on the- // layer's own depth so it lands on the tiles under a perspective view.- const origin = { ...xy, z: this.entityPlaneZ(rt) };+ const origin = rt != null ? this.getEntityWorldPos(rt) : null;+ if (!origin || rt == null) return null;return {params: {orientation: d.orientation ?? 0,diff --git a/desktop/src/engine/entityOps.ts b/desktop/src/engine/entityOps.tsindex 0c0f175a2..7a440e2bf 100644--- a/desktop/src/engine/entityOps.ts+++ b/desktop/src/engine/entityOps.ts@@ -96,7 +96,7 @@ export const EntityOps = {}const src = srcIdOf(ref);if (src == null || !point.world) return null;- SceneCommands.setEntityXY(src, point.world.x, point.world.y);+ SceneCommands.setEntityWorldPos(src, point.world.x, point.world.y);return 'document';},diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.tsindex 2da87c3e3..38025dea9 100644--- a/desktop/src/engine/entitySources.ts+++ b/desktop/src/engine/entitySources.ts@@ -25,10 +25,12 @@ import { componentGlyph, primitiveGlyph } from '@/components/icons';import { SceneCommands } from './SceneCommands';import { EngineHost } from './EngineHost';-/** Where a source is created: the target parent + (for asset/drop sources) its origin. */+/** Where a source is created: the target parent + (for asset/drop sources) its origin.+ * The origin is a point in space — a viewport drop resolves it on the plane the view+ * works on, which under a 3D eye is the ground rather than z = 0. */export interface CreateContext {parent: EntityId | null;- position?: { x: number; y: number };+ position?: { x: number; y: number; z?: number };assetPath?: string;/** Name the new entity instead of taking the template's own — one undo step, and* for a prefab template it becomes an ordinary `name` override. */diff --git a/desktop/src/engine/viewportMath.ts b/desktop/src/engine/viewportMath.tsindex 32d4b9d25..1e03a7935 100644--- a/desktop/src/engine/viewportMath.ts+++ b/desktop/src/engine/viewportMath.ts@@ -2,9 +2,12 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file viewportMath.ts- * @brief Pure 2D geometry for viewport picking, marquee, and gizmos — no engine+ * @brief Pure geometry for viewport picking, marquee, and gizmos — no engine* state or DOM, so it unit-tests in isolation. The imperative shells* (ViewportController picking, the gizmo tools) layer on top of these.+ * Flat helpers stay flat because what they describe is (a tile cell, a+ * laid-out UI box); a transform frame is not one of those, and its+ * inverse is `worldToLocal3D`.* The one import is the SDK's pure mirror of the renderer's layer rules,* which picking has to rank by rather than restate.*/@@ -92,6 +95,30 @@ export function worldToLocal2D(wx: number, wy: number, frame: Frame2D): { x: numreturn { x: frame.sx ? rx / frame.sx : rx, y: frame.sy ? ry / frame.sy : ry };}+/** A world frame: translation, rotation, per-axis scale — one entity's TRS. */+export interface Frame3D {+ pos: Vec3;+ rot: Quat;+ scale: Vec3;+}++/**+ * A world point re-expressed in `frame`'s local coordinates — the inverse of the+ * engine's TRS compose (world = T + R·(S·local)), so local = S⁻¹·R⁻¹·(world − T).+ * A parent turned about X or Y has no 2D inverse, which is why the editor writes+ * through this one. A zero scale axis passes through undivided (no inverse).+ */+export function worldToLocal3D(w: Vec3, frame: Frame3D): Vec3 {+ const d = { x: w.x - frame.pos.x, y: w.y - frame.pos.y, z: w.z - frame.pos.z };+ const q = frame.rot;+ const r = rotateVec3(d, { x: -q.x, y: -q.y, z: -q.z, w: q.w });+ return {+ x: frame.scale.x ? r.x / frame.scale.x : r.x,+ y: frame.scale.y ? r.y / frame.scale.y : r.y,+ z: frame.scale.z ? r.z / frame.scale.z : r.z,+ };+}+/** Whether two client rects overlap (touching edges count as overlap). */export function rectsIntersect(a: ClientRect, b: ClientRect): boolean {return a.x <= b.x + b.w && b.x <= a.x + a.w && a.y <= b.y + b.h && b.y <= a.y + a.h;@@ -114,6 +141,25 @@ export const snapTo = (v: number, step: number): number => (step > 0 ? Math.rounexport interface Quat { x: number; y: number; z: number; w: number }+/** A point or direction in world space. */+export interface Vec3 { x: number; y: number; z: number }++/**+ * A vector turned by a quaternion (q·v·q⁻¹, expanded).+ *+ * The editor's ONE copy of this: a gizmo's local axes, a group rotation's arm and+ * a parent frame's inverse are the same turn, and three transcriptions of it are+ * three chances for the handle, the motion and the stored value to disagree.+ */+export function rotateVec3(v: Vec3, q: Quat): Vec3 {+ const t = { x: 2 * (q.y * v.z - q.z * v.y), y: 2 * (q.z * v.x - q.x * v.z), z: 2 * (q.x * v.y - q.y * v.x) };+ return {+ x: v.x + q.w * t.x + q.y * t.z - q.z * t.y,+ y: v.y + q.w * t.y + q.z * t.x - q.x * t.z,+ z: v.z + q.w * t.z + q.x * t.y - q.y * t.x,+ };+}+/** Quaternion for a turn of `rad` about a world axis. */export function axisQuat(axis: 'x' | 'y' | 'z', rad: number): Quat {const s = Math.sin(rad / 2);diff --git a/desktop/src/flipbook/createAnimatedSprite.ts b/desktop/src/flipbook/createAnimatedSprite.tsindex 82d426e97..0769efdd7 100644--- a/desktop/src/flipbook/createAnimatedSprite.ts+++ b/desktop/src/flipbook/createAnimatedSprite.ts@@ -45,7 +45,7 @@ function animClipSource(clipPath: string, clipRef: string, asset: AnimClipAssetD/** Create a Sprite + SpriteAnimator entity referencing the given .esanim and select it. */export async function createAnimatedSpriteFromClip(clipPath: string,- position?: { x: number; y: number },+ position?: { x: number; y: number; z?: number },): Promise<void> {const clipRef = AssetRegistry.assetRef(clipPath); // .esanim → @uuidif (!clipRef) {diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex 3fdc2b0cb..b8ce69c0d 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -711,7 +711,7 @@ function buildEditorAutomation(): unknown {* layout-rejected. */entityWorldXY: (id: number) => {const rt = SceneModel.runtimeFor(id);- return rt == null ? null : ViewportController.getEntityWorldXY(rt);+ return rt == null ? null : ViewportController.getEntityWorldPos(rt);},/** The LIVE World component data for a SOURCE entity — for verifying that a* model edit actually reached the engine (vs stayed model-only). */diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex 8bb919aa4..0264bb35a 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -103,7 +103,7 @@ function startRadiusHandleDrag(): void {if (e.button !== 0) return;const src = SceneModel.sourceFor(rt);- const center = centerOverride ?? ViewportController.getEntityWorldXY(rt);+ const center = centerOverride ?? ViewportController.getEntityWorldPos(rt);if (src == null || !center) return;e.stopPropagation();runHandleDrag(eventWindow(e), `${component} radius`, (ev) => {@@ -125,7 +125,7 @@ function startSizeHandleDrag(): void {if (e.button !== 0) return;const src = SceneModel.sourceFor(rt);- const center = centerOverride ?? ViewportController.getEntityWorldXY(rt);+ const center = centerOverride ?? ViewportController.getEntityWorldPos(rt);if (src == null || !center) return;e.stopPropagation();const rot = ViewportController.getEntityWorldAngleRad(rt);@@ -155,7 +155,7 @@ function startPivotHandleDrag(rt: number, e: ReactPointerEvent): void {if (!p) return;const next = pivotDrag(f, p);SceneCommands.setField(src, 'Sprite', 'pivot', 'vec2', [next.pivot.x, next.pivot.y]);- SceneCommands.setEntityXY(src, next.pos.x, next.pos.y);+ SceneCommands.setEntityWorldPos(src, next.pos.x, next.pos.y);});}@@ -173,7 +173,7 @@ function startColliderPointDrag(): void {if (e.button !== 0) return;const src = SceneModel.sourceFor(rt);- const origin = ViewportController.getEntityWorldXY(rt);+ const origin = ViewportController.getEntityWorldPos(rt);if (src == null || !origin) return;e.stopPropagation();const rot = ViewportController.getEntityWorldAngleRad(rt);@@ -347,7 +347,7 @@ function startUiResizeDrag(rt: number, edge: UiEdge, e: ReactPointerEvent): voidfunction startAngleHandleDrag(rt: number, e: ReactPointerEvent): void {if (e.button !== 0) return;const src = SceneModel.sourceFor(rt);- const center = ViewportController.getEntityWorldXY(rt);+ const center = ViewportController.getEntityWorldPos(rt);if (src == null || !center) return;e.stopPropagation();const rot = ViewportController.getEntityWorldAngleRad(rt);@@ -588,7 +588,7 @@ function HudCursor() {if (!cursor && !tile) return null;return (<>- {cursor && <strong>{cursor.x}, {cursor.y}</strong>}+ {cursor && <strong>{cursor.axes[0]} {cursor.x}, {cursor.axes[1]} {cursor.y}</strong>}{tile && (<span className="hud-tile">{' '}▦ {tile.tx}, {tile.ty}{tile.id ? ` #${tile.id}` : ''}@@ -1460,7 +1460,11 @@ export function Viewport() {// for a pivot that's never drawn.const drawPivot = ready && showG && toolMode !== 'select' && selIds.length > 0;const pivotWorld = drawPivot ? selectionPivot(selIds) : null;- const pivot = pivotWorld ? ViewportController.worldToClient(pivotWorld.x, pivotWorld.y) : null;+ // Through the pivot's OWN depth: the gizmo belongs on the selection, and a+ // projection that assumes z = 0 puts it on the selection's shadow there.+ const pivot = pivotWorld+ ? ViewportController.worldToClient(pivotWorld.x, pivotWorld.y, pivotWorld.z)+ : null;if (pivot) {// No screen rotation: local space is baked into each handle's own// direction (gizmo.ts), which a CSS rotate could only ever express in 2D.@@ -1500,7 +1504,7 @@ export function Viewport() {? SceneModel.entityBySource(sid)?.components.find((c) => c.type === 'TilemapLayer'): undefined;const cs = layer?.data as { cellSize?: { x: number; y: number } } | undefined;- const origin = ready && rt != null ? ViewportController.getEntityWorldXY(rt) : null;+ const origin = ready && rt != null ? ViewportController.getEntityWorldPos(rt) : null;if (tsel && cs?.cellSize && origin && !nonOrtho) {const x0 = Math.min(tsel.x0, tsel.x1);const y0 = Math.min(tsel.y0, tsel.y1);@@ -2136,8 +2140,12 @@ export function Viewport() {};const onPointerMove = (e: ReactPointerEvent) => {- const wp = ViewportController.canvasToWorld(e.clientX, e.clientY);- if (wp) StatsStore.setCursor(wp.x, wp.y);+ // On the plane the view works on, and labelled with the axes that plane runs+ // in: over a 3D scene the pair is x/z, and reporting a z = 0 crossing as x/y+ // is two wrong numbers under two wrong names.+ const [pu, pv] = ViewportController.workPlaneAxes();+ const wp = ViewportController.canvasToWorkPlane(e.clientX, e.clientY);+ if (wp) StatsStore.setCursor(wp[pu as 'x' | 'y' | 'z'], wp[pv as 'x' | 'y' | 'z'], [pu, pv]);if (orbitRef.current) {ViewportController.orbitByClient(orbitRef.current.px, orbitRef.current.py, e.clientX, e.clientY);@@ -2282,7 +2290,10 @@ export function Viewport() {}const path = e.dataTransfer.getData('application/x-estella-asset');if (!path) return;- const wp = ViewportController.canvasToWorld(e.clientX, e.clientY);+ // Scene content lands on the plane the VIEW works on — the ground under a 3D+ // eye, the 2D plane under the orthographic one. A z = 0 answer would be a wall+ // the cursor crosses somewhere the person is not pointing at.+ const wp = ViewportController.canvasToWorkPlane(e.clientX, e.clientY);if (path.toLowerCase().endsWith('.esprefab')) {e.preventDefault();// Place at the drop point; fall back to the prefab's authored origin if it@@ -2290,10 +2301,10 @@ export function Viewport() {void ProjectStore.instantiatePrefabFromPath(path, null, wp ?? undefined);} else if (IMAGE_RE.test(path)) {e.preventDefault();- void ProjectStore.instantiateSpriteFromPath(path, wp ?? { x: 0, y: 0 });+ void ProjectStore.instantiateSpriteFromPath(path, wp ?? { x: 0, y: 0, z: 0 });} else if (path.toLowerCase().endsWith('.esmesh')) {e.preventDefault();- void ProjectStore.instantiateMeshFromPath(path, wp ?? { x: 0, y: 0 });+ void ProjectStore.instantiateMeshFromPath(path, wp ?? { x: 0, y: 0, z: 0 });} else if (path.toLowerCase().endsWith('.estileset')) {e.preventDefault();// A tileset spawns a paintable TilemapLayer, which wires its own placement + painter.@@ -2425,7 +2436,7 @@ export function Viewport() {</div>{/* Align + distribute — contextual, appears once 2+ entities are selected.- Every button lands through SceneCommands.setEntityXY (one undo step). */}+ Every button lands through SceneCommands.setEntityWorldPos (one undo step). */}{selCount >= 2 && (<div className="viewport__tb-group"><OvTool icon={AlignStartVertical} label={t('vp.align.left')} onClick={() => alignSelection('left')} />diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex b26197c42..a01d983d2 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -943,7 +943,7 @@ class ProjectStoreImpl {async instantiatePrefabFromPath(path: string,parent: number | null = null,- position?: { x: number; y: number },+ position?: { x: number; y: number; z?: number },name?: string,): Promise<number | null> {const uuid = AssetRegistry.uuidFor(path);@@ -1027,9 +1027,11 @@ class ProjectStoreImpl {const root = SceneModel.entityBySource(instanceRoot);const parent = root?.parent ?? null;const tf = root?.components.find((c) => c.type === 'Transform')?.data as- | { position?: { x: number; y: number } }+ | { position?: { x: number; y: number; z?: number } }| undefined;- const position = tf?.position ? { x: tf.position.x, y: tf.position.y } : undefined;+ const position = tf?.position+ ? { x: tf.position.x, y: tf.position.y, z: tf.position.z ?? 0 }+ : undefined;SceneCommands.deleteEntity(instanceRoot);return this.instantiatePrefabFromPath(info.path, parent, position);}@@ -1206,8 +1208,10 @@ class ProjectStoreImpl {// proven delete + re-instantiate path — the variant flattens to the same tree).const root = SceneModel.entityBySource(instanceRoot);const parent = root?.parent ?? null;- const tf = root?.components.find((c) => c.type === 'Transform')?.data as { position?: { x: number; y: number } } | undefined;- const position = tf?.position ? { x: tf.position.x, y: tf.position.y } : undefined;+ const tf = root?.components.find((c) => c.type === 'Transform')?.data as { position?: { x: number; y: number; z?: number } } | undefined;+ const position = tf?.position+ ? { x: tf.position.x, y: tf.position.y, z: tf.position.z ?? 0 }+ : undefined;SceneCommands.deleteEntity(instanceRoot);const newRoot = await this.instantiatePrefabFromPath(newPath, parent, position);Toasts.push(t('proj.variantCreated', { name: variantName }), 'success');@@ -1226,7 +1230,7 @@ class ProjectStoreImpl {* thumbnail and an inspector — and this is the door the other four asset kinds* already had.*/- async instantiateMeshFromPath(path: string, position: { x: number; y: number }): Promise<number | null> {+ async instantiateMeshFromPath(path: string, position: { x: number; y: number; z?: number }): Promise<number | null> {const ref = await AssetRegistry.assetRefForPath(path, 'mesh');if (!ref) return null;const summary = await readMeshSummary(path);@@ -1237,7 +1241,7 @@ class ProjectStoreImpl {return id;}- async instantiateSpriteFromPath(path: string, position: { x: number; y: number }): Promise<number | null> {+ async instantiateSpriteFromPath(path: string, position: { x: number; y: number; z?: number }): Promise<number | null> {const ref = await AssetRegistry.assetRefForPath(path, 'texture');if (!ref) return null;const size = await imageSize(path);diff --git a/desktop/src/tools/alignTools.ts b/desktop/src/tools/alignTools.tsindex f738bb9ec..dc2fc1aa3 100644--- a/desktop/src/tools/alignTools.ts+++ b/desktop/src/tools/alignTools.ts@@ -4,7 +4,7 @@* @file alignTools.ts* @brief Multi-selection align + distribute — the Figma/UMG layout-precision tools* the viewport was missing. Every move lands through the ONE unified position- * door, `SceneCommands.setEntityXY`, which routes a world point to a UINode+ * door, `SceneCommands.setEntityWorldPos`, which routes a world point to a UINode* inset (Absolute), a Transform position (world entity), or a no-op (a* flex-flow node the layout owns) — so align is correct for every entity kind* without special-casing here. One gesture = one undo step. Geometry is in the@@ -20,7 +20,7 @@ import { alignTargets, distributeTargets, type AlignBox, type AlignOp, type Distimport type { EntityId } from '@/types';/** Positionable selection → each entity's world AABB. Excludes flex-flow / orphan- * UI nodes (setEntityXY can't move them) and descendants of a selected ancestor+ * UI nodes (setEntityWorldPos can't move them) and descendants of a selected ancestor* (already carried by their parent's move). */function collectBoxes(): Array<{ sid: EntityId; box: AlignBox }> {const ids = pruneDescendants([...useSelection.getState().selectedIds]).filter(@@ -46,7 +46,7 @@ function collectBoxes(): Array<{ sid: EntityId; box: AlignBox }> {function apply(boxes: Array<{ sid: EntityId; box: AlignBox }>, targets: Array<{ cx: number; cy: number }>, label: string): void {SceneCommands.beginGesture(label);try {- boxes.forEach((b, i) => SceneCommands.setEntityXY(b.sid, targets[i].cx, targets[i].cy));+ boxes.forEach((b, i) => SceneCommands.setEntityWorldPos(b.sid, targets[i].cx, targets[i].cy));} finally {SceneCommands.endGesture();}diff --git a/desktop/src/tools/gizmo.ts b/desktop/src/tools/gizmo.tsindex 325f1fb21..16ffebee8 100644--- a/desktop/src/tools/gizmo.ts+++ b/desktop/src/tools/gizmo.ts@@ -14,17 +14,14 @@* direction, and the arrows and the rings are both made of it.*/-import { axisQuat, quatMul, type Quat } from '@/engine/viewportMath';+import { axisQuat, quatMul, rotateVec3, type Quat, type Vec3 } from '@/engine/viewportMath';-export { axisQuat, quatMul, type Quat };+export { axisQuat, quatMul, rotateVec3, type Quat, type Vec3 };export type GizmoMode = 'move' | 'rotate' | 'scale';/** What a handle constrains motion to: one world axis, or the plane of two. */export type GizmoAxis = 'x' | 'y' | 'z' | 'xy' | 'yz' | 'zx';-/** A direction in world space. */-export interface Vec3 { x: number; y: number; z: number }-/** Where each world axis points on screen — see `editorViewAxes`. */export interface ViewAxes {x: { dx: number; dy: number };@@ -109,21 +106,14 @@ export interface AxisHandle {*/export function axisHandles(axes: ViewAxes, rotation?: Quat): AxisHandle[] {return (['x', 'y', 'z'] as const)- .map((axis) => ({- axis,- dir: screenDir(axes, rotation ? rotateVec(AXIS_VECTOR[axis], rotation) : AXIS_VECTOR[axis]),- }))+ .map((axis) => ({ axis, dir: axisScreenDir(axes, axis, rotation) })).filter((h) => Math.hypot(h.dir.x, h.dir.y) >= AXIS_MIN_PROJ);}-/** A world direction turned by a quaternion — how a local axis reaches world space. */-export function rotateVec(v: Vec3, q: Quat): Vec3 {- const t = { x: 2 * (q.y * v.z - q.z * v.y), y: 2 * (q.z * v.x - q.x * v.z), z: 2 * (q.x * v.y - q.y * v.x) };- return {- x: v.x + q.w * t.x + q.y * t.z - q.z * t.y,- y: v.y + q.w * t.y + q.z * t.x - q.x * t.z,- z: v.z + q.w * t.z + q.x * t.y - q.y * t.x,- };+/** Where one world axis points on screen, in the entity's frame when `rotation` is+ * given — the arrow that is drawn, and the direction a drag along it is measured in. */+export function axisScreenDir(axes: ViewAxes, axis: 'x' | 'y' | 'z', rotation?: Quat): Pt {+ return screenDir(axes, rotation ? rotateVec3(AXIS_VECTOR[axis], rotation) : AXIS_VECTOR[axis]);}/** Distance from point `p` to the segment a→b (used for axis-arrow hit zones). */@@ -207,6 +197,29 @@ export function planeNormal(plane: 'xy' | 'yz' | 'zx'): Vec3 {return AXIS_VECTOR[axis];}+/**+ * The per-axis scale factor a handle applies: the axes it names take `f`, the+ * rest stay 1 — a handle constrains a scale the way it constrains a move. Head-on+ * the face-on plane is XY, so the 2D gizmo's uniform x/y scale is this rule's+ * yaw = pitch = 0 case rather than a mode of its own.+ */+export function scaleFactors(axis: GizmoAxis, f: number): Vec3 {+ const on = (a: 'x' | 'y' | 'z'): boolean =>+ (isPlaneAxis(axis) ? (PLANE_AXES[axis] as readonly string[]).includes(a) : axis === a);+ return { x: on('x') ? f : 1, y: on('y') ? f : 1, z: on('z') ? f : 1 };+}++/**+ * How far a drag has travelled along an axis handle, as a fraction of that+ * arrow's DRAWN length. Projected onto the arrow rather than measured from the+ * pivot: radial distance grows for motion across the axis, and dividing by the+ * drawn length is what makes one gesture mean one scale from every angle.+ */+export function axisDragFraction(dir: Pt, delta: Pt): number {+ const len2 = dir.x * dir.x + dir.y * dir.y;+ return len2 > 0 ? (delta.x * dir.x + delta.y * dir.y) / (len2 * GIZMO.axisLen) : 0;+}+/*** Constrain a world-space delta to what a handle allows: a plane handle keeps the* delta (it was measured ON that plane), an axis handle projects onto that axis.@@ -214,7 +227,7 @@ export function planeNormal(plane: 'xy' | 'yz' | 'zx'): Vec3 {*/export function constrainDelta(axis: GizmoAxis, delta: Vec3, rotation?: Quat): Vec3 {if (isPlaneAxis(axis)) return delta;- const a = rotation ? rotateVec(AXIS_VECTOR[axis], rotation) : AXIS_VECTOR[axis];+ const a = rotation ? rotateVec3(AXIS_VECTOR[axis], rotation) : AXIS_VECTOR[axis];const k = delta.x * a.x + delta.y * a.y + delta.z * a.z;return { x: a.x * k, y: a.y * k, z: a.z * k };}@@ -250,30 +263,35 @@ export function pivotDrag(f: PivotFrame, cursor: Pt): { pivot: Pt; pos: Pt } {};}-/** Centroid of a set of world points — the group transform pivot for multi-select. */-export function groupPivot(points: readonly Pt[]): Pt {- if (points.length === 0) return { x: 0, y: 0 };+/**+ * Centroid of a set of world points — the group transform pivot for multi-select.+ *+ * A point, not a point on a plane: a selection spread through depth has a centre+ * that is nowhere near z = 0, and a gizmo drawn there is drawn on nothing.+ */+export function groupPivot(points: readonly Vec3[]): Vec3 {+ if (points.length === 0) return { x: 0, y: 0, z: 0 };let sx = 0;let sy = 0;+ let sz = 0;for (const p of points) {sx += p.x;sy += p.y;+ sz += p.z;}- return { x: sx / points.length, y: sy / points.length };+ return { x: sx / points.length, y: sy / points.length, z: sz / points.length };}-/** Rotate a point `p` around pivot `c` by `angle` radians (group rotate). */-export function rotateAround(p: Pt, c: Pt, angle: number): Pt {- const cos = Math.cos(angle);- const sin = Math.sin(angle);- const dx = p.x - c.x;- const dy = p.y - c.y;- return { x: c.x + dx * cos - dy * sin, y: c.y + dx * sin + dy * cos };+/** A point turned about pivot `c` by `q` — one member's arm through a group rotate.+ * About X or Y that arm swings through depth, which is why it is not a 2D turn. */+export function turnAround(p: Vec3, c: Vec3, q: Quat): Vec3 {+ const r = rotateVec3({ x: p.x - c.x, y: p.y - c.y, z: p.z - c.z }, q);+ return { x: c.x + r.x, y: c.y + r.y, z: c.z + r.z };}-/** Scale a point `p` away from pivot `c` by per-axis factors (group scale). */-export function scaleAround(p: Pt, c: Pt, fx: number, fy: number): Pt {- return { x: c.x + (p.x - c.x) * fx, y: c.y + (p.y - c.y) * fy };+/** A point scaled away from pivot `c` by per-axis factors (group scale). */+export function scaleAround(p: Vec3, c: Vec3, f: Vec3): Vec3 {+ return { x: c.x + (p.x - c.x) * f.x, y: c.y + (p.y - c.y) * f.y, z: c.z + (p.z - c.z) * f.z };}/**@@ -311,7 +329,7 @@ const RING_MIN_DET = 0.12;*/export function rotateRings(axes: ViewAxes, rotation?: Quat): RotateRing[] {const dir = (a: 'x' | 'y' | 'z'): Pt =>- screenDir(axes, rotation ? rotateVec(AXIS_VECTOR[a], rotation) : AXIS_VECTOR[a]);+ screenDir(axes, rotation ? rotateVec3(AXIS_VECTOR[a], rotation) : AXIS_VECTOR[a]);return (['yz', 'zx', 'xy'] as const).map((plane) => {const [a, b] = PLANE_AXES[plane];diff --git a/desktop/src/tools/tileTools.ts b/desktop/src/tools/tileTools.tsindex 08e5372fb..24cb511d7 100644--- a/desktop/src/tools/tileTools.ts+++ b/desktop/src/tools/tileTools.ts@@ -30,7 +30,7 @@ import type { EditorTool, PointerInput } from './EditorTool';export function cursorTile(clientX: number, clientY: number, sourceId: number): { x: number; y: number } | null {const rt = SceneModel.runtimeFor(sourceId);const wp = ViewportController.canvasToWorld(clientX, clientY);- const ep = rt != null ? ViewportController.getEntityWorldXY(rt) : null;+ const ep = rt != null ? ViewportController.getEntityWorldPos(rt) : null;if (rt == null || !wp || !ep) return null;const t = TilemapAPI.worldToTile(rt, wp.x, wp.y, ep.x, ep.y);return { x: Math.floor(t.x), y: Math.floor(t.y) };diff --git a/desktop/src/tools/transformTools.ts b/desktop/src/tools/transformTools.tsindex 24513c8ed..ed7865005 100644--- a/desktop/src/tools/transformTools.ts+++ b/desktop/src/tools/transformTools.ts@@ -40,10 +40,15 @@ import {ringAngleAt,hitTestRings,axisQuat,+ axisDragFraction,+ axisScreenDir,+ isPlaneAxis,quatMul,+ scaleFactors,type Quat,type RotateRing,scaleAround,+ turnAround,} from './gizmo';import { Marquee } from './marquee';import { Toasts } from '@/store/Toasts';@@ -67,8 +72,13 @@ interface Drag {tx: EditorTransaction;kind: Kind;axis: GizmoAxis;- pivotWorld: Pt;+ /** The point the gizmo stands on, in space — a selection spread through depth+ * has a centroid that is not on any one plane. */+ pivotWorld: Vec3;pivotClient: Pt; // canvas-relative+ /** Where the world axes point on screen, so a scale drag can be measured along+ * the arrow that was grabbed rather than as distance from the pivot. */+ axes: ViewAxes;/*** The world plane this drag is measured on: through the active target, with the* normal the grabbed handle implies. Screen motion becomes world motion only on@@ -80,6 +90,9 @@ interface Drag {downWorld: Vec3;/** Where the press landed, in window-client px — what the slop is measured from. */downClient: Pt;+ /** The same press in canvas px, which is the space the handles are laid out in —+ * what a drag along one of them is measured from. */+ downCanvas: Pt;/** rotate: where the press landed — the ring's own parameter, or the screen* angle around the pivot when no ring took the press. */startAngle: number;@@ -121,17 +134,19 @@ function canvasOrigin(): { left: number; top: number } | null {function readTarget(sourceId: EntityId): Target | null {const rtId = SceneModel.runtimeFor(sourceId);if (rtId == null) return null;- const pos = ViewportController.getEntityWorldXY(rtId);+ const pos = ViewportController.getEntityWorldPos(rtId);if (!pos) return null;// The rotation field reads as three degrees; a drag composes onto the pose they// describe, which is why the whole quaternion is captured and not just its Z.const rot = (SceneQuery.getFieldValue(sourceId, 'Transform', 'rotation') as number[]) ?? [0, 0, 0];- const p = (SceneQuery.getFieldValue(sourceId, 'Transform', 'position') as number[]) ?? [0, 0, 0];const sc = (SceneQuery.getFieldValue(sourceId, 'Transform', 'scale') as number[]) ?? [1, 1, 1];+ // All three from the composed transform: a drag is measured and written in world+ // space, and a depth taken from the LOCAL field instead put the two halves of one+ // position in two different frames.return {sourceId,start: {- x: pos.x, y: pos.y, z: p[2] ?? 0, rot: eulerToQuat(rot),+ x: pos.x, y: pos.y, z: pos.z, rot: eulerToQuat(rot),sx: sc[0] ?? 1, sy: sc[1] ?? 1, sz: sc[2] ?? 1,},};@@ -154,7 +169,7 @@ export function pruneDescendants(ids: readonly EntityId[]): EntityId[] {/** Flow-layout (Relative) UINodes: the flex flow owns their position, so a move* gesture has nothing to write (Absolute nodes move via inset edits instead —- * see SceneCommands.setEntityXY). Rotation/scale are NOT layout-owned, so this+ * see SceneCommands.setEntityWorldPos). Rotation/scale are NOT layout-owned, so this* only gates `move`. */export function isFlowUINode(sourceId: EntityId): boolean {const pos = SceneQuery.getFieldValue(sourceId, 'UINode', 'position');@@ -228,12 +243,12 @@ function captureTargets(ids: readonly EntityId[], kind: Kind = 'move'): Target[]}/** Selection centroid = mean of the live world positions of `ids`. */-function pivotOf(ids: readonly EntityId[]): Pt | null {- const pts: Pt[] = [];+function pivotOf(ids: readonly EntityId[]): Vec3 | null {+ const pts: Vec3[] = [];for (const sid of ids) {const rtId = SceneModel.runtimeFor(sid);if (rtId == null) continue;- const pos = ViewportController.getEntityWorldXY(rtId);+ const pos = ViewportController.getEntityWorldPos(rtId);if (pos) pts.push(pos);}return pts.length ? groupPivot(pts) : null;@@ -261,13 +276,13 @@ function primaryRotationQuat(ids: readonly EntityId[]): Quat | undefined {* all when nothing in the selection may be transformed (an all-locked selection* returns null, which reads as "no handles" at both ends).*/-export function selectionPivot(ids: readonly EntityId[]): Pt | null {+export function selectionPivot(ids: readonly EntityId[]): Vec3 | null {const editable = transformableIds(ids);if (editable.length === 0) return null;if (useEditorStore.getState().pivotMode === 'pivot') {const id = primaryOf(editable);const rt = id != null ? SceneModel.runtimeFor(id) : null;- const pos = rt != null ? ViewportController.getEntityWorldXY(rt) : null;+ const pos = rt != null ? ViewportController.getEntityWorldPos(rt) : null;if (pos) return pos;}return pivotOf(editable);@@ -289,16 +304,16 @@ export function gizmoFrame(ids: readonly EntityId[]): Quat | undefined {* preceding the move gesture. Locked members are left out, like every other* viewport write — an Alt-drag over a mixed selection clones what it can move.*/-function altDuplicateTargets(ids: readonly EntityId[]): { targets: Target[]; pivot: Pt | null } {+function altDuplicateTargets(ids: readonly EntityId[]): { targets: Target[]; pivot: Vec3 | null } {const targets: Target[] = [];- const pts: Pt[] = [];+ const pts: Vec3[] = [];for (const sid of transformableIds(pruneDescendants(ids))) {const t = readTarget(sid);if (!t) continue;const copy = SceneCommands.duplicateEntity(sid);if (copy == null) continue;targets.push({ sourceId: copy, start: t.start });- pts.push({ x: t.start.x, y: t.start.y });+ pts.push({ x: t.start.x, y: t.start.y, z: t.start.z });}if (targets.length) {const ids2 = targets.map((t) => t.sourceId);@@ -311,7 +326,7 @@ function beginDrag(kind: Kind,axis: GizmoAxis,targets: Target[],- pivotWorld: Pt,+ pivotWorld: Vec3,pivotClient: Pt,p: PointerInput,cur: Pt,@@ -321,11 +336,10 @@ function beginDrag(ring: RotateRing | null = null,): Drag {const label = kind === 'rotate' ? 'Rotate' : kind === 'scale' ? 'Scale' : 'Move';- // The active target is the one the gizmo sits on, so its position is the point- // the plane passes through; a mixed-depth selection still moves rigidly with it.- const planePoint = { x: pivotWorld.x, y: pivotWorld.y, z: targets.length- ? ViewportController.entityPlaneZ(targets[targets.length - 1].sourceId)- : 0 };+ // Through the pivot — the point the handle being grabbed is drawn at. Taking the+ // plane through some other point leaves the world under the cursor sliding past+ // the arrow the cursor is on.+ const planePoint = pivotWorld;const normal = planeNormal(dragPlane(axis, axes));const downWorld = ViewportController.canvasToWorldOnPlane(p.clientX, p.clientY, planePoint, normal) ?? { x: 0, y: 0, z: planePoint.z };@@ -339,10 +353,12 @@ function beginDrag(axis,pivotWorld,pivotClient,+ axes,planePoint,planeNormal: normal,downWorld,downClient: { x: p.clientX, y: p.clientY },+ downCanvas: { x: cur.x, y: cur.y },ring,// A grabbed ring measures in its own parameter; without one this is the// screen angle around the pivot, which is what the 2D drag always used.@@ -381,7 +397,18 @@ function applyMove(d: Drag, curWorld: Vec3): void {// Through the one door a viewport move goes through: it routes a UINode to its// layout, and re-expresses a parented entity's world target in its parent's frame.for (const t of d.targets) {- SceneCommands.setEntityXY(t.sourceId, t.start.x + dx, t.start.y + dy, t.start.z + dz);+ SceneCommands.setEntityWorldPos(t.sourceId, t.start.x + dx, t.start.y + dy, t.start.z + dz);+ }+}++/** The group turn a rotate drag applies: every member's arm about the shared pivot,+ * and the same turn composed onto each member's own pose. */+function applyTurn(d: Drag, turn: Quat): void {+ for (const t of d.targets) {+ const p = turnAround({ x: t.start.x, y: t.start.y, z: t.start.z }, d.pivotWorld, turn);+ SceneCommands.setEntityWorldPos(t.sourceId, p.x, p.y, p.z);+ SceneCommands.setField(t.sourceId, 'Transform', 'rotation', 'euler',+ quatToEuler(quatMul(turn, t.start.rot)));}}@@ -403,17 +430,10 @@ function applyRotate(d: Drag, cur: Pt): void {const deg = snapTo(r0 + (deltaRad * 180) / Math.PI, ed.snapAngle) - r0;deltaRad = (deg * Math.PI) / 180;}- const turn = axisQuat(d.ring?.axis ?? 'z', deltaRad);- for (const t of d.targets) {- // The whole offset from the pivot turns, not just its x/y: about X or Y a- // group rotation moves its members through depth.- const rel = rotateVecByQuat(- { x: t.start.x - d.pivotWorld.x, y: t.start.y - d.pivotWorld.y, z: 0 }, turn);- SceneCommands.setField(t.sourceId, 'Transform', 'position', 'vec3',- [d.pivotWorld.x + rel.x, d.pivotWorld.y + rel.y, t.start.z + rel.z]);- SceneCommands.setField(t.sourceId, 'Transform', 'rotation', 'euler',- quatToEuler(quatMul(turn, t.start.rot)));- }+ // The whole arm from the pivot turns: about X or Y a group rotation carries its+ // members through depth, and a member at a depth of its own swings on a longer+ // arm than its x/y alone describe.+ applyTurn(d, axisQuat(d.ring?.axis ?? 'z', deltaRad));}/** An angle folded into (-pi, pi] — a drag past the seam is a small turn, not a full one. */@@ -426,40 +446,33 @@ function axisAngleOf(q: Quat, axis: 'x' | 'y' | 'z'): number {return quatToEuler(q)[axis === 'x' ? 0 : axis === 'y' ? 1 : 2];}-/** A vector turned by a quaternion (q·v·q⁻¹, expanded). */-function rotateVecByQuat(v: { x: number; y: number; z: number }, q: Quat): { x: number; y: number; z: number } {- const t = { x: 2 * (q.y * v.z - q.z * v.y), y: 2 * (q.z * v.x - q.x * v.z), z: 2 * (q.x * v.y - q.y * v.x) };- return {- x: v.x + q.w * t.x + q.y * t.z - q.z * t.y,- y: v.y + q.w * t.y + q.z * t.x - q.x * t.z,- z: v.z + q.w * t.z + q.x * t.y - q.y * t.x,- };-}-function applyScale(d: Drag, cur: Pt): void {- const curDist = Math.hypot(cur.x - d.pivotClient.x, cur.y - d.pivotClient.y);- // Delta-based, referenced to the gizmo's on-screen length — f is exactly 1 at the- // grab point and moves linearly with the drag, so grabbing the center box or an- // entity's body (down point near the pivot) can't produce a runaway factor the way- // the old curDist/startDist ratio did off a ~1px baseline.- const f = 1 + (curDist - d.startDist) / GIZMO.axisLen;+ const delta = { x: cur.x - d.downCanvas.x, y: cur.y - d.downCanvas.y };+ // f is exactly 1 at the grab point, so a grab near the pivot cannot run away.+ // An axis handle reads the drag ALONG its own arrow; a plane (or centre) handle+ // has no single direction, so it keeps the radial reading.+ const f = 1 + (isPlaneAxis(d.axis)+ ? (Math.hypot(cur.x - d.pivotClient.x, cur.y - d.pivotClient.y) - d.startDist) / GIZMO.axisLen+ : axisDragFraction(axisScreenDir(d.axes, d.axis, d.localRotation), delta));const ed = useEditorStore.getState();- let fx = d.axis === 'y' ? 1 : f;- let fy = d.axis === 'x' ? 1 : f;+ let factor = scaleFactors(d.axis, f);if (ed.snapping) {// Snap the primary's RESULTING absolute scale to the grid, then back out the// factor (like move-snap) — so a scaled object lands on 0.1 increments.const s0 = d.targets[0].start;- if (d.axis !== 'y' && s0.sx) fx = snapTo(s0.sx * fx, ed.snapScale) / s0.sx;- if (d.axis !== 'x' && s0.sy) fy = snapTo(s0.sy * fy, ed.snapScale) / s0.sy;+ const snapAxis = (k: number, start: number): number =>+ (k !== 1 && start ? snapTo(start * k, ed.snapScale) / start : k);+ factor = {+ x: snapAxis(factor.x, s0.sx), y: snapAxis(factor.y, s0.sy), z: snapAxis(factor.z, s0.sz),+ };}// Floor the factor so a drag through the pivot can't collapse or mirror the object.- fx = Math.max(0.01, fx);- fy = Math.max(0.01, fy);+ factor = { x: Math.max(0.01, factor.x), y: Math.max(0.01, factor.y), z: Math.max(0.01, factor.z) };for (const t of d.targets) {- const np = scaleAround({ x: t.start.x, y: t.start.y }, d.pivotWorld, fx, fy);- SceneCommands.setEntityXY(t.sourceId, np.x, np.y);- SceneCommands.setField(t.sourceId, 'Transform', 'scale', 'vec3', [t.start.sx * fx, t.start.sy * fy, t.start.sz]);+ const np = scaleAround({ x: t.start.x, y: t.start.y, z: t.start.z }, d.pivotWorld, factor);+ SceneCommands.setEntityWorldPos(t.sourceId, np.x, np.y, np.z);+ SceneCommands.setField(t.sourceId, 'Transform', 'scale', 'vec3',+ [t.start.sx * factor.x, t.start.sy * factor.y, t.start.sz * factor.z]);}}@@ -516,7 +529,9 @@ function makeTransformTool(mode: ToolMode): EditorTool {if (mode !== 'select' && ed.showGizmos && sel.selectedIds.size > 0) {const ids = [...sel.selectedIds];const pivotWorld = selectionPivot(ids);- const pc = pivotWorld ? ViewportController.worldToClient(pivotWorld.x, pivotWorld.y) : null;+ const pc = pivotWorld+ ? ViewportController.worldToClient(pivotWorld.x, pivotWorld.y, pivotWorld.z)+ : null;if (pivotWorld && pc) {// Aimed through the SAME basis the handles are drawn from, so the arrow// you grab is the axis that moves. Head-on, world Z projects to nothing —@@ -578,7 +593,7 @@ function makeTransformTool(mode: ToolMode): EditorTool {const pivotWorld = selectionPivot(ids);altPending = p.alt ? ids : null;if (!targets.length || !pivotWorld) return false;- const pc = ViewportController.worldToClient(pivotWorld.x, pivotWorld.y) ?? cur;+ const pc = ViewportController.worldToClient(pivotWorld.x, pivotWorld.y, pivotWorld.z) ?? cur;// Dragging the body itself slides it on the plane facing the eye, which// head-on is the XY plane this always used.const bodyAxes = ViewportController.viewAxes() ?? HEAD_ON;diff --git a/desktop/tests/anchor-preset.test.ts b/desktop/tests/anchor-preset.test.tsindex 303e7cf56..15eba9b65 100644--- a/desktop/tests/anchor-preset.test.ts+++ b/desktop/tests/anchor-preset.test.ts@@ -107,7 +107,7 @@ describe.skipIf(!HAS_WASM)('SceneCommands.setUINodeAnchor (headless World)', ()it('reads a field the scene never stored as its default, not as absent', () => {const { id } = withUINode(); // a bare UINode: nothing authored on it// "Is this a UINode, and how is it positioned?" — the question the move tool- // and setEntityXY both ask. Absent meant "not a UINode" / "no answer".+ // and setEntityWorldPos both ask. Absent meant "not a UINode" / "no answer".expect(S.query.getFieldValue(id, 'UINode', 'position')).toBe(UIPositionType.Relative);expect(S.query.getFieldValue(id, 'UINode', 'insetRight')).toEqual({ value: 0, unit: AUTO });// Still null for a component the entity genuinely does not have.@@ -119,7 +119,7 @@ describe.skipIf(!HAS_WASM)('SceneCommands.setUINodeAnchor (headless World)', ()// where it used to fall through and write Transform.position — a value the// next layout pass overwrites.const { id } = withUINode();- S.commands.setEntityXY(id, 123, 456);+ S.commands.setEntityWorldPos(id, 123, 456);expect(S.query.getFieldValue(id, 'Transform', 'position')).toEqual([0, 0, 0]);});diff --git a/desktop/tests/entity-ops.test.ts b/desktop/tests/entity-ops.test.tsindex 7c5f99480..b7ec92694 100644--- a/desktop/tests/entity-ops.test.ts+++ b/desktop/tests/entity-ops.test.ts@@ -15,7 +15,7 @@ vi.mock('@/engine/SceneCommands', () => ({setField: vi.fn(),setFieldValue: vi.fn(),setEntityVisible: vi.fn(),- setEntityXY: vi.fn(),+ setEntityWorldPos: vi.fn(),},toModelValue: (_cur: unknown, _type: unknown, _key: string, value: unknown) => value,}));@@ -58,7 +58,7 @@ describe('while editing', () => {it('moves through the document command, in world units', () => {expect(EntityOps.moveToPoint(authoredRef(3), { world: { x: 10, y: 20 } })).toBe('document');- expect(SceneCommands.setEntityXY).toHaveBeenCalledWith(3, 10, 20);+ expect(SceneCommands.setEntityWorldPos).toHaveBeenCalledWith(3, 10, 20);});it('refuses a ref the document has no entity for', () => {@@ -84,7 +84,7 @@ describe('while playing', () => {expect(PlayRealm.setVisible).toHaveBeenCalledWith(900, false);expect(PlayRealm.dragTo).toHaveBeenCalledWith(900, 0.5, 0.25, 'x', undefined);expect(SceneCommands.setEntityVisible).not.toHaveBeenCalled();- expect(SceneCommands.setEntityXY).not.toHaveBeenCalled();+ expect(SceneCommands.setEntityWorldPos).not.toHaveBeenCalled();});it('hands the grid to the side that can resolve it', () => {diff --git a/desktop/tests/gizmo.test.ts b/desktop/tests/gizmo.test.tsindex 025ba7f9d..6f3b2da77 100644--- a/desktop/tests/gizmo.test.ts+++ b/desktop/tests/gizmo.test.ts@@ -16,7 +16,7 @@ import {dragPlane,planeNormal,groupPivot,- rotateAround,+ turnAround,scaleAround,rotateRings,ringPoint,@@ -25,6 +25,9 @@ import {axisQuat,quatMul,distToSegment,+ scaleFactors,+ axisDragFraction,+ axisScreenDir,} from '@/tools/gizmo';const pivot = { x: 100, y: 100 };@@ -121,19 +124,73 @@ describe('the plane a drag is measured on', () => {describe('groupPivot', () => {it('is the centroid', () => {- expect(groupPivot([{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 5, y: 9 }])).toEqual({ x: 5, y: 3 });+ expect(groupPivot([+ { x: 0, y: 0, z: 0 }, { x: 10, y: 0, z: 3 }, { x: 5, y: 9, z: 6 },+ ])).toEqual({ x: 5, y: 3, z: 3 });});- it('empty is the origin', () => expect(groupPivot([])).toEqual({ x: 0, y: 0 }));+ it('empty is the origin', () => expect(groupPivot([])).toEqual({ x: 0, y: 0, z: 0 }));});-describe('rotateAround / scaleAround', () => {- it('rotates a point 90° about a pivot', () => {- const r = rotateAround({ x: 10, y: 0 }, { x: 0, y: 0 }, Math.PI / 2);+describe('turnAround / scaleAround', () => {+ it('turns a point 90° about a pivot', () => {+ const r = turnAround({ x: 10, y: 0, z: 0 }, { x: 0, y: 0, z: 0 }, axisQuat('z', Math.PI / 2));expect(r.x).toBeCloseTo(0, 6);expect(r.y).toBeCloseTo(10, 6);});+ // A member standing at a different depth than the pivot swings on the arm its+ // z gives it — the case a 2D turn silently answered with the wrong radius.+ it('swings the depth offset too', () => {+ const r = turnAround({ x: 0, y: 0, z: 10 }, { x: 0, y: 0, z: 0 }, axisQuat('y', Math.PI / 2));+ expect(r.x).toBeCloseTo(10, 6);+ expect(r.z).toBeCloseTo(0, 6);+ });it('scales a point away from a pivot per axis', () => {- expect(scaleAround({ x: 4, y: 4 }, { x: 0, y: 0 }, 2, 0.5)).toEqual({ x: 8, y: 2 });+ expect(scaleAround({ x: 4, y: 4, z: 4 }, { x: 0, y: 0, z: 0 }, { x: 2, y: 0.5, z: 1 }))+ .toEqual({ x: 8, y: 2, z: 4 });+ });+});++describe('scaleFactors', () => {+ // Head-on, the centre grab is the XY plane — the uniform x/y scale the 2D gizmo+ // has always had, arrived at by the same rule rather than written down for it.+ it('the face-on plane head-on is the 2D uniform scale', () => {+ expect(scaleFactors(faceOnPlane(HEAD_ON), 2)).toEqual({ x: 2, y: 2, z: 1 });+ });++ it('each arrow names its own axis, and only it', () => {+ expect(scaleFactors('x', 3)).toEqual({ x: 3, y: 1, z: 1 });+ expect(scaleFactors('y', 3)).toEqual({ x: 1, y: 3, z: 1 });+ expect(scaleFactors('z', 3)).toEqual({ x: 1, y: 1, z: 3 });+ });++ it('a plane handle names the two axes it spans', () => {+ expect(scaleFactors('yz', 4)).toEqual({ x: 1, y: 4, z: 4 });+ expect(scaleFactors('zx', 4)).toEqual({ x: 4, y: 1, z: 4 });+ });+});++describe('axisDragFraction', () => {+ const along = axisScreenDir(HEAD_ON, 'x');++ it('is the drag along the arrow, over the arrow drawn length', () => {+ expect(axisDragFraction(along, { x: GIZMO.axisLen, y: 0 })).toBeCloseTo(1, 9);+ expect(axisDragFraction(along, { x: -GIZMO.axisLen / 2, y: 0 })).toBeCloseTo(-0.5, 9);+ });++ // Radial distance from the pivot grows for this drag; the axis does not.+ it('ignores motion across the arrow', () => {+ expect(axisDragFraction(along, { x: 0, y: 40 })).toBeCloseTo(0, 9);+ });++ // A foreshortened arrow draws short, so the same world travel is fewer pixels —+ // dividing by the DRAWN length is what makes the gesture mean the same thing.+ it('scales with the foreshortening, so one gesture means one scale', () => {+ const half = { x: 0.5, y: 0 };+ expect(axisDragFraction(half, { x: GIZMO.axisLen / 2, y: 0 })).toBeCloseTo(1, 9);+ });++ it('an axis that projects to nothing names no distance', () => {+ expect(axisDragFraction({ x: 0, y: 0 }, { x: 30, y: 30 })).toBe(0);});});diff --git a/desktop/tests/play-edits.test.ts b/desktop/tests/play-edits.test.tsindex 78ece8a5a..daa53fa19 100644--- a/desktop/tests/play-edits.test.ts+++ b/desktop/tests/play-edits.test.ts@@ -15,7 +15,7 @@ vi.mock('@/engine/SceneCommands', () => ({setField: vi.fn(),setFieldValue: vi.fn(),setEntityVisible: vi.fn(),- setEntityXY: vi.fn(),+ setEntityWorldPos: vi.fn(),transact: vi.fn((_label: string, fn: () => void) => fn()),},toModelValue: (_cur: unknown, _t: unknown, _k: string, v: unknown) => v,diff --git a/desktop/tests/transaction.test.ts b/desktop/tests/transaction.test.tsindex 32b393917..c90accb91 100644--- a/desktop/tests/transaction.test.ts+++ b/desktop/tests/transaction.test.ts@@ -46,8 +46,8 @@ describe('SceneCommands transaction', () => {it('commit coalesces a burst of edits into one undo step', () => {const tx = cmds.transaction('Move');- cmds.setEntityXY(1, 5, 0);- cmds.setEntityXY(1, 9, 0);+ cmds.setEntityWorldPos(1, 5, 0);+ cmds.setEntityWorldPos(1, 9, 0);tx.commit();expect(posX(model)).toBe(9);expect(history.canUndo()).toBe(true);@@ -58,7 +58,7 @@ describe('SceneCommands transaction', () => {it('abort reverts live edits and records nothing', () => {const tx = cmds.transaction('Move');- cmds.setEntityXY(1, 7, 0);+ cmds.setEntityWorldPos(1, 7, 0);expect(posX(model)).toBe(7); // applied live during the stroketx.abort();expect(posX(model)).toBe(0); // restored to the captured BEFORE@@ -66,13 +66,13 @@ describe('SceneCommands transaction', () => {});it('transact commits on return and aborts (rethrows) on throw', () => {- cmds.transact('Batch', () => cmds.setEntityXY(1, 3, 0));+ cmds.transact('Batch', () => cmds.setEntityWorldPos(1, 3, 0));expect(posX(model)).toBe(3);expect(history.canUndo()).toBe(true);expect(() =>cmds.transact('Bad', () => {- cmds.setEntityXY(1, 8, 0);+ cmds.setEntityWorldPos(1, 8, 0);throw new Error('boom');}),).toThrow('boom');@@ -81,7 +81,7 @@ describe('SceneCommands transaction', () => {it('handle is idempotent (double commit/abort is a no-op)', () => {const tx = cmds.transaction('Move');- cmds.setEntityXY(1, 4, 0);+ cmds.setEntityWorldPos(1, 4, 0);tx.commit();tx.commit(); // no-optx.abort(); // no-opdiff --git a/desktop/tests/transform-tool.test.ts b/desktop/tests/transform-tool.test.tsindex 662649f42..041cdeb3e 100644--- a/desktop/tests/transform-tool.test.ts+++ b/desktop/tests/transform-tool.test.ts@@ -12,9 +12,17 @@ import { GIZMO } from '@/tools/gizmo';// Shared mutable test state the module mocks read (hoisted above the vi.mock calls).const h = vi.hoisted(() => ({pick: { entity: null as number | null, rect: [] as number[], stack: undefined as number[] | undefined },- pos: new Map<number, { x: number; y: number }>(),+ pos: new Map<number, { x: number; y: number; z: number }>(),locked: new Set<number>(),- calls: { setXY: [] as Array<[number, number, number]>, dup: [] as number[], commit: 0, abort: 0 },+ calls: {+ setXY: [] as Array<[number, number, number]>,+ dup: [] as number[],+ field: [] as Array<[number, string, string, unknown]>,+ commit: 0, abort: 0,+ },+ // Head-on by default (world Z projects to nothing); a test that needs the Z+ // arrow turns the eye first.+ axes: { x: { dx: 1, dy: 0, depth: 0 }, y: { dx: 0, dy: -1, depth: 0 }, z: { dx: 0, dy: 0, depth: 1 } },}));vi.mock('@/engine/EngineHost', () => ({@@ -25,7 +33,7 @@ vi.mock('@/engine/ViewportController', () => ({canvasToWorld: (x: number, y: number) => ({ x, y }), // identity: world == client px// Head-on: the rings the rotate tool aims at reduce to the single Z one, and// the arrows to X and Y — world Z projects to nothing.- viewAxes: () => ({ x: { dx: 1, dy: 0, depth: 0 }, y: { dx: 0, dy: -1, depth: 0 }, z: { dx: 0, dy: 0, depth: 1 } }),+ viewAxes: () => h.axes,// Flat scene: every plane is z = 0, which is what the orthographic editor// answers anyway — the drag plane must not change these expectations.entityPlaneZ: () => 0,@@ -33,7 +41,7 @@ vi.mock('@/engine/ViewportController', () => ({// plane, so a drag reads the same world units it always did.canvasToWorldOnPlane: (x: number, y: number) => ({ x, y, z: 0 }),worldToClient: (x: number, y: number) => ({ x, y }),- getEntityWorldXY: (rt: number) => h.pos.get(rt) ?? { x: 0, y: 0 },+ getEntityWorldPos: (rt: number) => h.pos.get(rt) ?? { x: 0, y: 0, z: 0 },getEntityWorldAngleRad: () => 0,getEntityWorldQuat: () => ({ x: 0, y: 0, z: 0, w: 1 }),pickEntity: () => h.pick.entity,@@ -44,8 +52,10 @@ vi.mock('@/engine/ViewportController', () => ({vi.mock('@/engine/SceneCommands', () => ({SceneCommands: {transaction: () => ({ commit: () => { h.calls.commit += 1; }, abort: () => { h.calls.abort += 1; } }),- setEntityXY: (sid: number, x: number, y: number) => { h.calls.setXY.push([sid, x, y]); },- setField: () => {},+ setEntityWorldPos: (sid: number, x: number, y: number) => { h.calls.setXY.push([sid, x, y]); },+ setField: (sid: number, comp: string, key: string, _t: string, value: unknown) => {+ h.calls.field.push([sid, comp, key, value]);+ },duplicateEntity: (sid: number) => { const n = sid + 100; h.calls.dup.push(n); return n; },},}));@@ -82,13 +92,59 @@ beforeEach(() => {h.locked.clear();h.calls.setXY = [];h.calls.dup = [];+ h.calls.field = [];h.calls.commit = 0;h.calls.abort = 0;+ h.axes = { x: { dx: 1, dy: 0, depth: 0 }, y: { dx: 0, dy: -1, depth: 0 }, z: { dx: 0, dy: 0, depth: 1 } };useSelection.getState().select(null);useEditorStore.setState({ tool: 'move', showGizmos: true, snapping: false });Marquee.set(null);});+// A quarter turn about world Y: world X now points at the eye and world Z lies+// along screen +x, so the Z arrow is the one a drag can reach.+const TURNED_AXES = {+ x: { dx: 0, dy: 0, depth: 1 }, y: { dx: 0, dy: -1, depth: 0 }, z: { dx: 1, dy: 0, depth: 0 },+};++const scaleWritten = (): number[] | undefined =>+ h.calls.field.filter((c) => c[2] === 'scale').at(-1)?.[3] as number[] | undefined;++describe('the scale gizmo names three axes', () => {+ // The arrow you grab is the axis that changes: the Z arrow must reach z, and+ // must not reach the other two.+ it('the Z arrow scales z, and nothing else', () => {+ h.axes = TURNED_AXES;+ useSelection.getState().select(7);+ h.pos.set(7, { x: 100, y: 100, z: 0 });+ const t = TRANSFORM_TOOLS.scale;+ // The Z arrow lies along screen +x here, so it is grabbed to the right of the+ // pivot and dragged further along itself.+ t.onPointerDown(ev(100 + GIZMO.axisLen - 4, 100), ctx);+ t.onPointerMove(ev(100 + GIZMO.axisLen + GIZMO.axisLen, 100), ctx);+ t.onPointerUp(ev(100 + GIZMO.axisLen + GIZMO.axisLen, 100), ctx);+ const s = scaleWritten();+ expect(s).toBeDefined();+ expect(s![0]).toBeCloseTo(1, 6);+ expect(s![1]).toBeCloseTo(1, 6);+ expect(s![2]).toBeGreaterThan(1.5);+ });++ it('the centre grab is still the 2D uniform x/y scale head-on', () => {+ useSelection.getState().select(7);+ h.pos.set(7, { x: 100, y: 100, z: 0 });+ const t = TRANSFORM_TOOLS.scale;+ t.onPointerDown(ev(100, 100), ctx);+ t.onPointerMove(ev(140, 100), ctx);+ t.onPointerUp(ev(140, 100), ctx);+ const s = scaleWritten();+ expect(s).toBeDefined();+ expect(s![0]).toBeCloseTo(s![1], 6);+ expect(s![0]).toBeGreaterThan(1);+ expect(s![2]).toBeCloseTo(1, 6);+ });+});+describe('empty space → marquee box-select', () => {it('drags a box and selects what it covers', () => {h.pick.entity = null;@@ -115,7 +171,7 @@ describe('empty space → marquee box-select', () => {describe('entity pick → select + move', () => {it('selects the clicked entity, and the SELECT tool moves it by the world delta', () => {h.pick.entity = 7;- h.pos.set(7, { x: 100, y: 100 });+ h.pos.set(7, { x: 100, y: 100, z: 0 });const t = TRANSFORM_TOOLS.select;expect(t.onPointerDown(ev(100, 100), ctx)).toBe(true);expect(useSelection.getState().selectedId).toBe(7);@@ -130,7 +186,7 @@ describe('entity pick → select + move', () => {// it used to transform freely, so any click that wobbled nudged the thing you// were only trying to pick.h.pick.entity = 7;- h.pos.set(7, { x: 100, y: 100 });+ h.pos.set(7, { x: 100, y: 100, z: 0 });for (const mode of ['move', 'rotate', 'scale'] as const) {h.calls.setXY = [];useSelection.getState().select(null);@@ -145,7 +201,7 @@ describe('entity pick → select + move', () => {it('the select tool does not nudge on a click that only wobbles', () => {h.pick.entity = 7;- h.pos.set(7, { x: 100, y: 100 });+ h.pos.set(7, { x: 100, y: 100, z: 0 });const t = TRANSFORM_TOOLS.select;t.onPointerDown(ev(100, 100), ctx);t.onPointerMove(ev(102, 101), ctx); // inside the click slop@@ -163,7 +219,7 @@ describe('entity pick → select + move', () => {it('Alt-drag duplicates on the first move and moves the copy', () => {h.pick.entity = 7;- h.pos.set(7, { x: 100, y: 100 });+ h.pos.set(7, { x: 100, y: 100, z: 0 });const t = TRANSFORM_TOOLS.select;t.onPointerDown(ev(100, 100, { alt: true }), ctx);expect(h.calls.dup).toEqual([]); // deferred — no clone until the drag actually moves@@ -176,7 +232,7 @@ describe('entity pick → select + move', () => {it('Alt rides the gizmo handle, now that the body does not transform', () => {useSelection.getState().select(7);- h.pos.set(7, { x: 100, y: 100 });+ h.pos.set(7, { x: 100, y: 100, z: 0 });const t = TRANSFORM_TOOLS.move;// Grab the x arrow: the pivot is the entity, world == client px in this harness.t.onPointerDown(ev(100 + GIZMO.axisLen - 5, 100, { alt: true }), ctx);@@ -188,7 +244,7 @@ describe('entity pick → select + move', () => {it('a bare Alt-click leaves no duplicate (no drag past the slop)', () => {h.pick.entity = 7;- h.pos.set(7, { x: 100, y: 100 });+ h.pos.set(7, { x: 100, y: 100, z: 0 });const t = TRANSFORM_TOOLS.select;t.onPointerDown(ev(100, 100, { alt: true }), ctx);t.onPointerUp(ev(100, 100), ctx); // released in place — never a drag@@ -197,7 +253,7 @@ describe('entity pick → select + move', () => {it('repeated clicks at the same spot cycle through the overlapping stack', () => {h.pick.stack = [7, 8, 9]; // topmost-first, all under (100,100)- for (const id of [7, 8, 9]) h.pos.set(id, { x: 100, y: 100 });+ for (const id of [7, 8, 9]) h.pos.set(id, { x: 100, y: 100, z: 0 });const t = TRANSFORM_TOOLS.select;const click = () => {t.onPointerDown(ev(100, 100), ctx);@@ -209,7 +265,7 @@ describe('entity pick → select + move', () => {it('a drag grabs the selected object instead of cycling', () => {h.pick.stack = [7, 8];- h.pos.set(7, { x: 100, y: 100 });+ h.pos.set(7, { x: 100, y: 100, z: 0 });const t = TRANSFORM_TOOLS.move;t.onPointerDown(ev(100, 100), ctx);t.onPointerUp(ev(100, 100), ctx); // click 1 → 7@@ -224,7 +280,7 @@ describe('entity pick → select + move', () => {describe('gizmo handle → axis-constrained group transform', () => {it('the X handle moves only in X', () => {useSelection.getState().select(7);- h.pos.set(7, { x: 200, y: 200 });+ h.pos.set(7, { x: 200, y: 200, z: 0 });const t = TRANSFORM_TOOLS.move;// Pivot at (200,200); the X handle sits one axis-length to the right.const downX = 200 + GIZMO.axisLen - 4;@@ -239,7 +295,7 @@ describe('gizmo handle → axis-constrained group transform', () => {it('the center plane moves freely in both axes', () => {useSelection.getState().select(7);- h.pos.set(7, { x: 200, y: 200 });+ h.pos.set(7, { x: 200, y: 200, z: 0 });const t = TRANSFORM_TOOLS.move;expect(t.onPointerDown(ev(200, 200), ctx)).toBe(true); // cursor on the pivot = plane handlet.onPointerMove(ev(225, 215), ctx);@@ -255,7 +311,7 @@ describe('locked entities are not transformed by the viewport', () => {// else. This is the whole of what a lock does to a gesture.it('a locked selection has no gizmo pivot, so the drag writes nothing and marquees', () => {useSelection.getState().select(7);- h.pos.set(7, { x: 200, y: 200 });+ h.pos.set(7, { x: 200, y: 200, z: 0 });h.locked.add(7);expect(selectionPivot([7])).toBeNull(); // no pivot → the viewport draws no gizmoconst t = TRANSFORM_TOOLS.move;@@ -271,8 +327,8 @@ describe('locked entities are not transformed by the viewport', () => {it('a mixed selection transforms only its unlocked members', () => {useSelection.getState().selectMany([7, 8], 7);- h.pos.set(7, { x: 200, y: 200 });- h.pos.set(8, { x: 200, y: 200 });+ h.pos.set(7, { x: 200, y: 200, z: 0 });+ h.pos.set(8, { x: 200, y: 200, z: 0 });h.locked.add(8);const t = TRANSFORM_TOOLS.move;const downX = 200 + GIZMO.axisLen - 4;@@ -283,10 +339,10 @@ describe('locked entities are not transformed by the viewport', () => {});it('unlocking restores the pivot', () => {- h.pos.set(7, { x: 200, y: 200 });+ h.pos.set(7, { x: 200, y: 200, z: 0 });h.locked.add(7);expect(selectionPivot([7])).toBeNull();h.locked.delete(7);- expect(selectionPivot([7])).toEqual({ x: 200, y: 200 });+ expect(selectionPivot([7])).toEqual({ x: 200, y: 200, z: 0 });});});diff --git a/desktop/tests/ui-absolute-bake.test.ts b/desktop/tests/ui-absolute-bake.test.tsindex a4cc5f045..8f42605a0 100644--- a/desktop/tests/ui-absolute-bake.test.ts+++ b/desktop/tests/ui-absolute-bake.test.ts@@ -121,7 +121,7 @@ describe.skipIf(!HAS_WASM)('setField UINode position → Absolute bakes insets (// Reset to the Center-anchor shape: every inset + margin auto (self-centered).for (const k of ['insetLeft', 'insetRight', 'insetTop', 'insetBottom', 'marginLeft', 'marginRight', 'marginTop', 'marginBottom'])S.commands.setField(child, 'UINode', k, 'dimension', { value: 0, unit: AUTO });- S.commands.setEntityXY(child, 250, 50); // center 100→250 in x (dx=150), y unchanged+ S.commands.setEntityWorldPos(child, 250, 50); // center 100→250 in x (dx=150), y unchangedconst n = host.world.get(e, UINode);// The dragged (x) axis: auto margins nailed to 0, inset pinned to move the node.expect(n.marginLeft.unit).toBe(PX);diff --git a/desktop/tests/viewport-math.test.ts b/desktop/tests/viewport-math.test.tsindex e032439b8..95698cf66 100644--- a/desktop/tests/viewport-math.test.ts+++ b/desktop/tests/viewport-math.test.ts@@ -15,6 +15,8 @@ import {snapTo,clamp,worldToLocal2D,+ worldToLocal3D,+ rotateVec3,axisIndicatorEnds,frustumPlaneCrossings,} from '@/engine/viewportMath';@@ -108,6 +110,62 @@ describe('worldToLocal2D', () => {});});+describe('worldToLocal3D', () => {+ const compose = (local: { x: number; y: number; z: number }, f: {+ pos: { x: number; y: number; z: number };+ rot: { x: number; y: number; z: number; w: number };+ scale: { x: number; y: number; z: number };+ }): { x: number; y: number; z: number } => {+ const s = { x: local.x * f.scale.x, y: local.y * f.scale.y, z: local.z * f.scale.z };+ const r = rotateVec3(s, f.rot);+ return { x: f.pos.x + r.x, y: f.pos.y + r.y, z: f.pos.z + r.z };+ };++ it('identity frame passes the point through', () => {+ expect(worldToLocal3D({ x: 3, y: 4, z: 5 }, {+ pos: { x: 0, y: 0, z: 0 }, rot: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 },+ })).toEqual({ x: 3, y: 4, z: 5 });+ });++ // The case a 2D inverse cannot answer: a parent turned about X mixes the child's+ // y and z, so a local position taken as (world.x, world.y, untouched z) is wrong+ // in two of three components.+ it('round-trips a frame turned about X', () => {+ const a = Math.PI / 5;+ const f = {+ pos: { x: 4, y: -2, z: 7 },+ rot: { x: Math.sin(a / 2), y: 0, z: 0, w: Math.cos(a / 2) },+ scale: { x: 1, y: 1, z: 1 },+ };+ const local = { x: 1, y: 6, z: -3 };+ const back = worldToLocal3D(compose(local, f), f);+ expect(back.x).toBeCloseTo(local.x, 9);+ expect(back.y).toBeCloseTo(local.y, 9);+ expect(back.z).toBeCloseTo(local.z, 9);+ });++ it('round-trips the whole TRS compose (turn about all three, per-axis scale)', () => {+ const f = {+ pos: { x: 10, y: -5, z: 2 },+ // A normalized quaternion with all four components non-zero.+ rot: { x: 0.3, y: -0.4, z: 0.5, w: Math.sqrt(1 - 0.09 - 0.16 - 0.25) },+ scale: { x: 2, y: 0.5, z: 3 },+ };+ const local = { x: 3, y: -7, z: 4 };+ const back = worldToLocal3D(compose(local, f), f);+ expect(back.x).toBeCloseTo(local.x, 9);+ expect(back.y).toBeCloseTo(local.y, 9);+ expect(back.z).toBeCloseTo(local.z, 9);+ });++ it('a zero scale axis passes through undivided instead of exploding', () => {+ const p = worldToLocal3D({ x: 5, y: 6, z: 8 }, {+ pos: { x: 0, y: 0, z: 0 }, rot: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 0, y: 2, z: 4 },+ });+ expect(p).toEqual({ x: 5, y: 3, z: 2 });+ });+});+describe('rankPickCandidates', () => {// Sprites listed near → far, so list order and depth order disagree on purpose.// This is the exact shape that used to select the sprite BEHIND the cursor.diff --git a/desktop/tests/viewport-navigation.test.ts b/desktop/tests/viewport-navigation.test.tsindex 1fcaf8b5f..4c825f164 100644--- a/desktop/tests/viewport-navigation.test.ts+++ b/desktop/tests/viewport-navigation.test.ts@@ -15,11 +15,14 @@ import { DEFAULT_EDITOR_VIEW, editorViewHalfExtent, type EditorViewData } from 'const host = vi.hoisted(() => ({view: null as EditorViewData | null,canvas: null as unknown,+ /** The ray a screen point names, when a test wants to ask where it lands. */+ ray: null as unknown,}));vi.mock('@/engine/EngineHost', () => ({EngineHost: {- getResource: () => host.view,+ getResource: (r: unknown) =>+ ((r as { _name?: string })?._name === 'CameraView' ? { screenRay: () => host.ray } : host.view),get canvas() { return host.canvas; },get world() { return null; },},@@ -108,3 +111,33 @@ describe('zooming about the cursor', () => {expect(Math.hypot(v.x, v.z)).toBeGreaterThan(1);});});++describe('the plane the view authors on', () => {+ // Straight down the −z axis from a point above the origin: it meets the 2D+ // plane at (12, 5, 0) and the ground at (12, 0, 5).+ const downAndBack = { origin: { x: 12, y: 5, z: 100 }, dir: { x: 0, y: -1, z: -1 } };++ it('orthographic is the 2D plane, which is where every 2D drop always landed', () => {+ host.view = view({});+ host.ray = downAndBack;+ const p = ViewportController.canvasToWorkPlane(400, 300);+ expect(p).not.toBeNull();+ expect(p!.z).toBeCloseTo(0, 6);+ expect(p!.x).toBeCloseTo(12, 6);+ expect(p!.y).toBeCloseTo(-95, 6);+ expect(ViewportController.workPlaneAxes()).toEqual(['x', 'y']);+ });++ // A 3D scene stands on the ground, and that is the surface a dropped thing+ // belongs on — not the wall at z = 0 the cursor happens to cross.+ it('perspective is the ground, and says so in the axes it names', () => {+ host.view = perspectiveView({});+ host.ray = downAndBack;+ const p = ViewportController.canvasToWorkPlane(400, 300);+ expect(p).not.toBeNull();+ expect(p!.y).toBeCloseTo(0, 6);+ expect(p!.x).toBeCloseTo(12, 6);+ expect(p!.z).toBeCloseTo(95, 6);+ expect(ViewportController.workPlaneAxes()).toEqual(['x', 'z']);+ });+});