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.

refactor(editor): the transform gizmo is built from the view's own basis

yhh6ee0cdf5899a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 95d3b11b7..75f26e446 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,29 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Changed
+
+- **The transform gizmo is built from the view's own basis.** Rotate already read
+ where the world axes point on screen and drew a ring per axis. Move and scale
+ did not: their arrows were two written-down screen directions, `+X is right` and
+ `+Y is up`, true only of a head-on orthographic view. Turn the eye and the arrow
+ you grabbed was no longer the axis that moved.
+
+ Now one basis feeds everything — the arrows, the rings, and the aim, from the
+ same call, so what is drawn is what is hit. There is a **Z axis**, the vocabulary
+ says plane where it means plane (`xy`/`yz`/`zx`, not an `xy` that meant
+ "whatever is free"), and local space is the entity's rotation applied to the
+ axes rather than a CSS turn of the whole gizmo — which is the only form that can
+ express a frame turned about X or Y.
+
+ A drag is measured on the plane its handle implies, found by intersecting the
+ cursor's world ray with it. `screenToWorld` was already building that ray and
+ throwing it away on a fixed z plane; it is now the ray's z-plane case, and
+ `CameraView.screenRay` hands the ray to anyone who needs a different one. Every
+ head-on expectation in the gizmo tests is unchanged, which is the compatibility
+ argument: a 2D scene keeps the two arrows, one ring and one free-move square it
+ always had, because world Z projects to nothing there.
+
### Fixed
- **The 3D view button turns the eye.** It swapped the editor camera's projection
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index 5df4e278b..179c33d51 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -552,19 +552,19 @@ export class SceneCommandsImpl {
}
/**
- * Move an entity to a world position (keeps local Z). Undoable like any field
- * edit. `Transform.position` is parent-local, so a parented entity's world
- * target is re-expressed in its parent's live world frame before the write —
- * viewport tools speak world space; the model invariant stays local.
+ * 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.
*/
- setEntityXY(sourceId: EntityId, x: number, y: number): void {
+ setEntityXY(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 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, pos?.z ?? 0]);
+ this.setField(sourceId, 'Transform', 'position', 'vec3', [local.x, local.y, z ?? pos?.z ?? 0]);
}
/**
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index d79e0bcce..7c6ed97f9 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -18,6 +18,7 @@ import {
editorViewHalfHeight, editorViewHalfExtent, setEditorViewHalfHeight, EDITOR_UI_ANCHOR,
entityWorldBox, uiNodeWorldBox, meshWorldBox, editorViewIsOrbited,
editorViewAxes, editorViewAxisAngles, cameraFrustumCorners, type ScreenAxis,
+ rayPlaneHit, type WorldRay, type Vec3,
type TilesetModel, type TileCollisionPiece, type TileGridParams,
} from 'esengine';
import type { EntityId } from '@/types';
@@ -80,6 +81,7 @@ function jointConnectedRuntime(j: JointGizmoData): EntityId | null {
// Structural shape of the engine's CameraView resource (screen<->world).
interface CameraViewLike {
screenToWorld(x: number, y: number, planeZ?: number): { x: number; y: number } | null;
+ screenRay(x: number, y: number): WorldRay | null;
worldToScreen(x: number, y: number, worldZ?: number): { x: number; y: number } | null;
}
@@ -199,6 +201,21 @@ export const ViewportController = {
return cv.screenToWorld(s.sx, s.sy, planeZ);
},
+ /**
+ * Where the cursor meets an arbitrary world plane — {@link canvasToWorld} with
+ * the plane spelled out instead of assumed. A drag along a world axis happens on
+ * a plane containing that axis, which is not a z plane for two axes out of three.
+ */
+ canvasToWorldOnPlane(
+ clientX: number, clientY: number, point: Vec3, normal: Vec3,
+ ): Vec3 | null {
+ const cv = cameraView();
+ const s = clientToScreen(clientX, clientY);
+ if (!cv || !s) return null;
+ const ray = cv.screenRay(s.sx, s.sy);
+ return ray ? rayPlaneHit(ray, point, normal) : null;
+ },
+
/** The world z an entity sits on — the plane its picking and dragging happen on. */
entityPlaneZ(e: EntityId): number {
const world = EngineHost.world;
@@ -399,6 +416,15 @@ export const ViewportController = {
return quatAngleZ(t.worldRotation as { w: number; x: number; y: number; z: number });
},
+ /** An entity's full world rotation — what a local-space handle turns the axes by.
+ * Identity for anything without one, which is the world-aligned gizmo. */
+ getEntityWorldQuat(id: EntityId): { x: number; y: number; z: number; w: number } {
+ const world = EngineHost.world;
+ if (!world || !world.valid(id) || !world.has(id, Transform)) return { x: 0, y: 0, z: 0, w: 1 };
+ const q = world.get(id, Transform).worldRotation as { w: number; x: number; y: number; z: number };
+ return { x: q.x, y: q.y, z: q.z, w: q.w };
+ },
+
/**
* 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
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 6d6208da7..8bb919aa4 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -50,8 +50,8 @@ import { usePanelWindow, eventWindow } from '@/components/PanelWindow';
import type { ToolMode, EntityId } from '@/types';
import { resolveActiveTool, type EditorTool, type ToolContext, type PointerInput } from '@/tools';
import { cursorTile } from '@/tools/tileTools';
-import { GIZMO, colliderHandleClass, pivotDrag, rotateRings, ringPoint, type GizmoAxis, type RotateRing } from '@/tools/gizmo';
-import { selectionPivot, gizmoScreenAngleRad } from '@/tools/transformTools';
+import { GIZMO, HEAD_ON, axisHandles, colliderHandleClass, pivotDrag, rotateRings, ringPoint, type GizmoAxis, type Quat, type RotateRing } from '@/tools/gizmo';
+import { selectionPivot, gizmoFrame } from '@/tools/transformTools';
import { Marquee } from '@/tools/marquee';
import { TilePaintPreview } from '@/tools/tilePreview';
@@ -425,12 +425,6 @@ const gizmoViewBox = `${-GIZMO_SVG / 2} ${-GIZMO_SVG / 2} ${GIZMO_SVG} ${GIZMO_S
// and thrash layout at N divs/frame. Below it the per-entity path is untouched.
const SELECTION_OUTLINE_MERGE_THRESHOLD = 200;
-// Head-on world axes, for the moment before the engine can answer: +X right,
-// +Y up (screen y is down), +Z straight at the eye.
-const HEAD_ON_AXES = {
- x: { dx: 1, dy: 0, depth: 0 }, y: { dx: 0, dy: -1, depth: 0 }, z: { dx: 0, dy: 0, depth: 1 },
-};
-
/** A ring as an SVG path, sampled around its own parameter. */
function ringPath(ring: RotateRing, radius: number): string {
const steps = 48;
@@ -442,66 +436,75 @@ function ringPath(ring: RotateRing, radius: number): string {
return `${d}Z`;
}
-function GizmoOverlay({ tool, active, axes }: {
+function GizmoOverlay({ tool, active, axes, rotation }: {
tool: ToolMode;
active: GizmoAxis | null;
axes: { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis } | null;
+ rotation: Quat | undefined;
}) {
const L = GIZMO.axisLen;
const B = GIZMO.boxSize;
const P = GIZMO.planeSize;
+ // Drawn from the SAME basis the tool aims through (gizmo.ts), so the arrow you
+ // grab is the axis that moves. Edge-on handles are dropped there, which is what
+ // leaves a head-on gizmo the two arrows and the single ring it always had.
+ const basis = axes ?? HEAD_ON;
// The grabbed handle reads "hot": a thicker stroke + full-opacity fill, so the
- // drag has the visual confirmation UE/Unity give. Axes light independently; the
- // center plane lights on the 'xy' (uniform) handle.
- const onX = active === 'x';
- const onY = active === 'y';
- const onXY = active === 'xy';
+ // drag has the visual confirmation UE/Unity give.
const axW = (on: boolean) => (on ? 4 : 2.5);
const planeOp = (on: boolean) => (on ? 1 : 0.85);
if (tool === 'rotate') {
// One ring per world axis, drawn where that axis's plane actually projects —
- // an ellipse once the eye is off-axis. Edge-on rings are dropped by
- // rotateRings, which is what leaves a head-on gizmo the single Z circle.
- const rings = rotateRings(axes ?? HEAD_ON_AXES);
- const hot: Record<string, boolean> = { x: active === 'x', y: active === 'y', z: active === 'xy' };
+ // an ellipse once the eye is off-axis.
return (
<svg className="gizmo-svg" width={GIZMO_SVG} height={GIZMO_SVG} viewBox={gizmoViewBox}>
- {rings.map((ring) => (
+ {rotateRings(basis, rotation).map((ring) => (
<path
key={ring.axis}
className={`gz-ring gz-${ring.axis}`}
d={ringPath(ring, GIZMO.ringRadius)}
fill="none"
- strokeWidth={hot[ring.axis] ? 3.5 : 2}
+ strokeWidth={active === ring.axis ? 3.5 : 2}
/>
))}
<circle cx="0" cy="0" r="2.5" fill="var(--star)" />
</svg>
);
}
- if (tool === 'scale') {
- return (
- <svg className="gizmo-svg" width={GIZMO_SVG} height={GIZMO_SVG} viewBox={gizmoViewBox}>
- <line x1="0" y1="0" x2={L} y2="0" stroke="var(--error)" strokeWidth={axW(onX)} />
- <rect x={L - B / 2} y={-B / 2} width={B} height={B} fill="var(--error)" opacity={onX ? 1 : 0.95} />
- <line x1="0" y1="0" x2="0" y2={-L} stroke="var(--run)" strokeWidth={axW(onY)} />
- <rect x={-B / 2} y={-L - B / 2} width={B} height={B} fill="var(--run)" opacity={onY ? 1 : 0.95} />
- <rect x={-P / 2} y={-P / 2} width={P} height={P} fill="var(--star)" opacity={planeOp(onXY)} />
- </svg>
- );
- }
- // move (and any other) → axis arrows + a center plane square
+ const handles = axisHandles(basis, rotation);
return (
<svg className="gizmo-svg" width={GIZMO_SVG} height={GIZMO_SVG} viewBox={gizmoViewBox}>
- <line x1="0" y1="0" x2={L} y2="0" stroke="var(--error)" strokeWidth={axW(onX)} />
- <path d={`M${L} 0 L${L - 9} -4 L${L - 9} 4 Z`} fill="var(--error)" opacity={onX ? 1 : 0.95} />
- <line x1="0" y1="0" x2="0" y2={-L} stroke="var(--run)" strokeWidth={axW(onY)} />
- <path d={`M0 ${-L} L-4 ${-L + 9} L4 ${-L + 9} Z`} fill="var(--run)" opacity={onY ? 1 : 0.95} />
- <rect x={-P / 2} y={-P / 2} width={P} height={P} fill="var(--star)" opacity={planeOp(onXY)} />
+ {handles.map((h) => {
+ const on = active === h.axis;
+ const ex = h.dir.x * L;
+ const ey = h.dir.y * L;
+ return (
+ <g key={h.axis} className={`gz-${h.axis}`}>
+ <line x1="0" y1="0" x2={ex} y2={ey} stroke="currentColor" strokeWidth={axW(on)} />
+ {tool === 'scale'
+ ? <rect x={ex - B / 2} y={ey - B / 2} width={B} height={B} fill="currentColor" opacity={on ? 1 : 0.95} />
+ : <path d={arrowHead(h.dir, L)} fill="currentColor" opacity={on ? 1 : 0.95} />}
+ </g>
+ );
+ })}
+ <rect x={-P / 2} y={-P / 2} width={P} height={P} fill="var(--star)"
+ opacity={planeOp(active !== null && active.length === 2)} />
</svg>
);
}
+/** The triangle at an axis arrow's tip, pointing the way the axis projects. */
+function arrowHead(dir: { x: number; y: number }, len: number): string {
+ const tx = dir.x * len;
+ const ty = dir.y * len;
+ const bx = dir.x * (len - 9);
+ const by = dir.y * (len - 9);
+ const nx = -dir.y * 4;
+ const ny = dir.x * 4;
+ return `M${tx.toFixed(2)} ${ty.toFixed(2)} L${(bx - nx).toFixed(2)} ${(by - ny).toFixed(2)} `
+ + `L${(bx + nx).toFixed(2)} ${(by + ny).toFixed(2)} Z`;
+}
+
const TOOLS: { mode: ToolMode; icon: LucideIcon; label: string; key: string }[] = [
{ mode: 'select', icon: MousePointer2, label: t('vp.tool.select'), key: 'Q' },
{ mode: 'move', icon: Move, label: t('vp.tool.move'), key: 'W' },
@@ -956,11 +959,14 @@ export function Viewport() {
release: (id) => stageRef.current?.releasePointerCapture(id),
}), []);
const [zoomPct, setZoomPct] = useState(100);
- // Where the world axes project, for the rotate gizmo's rings. Polled (like the
- // zoom readout) rather than mirrored, and only while that tool is up: it changes
- // when the eye turns, and re-rendering the viewport per orbit frame is not free.
+ // Where the world axes project — the basis EVERY handle is drawn from. Polled
+ // rather than mirrored, and only while a transform tool is up: re-rendering the
+ // viewport once per orbit frame is not free.
const [viewAxes, setViewAxes] = useState<{ x: ScreenAxis; y: ScreenAxis; z: ScreenAxis } | null>(null);
const viewAxesKey = useRef('');
+ // The frame the handles stand in (local space = the active entity's rotation),
+ // polled with the axes so one key drives both halves of the gizmo's basis.
+ const [gizmoRotation, setGizmoRotation] = useState<Quat | undefined>(undefined);
// Last-published zoom %, so the rAF only re-renders the HUD when it actually changes.
const zoomPctRef = useRef(100);
const engine = useSyncExternalStore(EngineHost.subscribe, EngineHost.getSnapshot);
@@ -1223,10 +1229,12 @@ export function Viewport() {
// that drifts. The setter no-ops on an unchanged value, so this costs a call.
useEditorStore.getState().setViewOrbited(ViewportController.isOrbited());
- if (toolMode === 'rotate') {
+ if (toolMode !== 'select') {
const a = ViewportController.viewAxes();
- const k = a ? [a.x, a.y, a.z].map((v) => `${v.dx.toFixed(3)},${v.dy.toFixed(3)}`).join('|') : '';
- if (k !== viewAxesKey.current) { viewAxesKey.current = k; setViewAxes(a); }
+ const f = gizmoFrame([...useSelection.getState().selectedIds]);
+ const k = (a ? [a.x, a.y, a.z].map((v) => `${v.dx.toFixed(3)},${v.dy.toFixed(3)}`).join('|') : '')
+ + (f ? `|${f.x.toFixed(3)},${f.y.toFixed(3)},${f.z.toFixed(3)},${f.w.toFixed(3)}` : '');
+ if (k !== viewAxesKey.current) { viewAxesKey.current = k; setViewAxes(a); setGizmoRotation(f); }
}
}
@@ -1454,8 +1462,9 @@ export function Viewport() {
const pivotWorld = drawPivot ? selectionPivot(selIds) : null;
const pivot = pivotWorld ? ViewportController.worldToClient(pivotWorld.x, pivotWorld.y) : null;
if (pivot) {
- const angDeg = (gizmoScreenAngleRad(selIds) * 180) / Math.PI;
- g.style.transform = `translate(${pivot.x}px, ${pivot.y}px) rotate(${angDeg}deg)`;
+ // 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.
+ g.style.transform = `translate(${pivot.x}px, ${pivot.y}px)`;
g.style.opacity = '1';
} else {
g.style.opacity = '0';
@@ -2927,7 +2936,7 @@ export function Viewport() {
))}
</div>
<div ref={gizmoRef} className="viewport__gizmo" aria-hidden="true">
- <GizmoOverlay tool={tool} active={activeGizmoAxis} axes={viewAxes} />
+ <GizmoOverlay tool={tool} active={activeGizmoAxis} axes={viewAxes} rotation={gizmoRotation} />
</div>
{engine.status !== 'ready' && (
diff --git a/desktop/src/tools/gizmo.ts b/desktop/src/tools/gizmo.ts
index a879c3bc3..325f1fb21 100644
--- a/desktop/src/tools/gizmo.ts
+++ b/desktop/src/tools/gizmo.ts
@@ -6,11 +6,12 @@
* axis constraint, group pivot. No engine / DOM coupling, so it unit-tests
* in isolation; transformTools.ts is the imperative shell that drives it.
*
- * Coordinate model: the gizmo lives at a screen-space (CSS px) pivot. Its axes map
- * to world axes through the editor's ortho 2D camera, where world +X = screen +X
- * and world +Y = screen −Y (screen y is down). So hit-testing is done in client
- * space against fixed screen directions, while the actual transform (in the tool)
- * applies the world-space delta the cursor traveled, constrained to the axis.
+ * Coordinate model: the gizmo lives at a screen-space (CSS px) pivot, and every
+ * handle is built from ONE input — where the world axes point on screen for the
+ * current view ({@link ViewAxes}, read off the camera's own basis). A second copy
+ * of that basis is exactly how a gizmo comes to disagree with what is rendered,
+ * so no direction here is written down: {@link screenDir} projects a world
+ * direction, and the arrows and the rings are both made of it.
*/
import { axisQuat, quatMul, type Quat } from '@/engine/viewportMath';
@@ -18,8 +19,54 @@ import { axisQuat, quatMul, type Quat } from '@/engine/viewportMath';
export { axisQuat, quatMul, type Quat };
export type GizmoMode = 'move' | 'rotate' | 'scale';
-/** Which world axes a handle drag affects. */
-export type GizmoAxis = 'x' | 'y' | 'xy';
+/** 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 };
+ y: { dx: number; dy: number };
+ z: { dx: number; dy: number };
+}
+
+/** The head-on 2D view: +X right, +Y up, Z straight at the eye. */
+export const HEAD_ON: ViewAxes = { x: { dx: 1, dy: 0 }, y: { dx: 0, dy: -1 }, z: { dx: 0, dy: 0 } };
+
+/**
+ * Where a world direction points on screen, in the view's own basis.
+ *
+ * The projection of a direction is linear in that basis, so every handle — an
+ * arrow, a ring's two spanning vectors, a local axis turned by the entity's own
+ * rotation — is this one function applied to a unit vector.
+ */
+export function screenDir(axes: ViewAxes, v: Vec3): Pt {
+ return {
+ x: v.x * axes.x.dx + v.y * axes.y.dx + v.z * axes.z.dx,
+ y: v.x * axes.x.dy + v.y * axes.y.dy + v.z * axes.z.dy,
+ };
+}
+
+/** The world axis a single-axis handle constrains to. */
+export const AXIS_VECTOR: Record<'x' | 'y' | 'z', Vec3> = {
+ x: { x: 1, y: 0, z: 0 },
+ y: { x: 0, y: 1, z: 0 },
+ z: { x: 0, y: 0, z: 1 },
+};
+
+/** The two world axes a plane handle spans, in right-handed order. */
+export const PLANE_AXES: Record<'xy' | 'yz' | 'zx', ['x' | 'y' | 'z', 'x' | 'y' | 'z']> = {
+ xy: ['x', 'y'],
+ yz: ['y', 'z'],
+ zx: ['z', 'x'],
+};
+
+/** Whether a handle names a plane rather than a single axis. */
+export function isPlaneAxis(axis: GizmoAxis): axis is 'xy' | 'yz' | 'zx' {
+ return axis.length === 2;
+}
export interface GizmoHandle {
id: string;
@@ -41,9 +88,43 @@ export const GIZMO = {
hitTol: 7, // px tolerance for line / ring proximity
} as const;
-// Screen-space unit directions of the world axes (ortho 2D camera): +X right, +Y up.
-const X_DIR: Pt = { x: 1, y: 0 };
-const Y_DIR: Pt = { x: 0, y: -1 };
+/**
+ * How short an axis may project and still be worth drawing or aiming at. Below it
+ * the arrow points at the eye — a dot, where a drag names no distance. It is also
+ * what leaves a head-on gizmo the two arrows it always had, world Z projecting to
+ * nothing there, the way {@link RING_MIN_DET} leaves it the single Z ring.
+ */
+const AXIS_MIN_PROJ = 0.12;
+
+/** One axis arrow, as it projects: the axis it constrains to, and where it points. */
+export interface AxisHandle {
+ axis: 'x' | 'y' | 'z';
+ dir: Pt;
+}
+
+/**
+ * The move/scale gizmo's arrows, from the same basis the rotate rings are built
+ * from. `rotation`, when given, turns the axes into the entity's own frame — local
+ * space is a rotation of the world axes, not an angle applied to the screen.
+ */
+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]),
+ }))
+ .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,
+ };
+}
/** Distance from point `p` to the segment a→b (used for axis-arrow hit zones). */
export function distToSegment(p: Pt, a: Pt, b: Pt): number {
@@ -59,64 +140,83 @@ export function distToSegment(p: Pt, a: Pt, b: Pt): number {
const within = (p: Pt, c: Pt, half: number): boolean => Math.abs(p.x - c.x) <= half && Math.abs(p.y - c.y) <= half;
const along = (pivot: Pt, dir: Pt, d: number): Pt => ({ x: pivot.x + dir.x * d, y: pivot.y + dir.y * d });
-/** Rotate a screen-space direction by `a` radians (screen frame). */
-function rotDir(dir: Pt, a: number): Pt {
- const c = Math.cos(a);
- const s = Math.sin(a);
- return { x: dir.x * c - dir.y * s, y: dir.x * s + dir.y * c };
-}
-
/**
* The handle under `cursor` for the active gizmo at `pivot` (all CSS px), or null.
- * Central handles (plane / uniform box / nothing) are tested before the axes so the
- * smaller, foreground targets win. `axisAngleRad` rotates the axis arrows to the
- * gizmo's on-screen orientation (0 = world-aligned; non-zero in local space, and it
- * must match the gizmo's render rotation so the handle you aim at is the one hit).
+ * The centre handle is tested before the axes so the smaller, foreground target
+ * wins. `rotation` puts the arrows in the entity's own frame (local space).
*/
-export function hitTestGizmo(mode: 'move' | 'scale', pivot: Pt, cursor: Pt, axisAngleRad = 0): GizmoHandle | null {
- const xEnd = along(pivot, rotDir(X_DIR, axisAngleRad), GIZMO.axisLen);
- const yEnd = along(pivot, rotDir(Y_DIR, axisAngleRad), GIZMO.axisLen);
-
- if (mode === 'move') {
- if (within(cursor, pivot, GIZMO.planeSize / 2)) return { id: 'move.xy', mode, axis: 'xy' };
- if (distToSegment(cursor, pivot, xEnd) <= GIZMO.hitTol) return { id: 'move.x', mode, axis: 'x' };
- if (distToSegment(cursor, pivot, yEnd) <= GIZMO.hitTol) return { id: 'move.y', mode, axis: 'y' };
- return null;
+export function hitTestGizmo(
+ mode: 'move' | 'scale', axes: ViewAxes, pivot: Pt, cursor: Pt, rotation?: Quat,
+): GizmoHandle | null {
+ if (within(cursor, pivot, GIZMO.planeSize / 2)) {
+ const axis = faceOnPlane(axes);
+ return { id: `${mode}.${axis}`, mode, axis };
}
- if (mode === 'scale') {
- if (within(cursor, pivot, GIZMO.planeSize / 2)) return { id: 'scale.xy', mode, axis: 'xy' };
- if (within(cursor, xEnd, GIZMO.boxSize) || distToSegment(cursor, pivot, xEnd) <= GIZMO.hitTol)
- return { id: 'scale.x', mode, axis: 'x' };
- if (within(cursor, yEnd, GIZMO.boxSize) || distToSegment(cursor, pivot, yEnd) <= GIZMO.hitTol)
- return { id: 'scale.y', mode, axis: 'y' };
- return null;
+ for (const h of axisHandles(axes, rotation)) {
+ const end = along(pivot, h.dir, GIZMO.axisLen);
+ const onEnd = mode === 'scale' && within(cursor, end, GIZMO.boxSize);
+ if (onEnd || distToSegment(cursor, pivot, end) <= GIZMO.hitTol) {
+ return { id: `${mode}.${h.axis}`, mode, axis: h.axis };
+ }
}
- // rotate aims at rings, which need the view's axes — see hitTestRings.
return null;
}
-/** Constrain a world-space delta to a handle's axis (world-aligned axes). */
-export function constrainWorldDelta(axis: GizmoAxis, dx: number, dy: number): [number, number] {
- if (axis === 'x') return [dx, 0];
- if (axis === 'y') return [0, dy];
- return [dx, dy];
+/**
+ * The world plane most facing the eye — what the centre square means. Head-on that
+ * is XY, which is the free-move handle a 2D gizmo has always had; turned, it is
+ * whichever plane the cursor can actually slide along without racing off to the
+ * horizon.
+ */
+export function faceOnPlane(axes: ViewAxes): 'xy' | 'yz' | 'zx' {
+ let best: 'xy' | 'yz' | 'zx' = 'xy';
+ let bestArea = -1;
+ for (const plane of ['xy', 'yz', 'zx'] as const) {
+ const [a, b] = PLANE_AXES[plane];
+ const u = axes[a];
+ const v = axes[b];
+ const area = Math.abs(u.dx * v.dy - u.dy * v.dx);
+ if (area > bestArea) { bestArea = area; best = plane; }
+ }
+ return best;
+}
+
+/**
+ * The world plane a handle's drag is measured on. A plane handle IS one; an axis
+ * handle takes whichever of the two planes containing it the eye sees most of,
+ * because a plane seen edge-on turns a pixel of cursor travel into an unbounded
+ * world distance.
+ */
+export function dragPlane(axis: GizmoAxis, axes: ViewAxes): 'xy' | 'yz' | 'zx' {
+ if (isPlaneAxis(axis)) return axis;
+ const candidates = (['xy', 'yz', 'zx'] as const).filter((p) => PLANE_AXES[p].includes(axis));
+ let best = candidates[0]!;
+ let bestArea = -1;
+ for (const p of candidates) {
+ const [a, b] = PLANE_AXES[p];
+ const area = Math.abs(axes[a].dx * axes[b].dy - axes[a].dy * axes[b].dx);
+ if (area > bestArea) { bestArea = area; best = p; }
+ }
+ return best;
+}
+
+/** The world normal of a plane the gizmo names — the axis it does not span. */
+export function planeNormal(plane: 'xy' | 'yz' | 'zx'): Vec3 {
+ const spans = PLANE_AXES[plane];
+ const axis = (['x', 'y', 'z'] as const).find((a) => !spans.includes(a))!;
+ return AXIS_VECTOR[axis];
}
/**
- * Constrain a world-space delta to a handle's axis rotated into the object's local
- * frame by `angleRad` (the entity's world rotation, +Y up). The delta is projected
- * onto the local axis so a single-axis drag slides along the object's own X/Y.
- * `xy` is unconstrained. With `angleRad === 0` this equals {@link constrainWorldDelta}.
+ * 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.
+ * `rotation` puts the axis in the entity's own frame — a local-space drag.
*/
-export function constrainLocalDelta(axis: GizmoAxis, dx: number, dy: number, angleRad: number): [number, number] {
- if (axis === 'xy') return [dx, dy];
- const c = Math.cos(angleRad);
- const s = Math.sin(angleRad);
- // Local X = (cosθ, sinθ); local Y = (−sinθ, cosθ) in world space (+Y up).
- const ax = axis === 'x' ? c : -s;
- const ay = axis === 'x' ? s : c;
- const k = dx * ax + dy * ay; // project the delta onto the chosen local axis
- return [k * ax, k * ay];
+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 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 };
}
/** What a pivot drag is measured against, snapshotted when the handle is grabbed.
@@ -209,15 +309,16 @@ const RING_MIN_DET = 0.12;
* order (Y×Z = X, Z×X = Y, X×Y = Z) — so a drag from `u` toward `v` is a POSITIVE
* turn about the axis, and the sign needs no separate table.
*/
-export function rotateRings(axes: {
- x: { dx: number; dy: number }; y: { dx: number; dy: number }; z: { dx: number; dy: number };
-}): RotateRing[] {
- const pt = (a: { dx: number; dy: number }): Pt => ({ x: a.dx, y: a.dy });
- return ([
- { axis: 'x', u: pt(axes.y), v: pt(axes.z) },
- { axis: 'y', u: pt(axes.z), v: pt(axes.x) },
- { axis: 'z', u: pt(axes.x), v: pt(axes.y) },
- ] as const).filter((r) => Math.abs(r.u.x * r.v.y - r.u.y * r.v.x) >= RING_MIN_DET);
+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]);
+ return (['yz', 'zx', 'xy'] as const)
+ .map((plane) => {
+ const [a, b] = PLANE_AXES[plane];
+ const normal = (['x', 'y', 'z'] as const).find((n) => !PLANE_AXES[plane].includes(n))!;
+ return { axis: normal, u: dir(a), v: dir(b) };
+ })
+ .filter((r) => Math.abs(r.u.x * r.v.y - r.u.y * r.v.x) >= RING_MIN_DET);
}
/** A point on `ring` at parameter `t`, in screen offsets from the pivot. */
diff --git a/desktop/src/tools/transformTools.ts b/desktop/src/tools/transformTools.ts
index 5d6a6f061..24513c8ed 100644
--- a/desktop/src/tools/transformTools.ts
+++ b/desktop/src/tools/transformTools.ts
@@ -28,7 +28,13 @@ import {
type Pt,
GIZMO,
hitTestGizmo,
- constrainLocalDelta,
+ constrainDelta,
+ dragPlane,
+ planeNormal,
+ faceOnPlane,
+ HEAD_ON,
+ type Vec3,
+ type ViewAxes,
groupPivot,
rotateRings,
ringAngleAt,
@@ -64,16 +70,14 @@ interface Drag {
pivotWorld: Pt;
pivotClient: Pt; // canvas-relative
/**
- * The world plane this drag happens on — the active target's z.
- *
- * A drag converts screen motion into world motion, and under a perspective
- * view that conversion depends on depth: the same pixels are a larger world
- * distance further away. Measuring on the 2D plane would make anything with a
- * z drift away from the cursor. Orthographically the plane is irrelevant and
- * this changes nothing.
+ * 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
+ * some plane, and along an axis that is not X or Y no z plane contains it.
+ * Head-on with an X or Y handle this is the z plane the drag always used.
*/
- planeZ: number;
- downWorld: Pt;
+ planePoint: Vec3;
+ planeNormal: Vec3;
+ downWorld: Vec3;
/** Where the press landed, in window-client px — what the slop is measured from. */
downClient: Pt;
/** rotate: where the press landed — the ring's own parameter, or the screen
@@ -82,8 +86,8 @@ interface Drag {
/** rotate: which ring was grabbed. Absent = the 2D screen-angle drag. */
ring: RotateRing | null;
startDist: number; // scale: cursor screen-distance from the pivot
- /** Local-frame angle (world radians) for axis-constrained move; 0 = world axes. */
- angleRad: number;
+ /** The entity's world rotation for a local-space drag; absent = world axes. */
+ localRotation?: Quat;
targets: Target[];
/**
* Whether this drag may write yet.
@@ -243,10 +247,11 @@ function primaryOf(ids: readonly EntityId[]): EntityId | null {
/** The active entity's world rotation in radians (drives the local-axis frame —
* the on-screen orientation is the parent-composed rotation, not the local one). */
-function primaryRotationRad(ids: readonly EntityId[]): number {
+/** The primary's world rotation — what a local-space handle turns the axes by. */
+function primaryRotationQuat(ids: readonly EntityId[]): Quat | undefined {
const id = primaryOf(ids);
const rt = id != null ? SceneModel.runtimeFor(id) : null;
- return rt != null ? ViewportController.getEntityWorldAngleRad(rt) : 0;
+ return rt != null ? ViewportController.getEntityWorldQuat(rt) : undefined;
}
/**
@@ -268,12 +273,13 @@ export function selectionPivot(ids: readonly EntityId[]): Pt | null {
return pivotOf(editable);
}
-/** The gizmo's on-screen rotation (radians): the negated active rotation in local
- * space (screen y is down), else 0. Shared with the viewport's gizmo render. */
-export function gizmoScreenAngleRad(ids: readonly EntityId[]): number {
+/** The frame the gizmo's handles stand in: the active entity's world rotation in
+ * local space, else undefined for the world axes. Shared with the viewport's
+ * render, so the handles it draws are the handles this aims through. */
+export function gizmoFrame(ids: readonly EntityId[]): Quat | undefined {
return useEditorStore.getState().coordSpace === 'local'
- ? -primaryRotationRad(transformableIds(ids))
- : 0;
+ ? primaryRotationQuat(transformableIds(ids))
+ : undefined;
}
/**
@@ -309,17 +315,20 @@ function beginDrag(
pivotClient: Pt,
p: PointerInput,
cur: Pt,
- angleRad = 0,
+ axes: ViewAxes,
+ localRotation: Quat | undefined = undefined,
armed = true,
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 it is the plane the user
- // is reaching for; a mixed-depth selection still moves rigidly with it.
- const planeZ = targets.length
+ // 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;
- const downWorld = ViewportController.canvasToWorld(p.clientX, p.clientY, planeZ) ?? { x: 0, y: 0 };
+ : 0 };
+ const normal = planeNormal(dragPlane(axis, axes));
+ const downWorld = ViewportController.canvasToWorldOnPlane(
+ p.clientX, p.clientY, planePoint, normal) ?? { x: 0, y: 0, z: planePoint.z };
// Freeze React panel re-renders (Details/Outliner) for the drag — the model
// mutates every frame while the viewport stays live via the Reconciler. Resumed
// on commit (onPointerUp) or abort (cancel), flushing one final bump.
@@ -330,7 +339,8 @@ function beginDrag(
axis,
pivotWorld,
pivotClient,
- planeZ,
+ planePoint,
+ planeNormal: normal,
downWorld,
downClient: { x: p.clientX, y: p.clientY },
ring,
@@ -343,27 +353,36 @@ function beginDrag(
// this (not a ratio), so it needs no floor and can't blow up when you grab near
// the pivot (the center box / an entity's body).
startDist: Math.hypot(cur.x - pivotClient.x, cur.y - pivotClient.y),
- angleRad,
+ localRotation,
targets,
armed,
};
}
-function applyMove(d: Drag, curWorld: Pt): void {
- let dx = curWorld.x - d.downWorld.x;
- let dy = curWorld.y - d.downWorld.y;
- // angleRad is 0 for world axes (→ identical to constrainWorldDelta) and the
- // entity's rotation for local axes, so the drag slides along the object's own X/Y.
- [dx, dy] = constrainLocalDelta(d.axis, dx, dy, d.angleRad);
+function applyMove(d: Drag, curWorld: Vec3): void {
+ // The delta was measured ON the handle's plane, so constraining it is a
+ // projection onto the axis — for a plane handle there is nothing left to do.
+ const delta = constrainDelta(d.axis, {
+ x: curWorld.x - d.downWorld.x,
+ y: curWorld.y - d.downWorld.y,
+ z: curWorld.z - d.downWorld.z,
+ }, d.localRotation);
+ let { x: dx, y: dy, z: dz } = delta;
const ed = useEditorStore.getState();
if (ed.snapping && d.targets.length) {
// Snap the primary's resulting position to the grid, apply that delta to all,
- // so the group keeps its relative layout.
+ // so the group keeps its relative layout. An axis the handle does not move
+ // has a zero delta, and snapping it would drag the whole group onto the grid.
const p0 = d.targets[0].start;
- if (d.axis !== 'y') dx = snapTo(p0.x + dx, ed.snapStep) - p0.x;
- if (d.axis !== 'x') dy = snapTo(p0.y + dy, ed.snapStep) - p0.y;
+ if (dx !== 0) dx = snapTo(p0.x + dx, ed.snapStep) - p0.x;
+ if (dy !== 0) dy = snapTo(p0.y + dy, ed.snapStep) - p0.y;
+ if (dz !== 0) dz = snapTo(p0.z + dz, ed.snapStep) - p0.z;
+ }
+ // 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);
}
- for (const t of d.targets) SceneCommands.setEntityXY(t.sourceId, t.start.x + dx, t.start.y + dy);
}
function applyRotate(d: Drag, cur: Pt): void {
@@ -499,16 +518,17 @@ function makeTransformTool(mode: ToolMode): EditorTool {
const pivotWorld = selectionPivot(ids);
const pc = pivotWorld ? ViewportController.worldToClient(pivotWorld.x, pivotWorld.y) : null;
if (pivotWorld && pc) {
- const localAngle = ed.coordSpace === 'local' ? primaryRotationRad(ids) : 0;
- // Rotate aims at rings, which are where the world axes actually project;
- // a head-on view leaves only the Z one, so a 2D aim is unchanged.
- const axes = ViewportController.viewAxes();
- const ring = mode === 'rotate' && axes ? hitTestRings(rotateRings(axes), pc, cur) : null;
+ // 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 —
+ // which is what leaves a 2D gizmo its two arrows and single ring.
+ const axes = ViewportController.viewAxes() ?? HEAD_ON;
+ const localRotation = ed.coordSpace === 'local' ? primaryRotationQuat(ids) : undefined;
+ const ring = mode === 'rotate' ? hitTestRings(rotateRings(axes), pc, cur) : null;
const handle = mode === 'rotate'
- ? (ring && { id: `rotate.${ring.axis}`, mode, axis: (ring.axis === 'z' ? 'xy' : ring.axis) as GizmoAxis })
- : hitTestGizmo(mode as 'move' | 'scale', pc, cur, -localAngle);
+ ? (ring && { id: `rotate.${ring.axis}`, mode, axis: ring.axis as GizmoAxis })
+ : hitTestGizmo(mode as 'move' | 'scale', axes, pc, cur, localRotation);
if (handle) {
- drag = beginDrag(kind, handle.axis, captureTargets(ids, kind), pivotWorld, pc, p, cur, localAngle, true, ring);
+ drag = beginDrag(kind, handle.axis, captureTargets(ids, kind), pivotWorld, pc, p, cur, axes, localRotation, true, ring);
ed.setActiveGizmoAxis(handle.axis); // light up the grabbed handle
// Alt-duplicate rides the handle too, now that the body no longer
// transforms — otherwise Alt+drag would have nowhere to happen in the
@@ -559,7 +579,10 @@ function makeTransformTool(mode: ToolMode): EditorTool {
altPending = p.alt ? ids : null;
if (!targets.length || !pivotWorld) return false;
const pc = ViewportController.worldToClient(pivotWorld.x, pivotWorld.y) ?? cur;
- drag = beginDrag(kind, 'xy', targets, pivotWorld, pc, p, cur, 0, false);
+ // 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;
+ drag = beginDrag(kind, faceOnPlane(bodyAxes), targets, pivotWorld, pc, p, cur, bodyAxes, undefined, false);
ctx.capture(p.pointerId);
return true;
}
@@ -601,7 +624,8 @@ function makeTransformTool(mode: ToolMode): EditorTool {
? { x: p.clientX - origin.left, y: p.clientY - origin.top }
: { x: p.clientX, y: p.clientY };
if (drag.kind === 'move') {
- const w = ViewportController.canvasToWorld(p.clientX, p.clientY, drag.planeZ);
+ const w = ViewportController.canvasToWorldOnPlane(
+ p.clientX, p.clientY, drag.planePoint, drag.planeNormal);
if (w) applyMove(drag, w);
} else if (drag.kind === 'rotate') {
applyRotate(drag, cur);
diff --git a/desktop/tests/gizmo-local-pivot.test.ts b/desktop/tests/gizmo-local-pivot.test.ts
index c05f91c9f..0e52b0b10 100644
--- a/desktop/tests/gizmo-local-pivot.test.ts
+++ b/desktop/tests/gizmo-local-pivot.test.ts
@@ -1,57 +1,84 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file Local-space gizmo math: axis-rotated hit-testing + local-frame delta
- * constraint (the Local/World coordinate-space toggle).
+ * @file Local-space gizmo math: the handles standing in the entity's own frame
+ * (the Local/World coordinate-space toggle).
+ *
+ * Local space is a ROTATION of the world axes, not an angle applied to the
+ * screen — the screen-angle form could only ever express a turn about Z,
+ * and it had to be negated at one call site and not the other.
*/
import { describe, it, expect } from 'vitest';
-import { hitTestGizmo, constrainLocalDelta, GIZMO } from '@/tools/gizmo';
+import { HEAD_ON, hitTestGizmo, constrainDelta, axisHandles, GIZMO } from '@/tools/gizmo';
const pivot = { x: 100, y: 100 };
const close = (a: number, b: number, eps = 1e-9) => expect(Math.abs(a - b)).toBeLessThanOrEqual(eps);
-describe('constrainLocalDelta', () => {
- it('matches constrainWorldDelta at angle 0', () => {
- // Per-component (signed-zero: -0 is numerically equal but `toEqual` distinguishes it).
- const [ax, ay] = constrainLocalDelta('x', 3, 4, 0);
- close(ax, 3); close(ay, 0);
- const [bx, by] = constrainLocalDelta('y', 3, 4, 0);
- close(bx, 0); close(by, 4);
- expect(constrainLocalDelta('xy', 3, 4, 0)).toEqual([3, 4]);
+/** A turn of `rad` about world Z — the rotation a 2D entity has. */
+const spinZ = (rad: number) => ({ x: 0, y: 0, z: Math.sin(rad / 2), w: Math.cos(rad / 2) });
+/** A turn of `rad` about world X — a pose no screen angle could describe. */
+const spinX = (rad: number) => ({ x: Math.sin(rad / 2), y: 0, z: 0, w: Math.cos(rad / 2) });
+
+const delta = { x: 3, y: 4, z: 0 };
+
+describe('constrainDelta in a local frame', () => {
+ it('is the world constraint with no rotation', () => {
+ const a = constrainDelta('x', delta);
+ close(a.x, 3); close(a.y, 0); close(a.z, 0);
+ const b = constrainDelta('y', delta);
+ close(b.x, 0); close(b.y, 4); close(b.z, 0);
+ expect(constrainDelta('xy', delta)).toEqual(delta);
+ });
+
+ it('projects onto the rotated local axis (90° about Z)', () => {
+ // Local X = world +Y: the x-handle slides along world +Y, so (3,4) → (0,4).
+ const a = constrainDelta('x', delta, spinZ(Math.PI / 2));
+ close(a.x, 0); close(a.y, 4); close(a.z, 0);
+ // Local Y = world −X, so (3,4) → (3,0) — the same magnitude, the other axis.
+ const b = constrainDelta('y', delta, spinZ(Math.PI / 2));
+ close(b.x, 3); close(b.y, 0); close(b.z, 0);
});
- it('projects onto the rotated local axis (90°)', () => {
- // Local X = (0,1): the x-handle slides along world +Y, so (3,4) → (0,4).
- const [x1, y1] = constrainLocalDelta('x', 3, 4, Math.PI / 2);
- close(x1, 0); close(y1, 4);
- // Local Y = (-1,0): the y-handle slides along world −X, so (3,4) → (3,0).
- const [x2, y2] = constrainLocalDelta('y', 3, 4, Math.PI / 2);
- close(x2, 3); close(y2, 0);
+ // What the screen-angle form could not say at all.
+ it('projects onto an axis turned out of the plane', () => {
+ // 90° about X takes local Y onto world +Z, so a delta in z is what it keeps.
+ const a = constrainDelta('y', { x: 3, y: 4, z: 7 }, spinX(Math.PI / 2));
+ close(a.x, 0); close(a.y, 0); close(a.z, 7);
});
- it('leaves xy unconstrained at any angle', () => {
- expect(constrainLocalDelta('xy', 3, 4, 1.234)).toEqual([3, 4]);
+ it('leaves a plane handle unconstrained in any frame', () => {
+ expect(constrainDelta('xy', delta, spinZ(1.234))).toEqual(delta);
});
it('keeps only the component along a 45° local axis', () => {
- // Local X = (√½, √½); a delta perpendicular to it projects to ~0.
- const [x, y] = constrainLocalDelta('x', 1, -1, Math.PI / 4);
- close(x, 0); close(y, 0);
+ // Local X = (√½, √½, 0); a delta perpendicular to it projects to ~0.
+ const a = constrainDelta('x', { x: 1, y: -1, z: 0 }, spinZ(Math.PI / 4));
+ close(a.x, 0); close(a.y, 0); close(a.z, 0);
});
});
-describe('hitTestGizmo with axisAngleRad', () => {
- it('angle 0 is unchanged (world +X hits move.x)', () => {
- const h = hitTestGizmo('move', pivot, { x: pivot.x + GIZMO.axisLen, y: pivot.y }, 0);
+describe('hitTestGizmo in a local frame', () => {
+ it('no rotation is unchanged (world +X hits move.x)', () => {
+ const h = hitTestGizmo('move', HEAD_ON, pivot, { x: pivot.x + GIZMO.axisLen, y: pivot.y });
expect(h?.axis).toBe('x');
});
- it('rotates the x-arrow: at 90° the x-handle points along screen +Y', () => {
- // rotDir((1,0), 90°) = (0,1) → xEnd at (100, 100+axisLen).
- const onRotatedX = hitTestGizmo('move', pivot, { x: pivot.x, y: pivot.y + GIZMO.axisLen }, Math.PI / 2);
- expect(onRotatedX?.axis).toBe('x');
- // The old world +X spot is no longer the x-handle.
- const offWorldX = hitTestGizmo('move', pivot, { x: pivot.x + GIZMO.axisLen, y: pivot.y }, Math.PI / 2);
- expect(offWorldX?.axis).not.toBe('x');
+ it('turns the x-arrow: at 90° about Z it points where world +Y does', () => {
+ // Local X = world +Y, which is screen UP — the direction the arrow is drawn,
+ // because both come from the same call.
+ const up = { x: pivot.x, y: pivot.y - GIZMO.axisLen };
+ expect(hitTestGizmo('move', HEAD_ON, pivot, up, spinZ(Math.PI / 2))?.axis).toBe('x');
+ const worldX = { x: pivot.x + GIZMO.axisLen, y: pivot.y };
+ expect(hitTestGizmo('move', HEAD_ON, pivot, worldX, spinZ(Math.PI / 2))?.axis).not.toBe('x');
+ });
+
+ // The aim and the drawing are one call, so they cannot disagree.
+ it('aims at exactly where it draws the arrow', () => {
+ for (const rot of [undefined, spinZ(0.7), spinX(0.9)]) {
+ for (const h of axisHandles(HEAD_ON, rot)) {
+ const tip = { x: pivot.x + h.dir.x * GIZMO.axisLen, y: pivot.y + h.dir.y * GIZMO.axisLen };
+ expect(hitTestGizmo('move', HEAD_ON, pivot, tip, rot)?.axis).toBe(h.axis);
+ }
+ }
});
});
diff --git a/desktop/tests/gizmo.test.ts b/desktop/tests/gizmo.test.ts
index 66df1ea54..025ba7f9d 100644
--- a/desktop/tests/gizmo.test.ts
+++ b/desktop/tests/gizmo.test.ts
@@ -8,8 +8,13 @@ import { describe, it, expect } from 'vitest';
import {
GIZMO,
colliderHandleClass,
+ HEAD_ON,
hitTestGizmo,
- constrainWorldDelta,
+ constrainDelta,
+ axisHandles,
+ faceOnPlane,
+ dragPlane,
+ planeNormal,
groupPivot,
rotateAround,
scaleAround,
@@ -24,38 +29,94 @@ import {
const pivot = { x: 100, y: 100 };
+// A quarter turn about world Y: X now points into the screen and Z out of it.
+const TURNED = {
+ x: { dx: 0, dy: 0 }, y: { dx: 0, dy: -1 }, z: { dx: 1, dy: 0 },
+};
+
describe('hitTestGizmo — move', () => {
- it('center hits the XY plane', () => {
- expect(hitTestGizmo('move', pivot, pivot)?.id).toBe('move.xy');
+ it('center hits the plane facing the eye, which head-on is XY', () => {
+ expect(hitTestGizmo('move', HEAD_ON, pivot, pivot)?.id).toBe('move.xy');
});
it('along +X hits the X axis (screen right)', () => {
- const h = hitTestGizmo('move', pivot, { x: pivot.x + GIZMO.axisLen - 6, y: pivot.y });
+ const h = hitTestGizmo('move', HEAD_ON, pivot, { x: pivot.x + GIZMO.axisLen - 6, y: pivot.y });
expect(h?.id).toBe('move.x');
expect(h?.axis).toBe('x');
});
it('along −screenY (up) hits the Y axis', () => {
- const h = hitTestGizmo('move', pivot, { x: pivot.x, y: pivot.y - GIZMO.axisLen + 6 });
+ const h = hitTestGizmo('move', HEAD_ON, pivot, { x: pivot.x, y: pivot.y - GIZMO.axisLen + 6 });
expect(h?.id).toBe('move.y');
expect(h?.axis).toBe('y');
});
it('empty space misses', () => {
- expect(hitTestGizmo('move', pivot, { x: pivot.x + 200, y: pivot.y + 200 })).toBeNull();
+ expect(hitTestGizmo('move', HEAD_ON, pivot, { x: pivot.x + 200, y: pivot.y + 200 })).toBeNull();
+ });
+ // The defect the basis fixes: the arrow pointing screen-right is whichever axis
+ // the eye puts there, not always X.
+ it('aims at the axis the VIEW puts under the cursor, not at a fixed direction', () => {
+ const right = { x: pivot.x + GIZMO.axisLen - 6, y: pivot.y };
+ expect(hitTestGizmo('move', HEAD_ON, pivot, right)?.axis).toBe('x');
+ expect(hitTestGizmo('move', TURNED, pivot, right)?.axis).toBe('z');
});
});
describe('hitTestGizmo — scale', () => {
it('center hits the uniform box', () => {
- expect(hitTestGizmo('scale', pivot, pivot)?.id).toBe('scale.xy');
+ expect(hitTestGizmo('scale', HEAD_ON, pivot, pivot)?.id).toBe('scale.xy');
});
it('the X end box hits scale.x', () => {
- expect(hitTestGizmo('scale', pivot, { x: pivot.x + GIZMO.axisLen, y: pivot.y })?.id).toBe('scale.x');
+ expect(hitTestGizmo('scale', HEAD_ON, pivot, { x: pivot.x + GIZMO.axisLen, y: pivot.y })?.id).toBe('scale.x');
+ });
+});
+
+describe('axisHandles', () => {
+ // The same rule that leaves a head-on rotate gizmo one ring: an axis pointing at
+ // the eye projects to nothing, and a dot names no drag.
+ it('drops the axis pointing at the eye, so a head-on gizmo keeps its two arrows', () => {
+ expect(axisHandles(HEAD_ON).map((h) => h.axis)).toEqual(['x', 'y']);
+ });
+ it('offers all three once the eye is off-axis', () => {
+ const axes = { x: { dx: 0.7, dy: 0.3 }, y: { dx: 0, dy: -1 }, z: { dx: -0.7, dy: 0.3 } };
+ expect(axisHandles(axes).map((h) => h.axis)).toEqual(['x', 'y', 'z']);
+ });
+ // Local space is a rotation of the axes, not an angle applied to the screen —
+ // which is the only form that can express a turn about X or Y.
+ it('turns the arrows into the entity frame', () => {
+ const quarterZ = { x: 0, y: 0, z: Math.SQRT1_2, w: Math.SQRT1_2 };
+ const x = axisHandles(HEAD_ON, quarterZ).find((h) => h.axis === 'x')!;
+ expect(x.dir.x).toBeCloseTo(0, 6);
+ expect(x.dir.y).toBeCloseTo(-1, 6); // world +Y is screen up
});
});
-describe('constrainWorldDelta', () => {
- it('x axis keeps only dx', () => expect(constrainWorldDelta('x', 5, 9)).toEqual([5, 0]));
- it('y axis keeps only dy', () => expect(constrainWorldDelta('y', 5, 9)).toEqual([0, 9]));
- it('xy keeps both', () => expect(constrainWorldDelta('xy', 5, 9)).toEqual([5, 9]));
+describe('constrainDelta', () => {
+ const d = { x: 5, y: 9, z: 4 };
+ it('x axis keeps only dx', () => expect(constrainDelta('x', d)).toEqual({ x: 5, y: 0, z: 0 }));
+ it('y axis keeps only dy', () => expect(constrainDelta('y', d)).toEqual({ x: 0, y: 9, z: 0 }));
+ it('z axis keeps only dz', () => expect(constrainDelta('z', d)).toEqual({ x: 0, y: 0, z: 4 }));
+ // A plane handle measured the delta ON its plane, so there is nothing to project.
+ it('a plane handle keeps the delta it was given', () => expect(constrainDelta('xy', d)).toEqual(d));
+});
+
+describe('the plane a drag is measured on', () => {
+ // Head-on, an X or Y drag happens on the z plane it always did.
+ it('is the z plane for X and Y head-on', () => {
+ expect(dragPlane('x', HEAD_ON)).toBe('xy');
+ expect(dragPlane('y', HEAD_ON)).toBe('xy');
+ expect(planeNormal('xy')).toEqual({ x: 0, y: 0, z: 1 });
+ });
+ // And never an edge-on one, where a pixel of cursor travel is an unbounded
+ // world distance. Turned about Y, the XY plane is edge-on for a Z drag.
+ it('avoids the plane the eye sees edge-on', () => {
+ expect(dragPlane('z', TURNED)).toBe('yz');
+ });
+ it('is the plane itself for a plane handle', () => {
+ expect(dragPlane('yz', HEAD_ON)).toBe('yz');
+ });
+ it('faces the eye for the centre handle', () => {
+ expect(faceOnPlane(HEAD_ON)).toBe('xy');
+ expect(faceOnPlane(TURNED)).toBe('yz');
+ });
});
describe('groupPivot', () => {
diff --git a/desktop/tests/transform-tool.test.ts b/desktop/tests/transform-tool.test.ts
index 75c59b183..662649f42 100644
--- a/desktop/tests/transform-tool.test.ts
+++ b/desktop/tests/transform-tool.test.ts
@@ -23,14 +23,19 @@ vi.mock('@/engine/EngineHost', () => ({
vi.mock('@/engine/ViewportController', () => ({
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.
+ // 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 } }),
// 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,
+ // The identity above, on the plane the handle chose: head-on that is the z
+ // 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 },
getEntityWorldAngleRad: () => 0,
+ getEntityWorldQuat: () => ({ x: 0, y: 0, z: 0, w: 1 }),
pickEntity: () => h.pick.entity,
pickEntitiesAt: () => (h.pick.stack ?? (h.pick.entity != null ? [h.pick.entity] : [])),
pickInRect: () => h.pick.rect,
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 3a348d845..a888f31bc 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 113,
"beta": 73,
- "experimental": 1568,
+ "experimental": 1571,
"deprecated": 3
},
- "total": 1754,
+ "total": 1757,
"subsystems": [
{
"id": "ecs",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index bdfa7661e..58c1e8750 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: 113 public · 66 beta · 1454 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1457 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1617,6 +1617,7 @@ ResourceDef<CameraViewAPI>
```
getWorldBounds: () => { left: number; right: number; bottom: number; top: number; } | null
getWorldMousePosition: () => { x: number; y: number; } | null
+screenRay: (screenX: number, screenY: number) => WorldRay | null
screenToWorld: (screenX: number, screenY: number, planeZ?: number) => { x: number; y: number; } | null
worldToScreen: (worldX: number, worldY: number, worldZ?: number) => { x: number; y: number; } | null
static new (app_: App): CameraViewAPI
@@ -9050,6 +9051,12 @@ static new (): World
static prototype: World
```
+## WorldRay — interface @experimental
+```
+dir: Vec3
+origin: Vec3
+```
+
## WorldRect — interface @experimental
```
bottom: number
@@ -11053,6 +11060,11 @@ PrefabsPlugin
(radius: number, options?: RadiusInterestOptions): InterestPolicy
```
+## rayPlaneHit — function @experimental
+```
+(ray: WorldRay, point: Vec3, normal: Vec3): Vec3 | null
+```
+
## readCollider3DShapes — function @experimental
```
(world: World, entity: number): Collider3DInstance[]
@@ -11393,6 +11405,11 @@ Plugin
(name: string): string
```
+## screenRay — function @experimental
+```
+(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): WorldRay
+```
+
## screenToUiWorld — function @experimental
```
(camera: UICameraData, screenGLX: number, screenGLY: number): { x: number; y: number; }
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index e8b636886..a0827c61b 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 71 beta · 1473 experimental · 3 deprecated
+Symbols: 113 public · 71 beta · 1476 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1617,6 +1617,7 @@ ResourceDef<CameraViewAPI>
```
getWorldBounds: () => { left: number; right: number; bottom: number; top: number; } | null
getWorldMousePosition: () => { x: number; y: number; } | null
+screenRay: (screenX: number, screenY: number) => WorldRay | null
screenToWorld: (screenX: number, screenY: number, planeZ?: number) => { x: number; y: number; } | null
worldToScreen: (worldX: number, worldY: number, worldZ?: number) => { x: number; y: number; } | null
static new (app_: App): CameraViewAPI
@@ -9243,6 +9244,12 @@ static new (): World
static prototype: World
```
+## WorldRay — interface @experimental
+```
+dir: Vec3
+origin: Vec3
+```
+
## WorldRect — interface @experimental
```
bottom: number
@@ -11296,6 +11303,11 @@ PrefabsPlugin
(radius: number, options?: RadiusInterestOptions): InterestPolicy
```
+## rayPlaneHit — function @experimental
+```
+(ray: WorldRay, point: Vec3, normal: Vec3): Vec3 | null
+```
+
## readCollider3DShapes — function @experimental
```
(world: World, entity: number): Collider3DInstance[]
@@ -11636,6 +11648,11 @@ Plugin
(name: string): string
```
+## screenRay — function @experimental
+```
+(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): WorldRay
+```
+
## screenToUiWorld — function @experimental
```
(camera: UICameraData, screenGLX: number, screenGLY: number): { x: number; y: number; }
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index c0600dbfd..fe0e185d7 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: 113 public · 68 beta · 1453 experimental · 3 deprecated
+Symbols: 113 public · 68 beta · 1456 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1612,6 +1612,7 @@ ResourceDef<CameraViewAPI>
```
getWorldBounds: () => { left: number; right: number; bottom: number; top: number; } | null
getWorldMousePosition: () => { x: number; y: number; } | null
+screenRay: (screenX: number, screenY: number) => WorldRay | null
screenToWorld: (screenX: number, screenY: number, planeZ?: number) => { x: number; y: number; } | null
worldToScreen: (worldX: number, worldY: number, worldZ?: number) => { x: number; y: number; } | null
static new (app_: App): CameraViewAPI
@@ -9045,6 +9046,12 @@ static new (): World
static prototype: World
```
+## WorldRay — interface @experimental
+```
+dir: Vec3
+origin: Vec3
+```
+
## WorldRect — interface @experimental
```
bottom: number
@@ -11058,6 +11065,11 @@ PrefabsPlugin
(radius: number, options?: RadiusInterestOptions): InterestPolicy
```
+## rayPlaneHit — function @experimental
+```
+(ray: WorldRay, point: Vec3, normal: Vec3): Vec3 | null
+```
+
## readCollider3DShapes — function @experimental
```
(world: World, entity: number): Collider3DInstance[]
@@ -11398,6 +11410,11 @@ Plugin
(name: string): string
```
+## screenRay — function @experimental
+```
+(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): WorldRay
+```
+
## screenToUiWorld — function @experimental
```
(camera: UICameraData, screenGLX: number, screenGLY: number): { x: number; y: number; }
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index aecff674e..8877de339 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 66 beta · 1474 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1477 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1612,6 +1612,7 @@ ResourceDef<CameraViewAPI>
```
getWorldBounds: () => { left: number; right: number; bottom: number; top: number; } | null
getWorldMousePosition: () => { x: number; y: number; } | null
+screenRay: (screenX: number, screenY: number) => WorldRay | null
screenToWorld: (screenX: number, screenY: number, planeZ?: number) => { x: number; y: number; } | null
worldToScreen: (worldX: number, worldY: number, worldZ?: number) => { x: number; y: number; } | null
static new (app_: App): CameraViewAPI
@@ -9290,6 +9291,12 @@ static new (): World
static prototype: World
```
+## WorldRay — interface @experimental
+```
+dir: Vec3
+origin: Vec3
+```
+
## WorldRect — interface @experimental
```
bottom: number
@@ -11308,6 +11315,11 @@ PrefabsPlugin
(radius: number, options?: RadiusInterestOptions): InterestPolicy
```
+## rayPlaneHit — function @experimental
+```
+(ray: WorldRay, point: Vec3, normal: Vec3): Vec3 | null
+```
+
## readCollider3DShapes — function @experimental
```
(world: World, entity: number): Collider3DInstance[]
@@ -11648,6 +11660,11 @@ Plugin
(name: string): string
```
+## screenRay — function @experimental
+```
+(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): WorldRay
+```
+
## screenToUiWorld — function @experimental
```
(camera: UICameraData, screenGLX: number, screenGLY: number): { x: number; y: number; }
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 9a6bbdd05..bb741880c 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 66 beta · 1464 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1467 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1612,6 +1612,7 @@ ResourceDef<CameraViewAPI>
```
getWorldBounds: () => { left: number; right: number; bottom: number; top: number; } | null
getWorldMousePosition: () => { x: number; y: number; } | null
+screenRay: (screenX: number, screenY: number) => WorldRay | null
screenToWorld: (screenX: number, screenY: number, planeZ?: number) => { x: number; y: number; } | null
worldToScreen: (worldX: number, worldY: number, worldZ?: number) => { x: number; y: number; } | null
static new (app_: App): CameraViewAPI
@@ -9072,6 +9073,12 @@ static new (): World
static prototype: World
```
+## WorldRay — interface @experimental
+```
+dir: Vec3
+origin: Vec3
+```
+
## WorldRect — interface @experimental
```
bottom: number
@@ -11080,6 +11087,11 @@ PrefabsPlugin
(radius: number, options?: RadiusInterestOptions): InterestPolicy
```
+## rayPlaneHit — function @experimental
+```
+(ray: WorldRay, point: Vec3, normal: Vec3): Vec3 | null
+```
+
## readCollider3DShapes — function @experimental
```
(world: World, entity: number): Collider3DInstance[]
@@ -11420,6 +11432,11 @@ Plugin
(name: string): string
```
+## screenRay — function @experimental
+```
+(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): WorldRay
+```
+
## screenToUiWorld — function @experimental
```
(camera: UICameraData, screenGLX: number, screenGLY: number): { x: number; y: number; }
diff --git a/sdk/src/camera/Camera.ts b/sdk/src/camera/Camera.ts
index b3d281753..219eb1a4f 100644
--- a/sdk/src/camera/Camera.ts
+++ b/sdk/src/camera/Camera.ts
@@ -3,7 +3,7 @@
import type { App } from '../app/app';
import { defineResource } from '../ecs/resource';
import { UICameraInfo, type UICameraData } from '../ui/core/ui-camera-info';
-import { screenToWorld, worldToScreen, createInvVPCache } from '../ui/util/math';
+import { screenToWorld, worldToScreen, createInvVPCache, screenRay, type WorldRay } from '../ui/util/math';
/**
* Per-App camera-space query API: screen<->world conversions, the world-space
@@ -41,6 +41,20 @@ export class CameraViewAPI {
return screenToWorld(screenX, screenY, invVP, cam.vpX, cam.vpY, cam.vpW, cam.vpH, planeZ);
}
+ /**
+ * The world ray a screen point names — what `screenToWorld` intersects with
+ * the z plane. Callers that drag along an arbitrary plane (an editor moving
+ * along a world axis, a pick against the ground) need the ray itself: a
+ * z-keyed answer cannot express a plane that is not z-keyed.
+ */
+ screenRay(screenX: number, screenY: number): WorldRay | null {
+ const cam = this.cam();
+ if (!cam) return null;
+ this.invVPCache.update(cam.viewProjection);
+ const invVP = this.invVPCache.getInverse(cam.viewProjection);
+ return screenRay(screenX, screenY, invVP, cam.vpX, cam.vpY, cam.vpW, cam.vpH);
+ }
+
/**
* Where the world point lands on screen — the inverse of `screenToWorld`,
* taking the same third dimension. Under a perspective camera a point at
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index 4433b120e..cd54bd174 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -36,6 +36,9 @@ export {
intersectRects,
invertMatrix4,
screenToWorld,
+ screenRay,
+ rayPlaneHit,
+ type WorldRay,
pointInWorldRect,
pointInOBB,
quaternionToAngle2D,
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 2e9ec2333..fe43a8ee5 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -331,12 +331,15 @@ export {
intersectRects,
invertMatrix4,
screenToWorld,
+ screenRay,
+ rayPlaneHit,
pointInWorldRect,
pointInOBB,
quaternionToAngle2D,
worldToScreen,
createInvVPCache,
type ScreenRect,
+ type WorldRay,
} from './util/math';
// ─── Plugins (composed UI pipeline + the concept plugins it builds) ─────────
diff --git a/sdk/src/ui/util/math.ts b/sdk/src/ui/util/math.ts
index 1881ae98c..44207127b 100644
--- a/sdk/src/ui/util/math.ts
+++ b/sdk/src/ui/util/math.ts
@@ -5,6 +5,7 @@
// for it.
import { invertMatrix4 } from '../../math/mat4';
import { q } from '../../math/quat';
+import type { Vec3 } from '../../types';
export { invertMatrix4 };
@@ -41,6 +42,55 @@ function unproject(
return { x: x * inv, y: y * inv, z: z * inv };
}
+/**
+ * The world-space ray a screen point names.
+ *
+ * @details Every plane it could land on gives a different answer, so the ray is
+ * what exists and a position is what a chosen plane yields. `dir` is a
+ * unit vector; `origin` sits on the near plane.
+ */
+export interface WorldRay {
+ origin: Vec3;
+ dir: Vec3;
+}
+
+export function screenRay(
+ screenX: number, screenY: number,
+ inverseVP: Float32Array,
+ vpX: number, vpY: number, vpW: number, vpH: number,
+): WorldRay {
+ const ndcX = ((screenX - vpX) / vpW) * 2 - 1;
+ const ndcY = ((screenY - vpY) / vpH) * 2 - 1;
+ const near = unproject(ndcX, ndcY, -1, inverseVP);
+ const far = unproject(ndcX, ndcY, 1, inverseVP);
+ const dx = far.x - near.x;
+ const dy = far.y - near.y;
+ const dz = far.z - near.z;
+ const len = Math.hypot(dx, dy, dz) || 1;
+ return { origin: near, dir: { x: dx / len, y: dy / len, z: dz / len } };
+}
+
+/**
+ * Where @p ray meets the plane through @p point with normal @p normal, or null
+ * when the two are parallel — a plane the ray never reaches has no point on it,
+ * and a number would be a position the caller did not ask about.
+ */
+export function rayPlaneHit(ray: WorldRay, point: Vec3, normal: Vec3): Vec3 | null {
+ const denom = ray.dir.x * normal.x + ray.dir.y * normal.y + ray.dir.z * normal.z;
+ if (Math.abs(denom) <= 1e-9) return null;
+ const t = ((point.x - ray.origin.x) * normal.x
+ + (point.y - ray.origin.y) * normal.y
+ + (point.z - ray.origin.z) * normal.z) / denom;
+ return {
+ x: ray.origin.x + ray.dir.x * t,
+ y: ray.origin.y + ray.dir.y * t,
+ z: ray.origin.z + ray.dir.z * t,
+ };
+}
+
+/** The plane 2D content lives on, and the one a caller with no depth in mind means. */
+const Z_NORMAL: Vec3 = { x: 0, y: 0, z: 1 };
+
/**
* Where a screen point lands on the world plane at @p planeZ.
*
@@ -62,20 +112,12 @@ export function screenToWorld(
vpX: number, vpY: number, vpW: number, vpH: number,
planeZ = 0,
): { x: number; y: number } {
- const ndcX = ((screenX - vpX) / vpW) * 2 - 1;
- const ndcY = ((screenY - vpY) / vpH) * 2 - 1;
-
- const near = unproject(ndcX, ndcY, -1, inverseVP);
- const far = unproject(ndcX, ndcY, 1, inverseVP);
-
- const dz = far.z - near.z;
+ const ray = screenRay(screenX, screenY, inverseVP, vpX, vpY, vpW, vpH);
// A ray parallel to the plane it is being intersected with has no answer;
// the near point is the closest thing to one, and it is what the
// orthographic path returned before this existed.
- if (dz === 0) return { x: near.x, y: near.y };
-
- const t = (planeZ - near.z) / dz;
- return { x: near.x + (far.x - near.x) * t, y: near.y + (far.y - near.y) * t };
+ const hit = rayPlaneHit(ray, { x: 0, y: 0, z: planeZ }, Z_NORMAL);
+ return hit ? { x: hit.x, y: hit.y } : { x: ray.origin.x, y: ray.origin.y };
}
export function pointInWorldRect(
diff --git a/sdk/tests/uiMath.test.ts b/sdk/tests/uiMath.test.ts
index fab07b5b2..ae3da75c7 100644
--- a/sdk/tests/uiMath.test.ts
+++ b/sdk/tests/uiMath.test.ts
@@ -10,6 +10,8 @@ import {
worldToScreen,
createInvVPCache,
pointInOBB,
+ screenRay,
+ rayPlaneHit,
} from '../src/ui/util/math';
import type { ScreenRect } from '../src/ui/util/math';
@@ -669,3 +671,60 @@ describe('an orthographic 2D camera fits by height', () => {
expect(Math.abs(near - designX(w * 0.1))).toBeGreaterThan(40);
});
});
+
+// =============================================================================
+// The ray itself, and screenToWorld as its z-plane case
+// =============================================================================
+
+describe('screenRay', () => {
+ // What a screen point actually names. `screenToWorld` answers for ONE plane —
+ // the one 2D content sits on — and a caller that needs a different one (an
+ // editor dragging along an axis) could not ask before this existed.
+ it('is a unit ray leaving the near plane', () => {
+ const inv = invertMatrix4(perspective4(Math.PI / 2, 1, 0.1, 1000))!;
+ const ray = screenRay(320, 240, inv, 0, 0, 640, 480);
+ const len = Math.hypot(ray.dir.x, ray.dir.y, ray.dir.z);
+ expect(len).toBeCloseTo(1, 6);
+ // Down the centre of a camera at the origin looking along -z.
+ expect(ray.dir.z).toBeCloseTo(-1, 6);
+ expect(ray.origin.z).toBeCloseTo(-0.1, 3);
+ });
+
+ // The plane no z-keyed call can express: the GROUND, which is where 3D content
+ // stands. A 45° ray meets y = -10 at z = -10 — that is the whole point of
+ // handing the plane in rather than assuming it.
+ it('meets a tilted plane where the geometry says', () => {
+ const inv = invertMatrix4(perspective4(Math.PI / 2, 1, 0.1, 1000))!;
+ const ray = screenRay(320, 0, inv, 0, 0, 640, 480);
+ const hit = rayPlaneHit(ray, { x: 0, y: -10, z: 0 }, { x: 0, y: 1, z: 0 })!;
+ expect(hit).not.toBeNull();
+ expect(hit.y).toBeCloseTo(-10, 3);
+ expect(hit.z).toBeCloseTo(-10, 3);
+ expect(hit.x).toBeCloseTo(0, 3);
+ });
+
+ it('has no answer for a plane it runs along', () => {
+ const inv = invertMatrix4(perspective4(Math.PI / 2, 1, 0.1, 1000))!;
+ const ray = screenRay(320, 240, inv, 0, 0, 640, 480);
+ expect(rayPlaneHit(ray, { x: 0, y: 0, z: -5 }, { x: 1, y: 0, z: 0 })).toBeNull();
+ });
+
+ // The refactor's contract: the old entry point is the new one with the plane
+ // 2D content lives on, so no 2D caller can drift from the ray.
+ it('is what screenToWorld intersects, for every plane and projection', () => {
+ for (const vp of [ortho4(160, 120, 1000), perspective4(Math.PI / 2, 4 / 3, 0.1, 1000)]) {
+ const inv = invertMatrix4(vp)!;
+ for (const [sx, sy] of [[0, 0], [320, 240], [637, 11], [500, 200]]) {
+ for (const planeZ of [0, -10, 37, -400]) {
+ const viaPlane = screenToWorld(sx, sy, inv, 0, 0, 640, 480, planeZ);
+ const ray = screenRay(sx, sy, inv, 0, 0, 640, 480);
+ const hit = rayPlaneHit(ray, { x: 0, y: 0, z: planeZ }, { x: 0, y: 0, z: 1 });
+ expect(hit).not.toBeNull();
+ expect(viaPlane.x).toBeCloseTo(hit!.x, 4);
+ expect(viaPlane.y).toBeCloseTo(hit!.y, 4);
+ expect(hit!.z).toBeCloseTo(planeZ, 4);
+ }
+ }
+ }
+ });
+});