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.

feat(editor): a viewport that says which way it faces

esengineca86d2948087
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index 0cb001436..a918384b2 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -496,10 +496,7 @@ commands.register({
label: t('cmd.view.resetOrbit'),
category: t('cat.view'),
isEnabled: () => ViewportController.isOrbited(),
- run: () => {
- ViewportController.resetOrbit();
- editor().setViewOrbited(false);
- },
+ run: () => ViewportController.resetOrbit(),
});
commands.register({
id: 'view.togglePivotMode',
diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.ts
index 59761efc0..e761e6230 100644
--- a/desktop/src/engine/EditorControlSurface.ts
+++ b/desktop/src/engine/EditorControlSurface.ts
@@ -849,6 +849,12 @@ export class EditorControlSurfaceImpl {
ViewportController.setOrbit(yaw, pitch);
}
+ /** Where the eye stands now (degrees) — the read half of {@link setViewOrbit}.
+ * Without it a driver can turn the view but can only judge the result by eye. */
+ viewOrbit(): { yaw: number; pitch: number } {
+ return ViewportController.orbitAngles();
+ }
+
/** Render (and hit-test) through the editor's own eye rather than the scene
* camera — what edit mode does, as one call a driver can make. */
useEditorView(on: boolean): void {
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index 165024063..17e7c1461 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -14,6 +14,7 @@ import {
layerOrderOf,
editorViewHalfHeight, editorViewHalfExtent, setEditorViewHalfHeight, EDITOR_UI_ANCHOR,
entityWorldBox, uiNodeWorldBox, meshWorldBox, editorViewIsOrbited,
+ editorViewAxes, editorViewAxisAngles, type ScreenAxis,
type TilesetModel, type TileCollisionPiece, type TileGridParams,
} from 'esengine';
import type { EntityId } from '@/types';
@@ -470,12 +471,51 @@ export const ViewportController = {
view.pitch = Math.max(-89, Math.min(89, view.pitch + (curY - prevY) * ORBIT_DEG_PER_PX));
},
- /** Point the eye at a given yaw/pitch (degrees) — the automation door's orbit. */
+ /**
+ * Point the eye at a given yaw/pitch (degrees) — the automation door's orbit.
+ * The poles are allowed here, unlike a drag: looking straight down IS a standard
+ * view, and the view basis has its own pole branch for it. What a drag must not
+ * do is cross a pole, which is why the clamp lives in {@link orbitByClient}.
+ */
setOrbit(yaw: number, pitch: number): void {
const view = editorView();
if (!view) return;
view.yaw = yaw;
- view.pitch = Math.max(-89, Math.min(89, pitch));
+ view.pitch = Math.max(-90, Math.min(90, pitch));
+ },
+
+ /** Stand the eye on a world axis and look back down it (front / side / top). */
+ lookAlongAxis(axis: 'x' | 'y' | 'z', sign: 1 | -1): void {
+ const a = editorViewAxisAngles(axis, sign);
+ this.setOrbit(a.yaw, a.pitch);
+ },
+
+ /**
+ * CSS pixels per world unit at the focus plane — the zoom readout.
+ *
+ * Measured from what the view sees, not by projecting two world points: the
+ * world x axis projects to nothing once the eye looks down it, which read as
+ * 1% on a turned view although the zoom had not moved.
+ */
+ zoomScale(): number | null {
+ const view = editorView();
+ const canvas = EngineHost.canvas;
+ if (!view || !canvas) return null;
+ const seen = zoomAmount(view) * 2;
+ const dpr = window.devicePixelRatio || 1;
+ return seen > 0 ? canvas.height / dpr / seen : null;
+ },
+
+ /** Where the eye stands, in degrees (0/0 = head-on). */
+ orbitAngles(): { yaw: number; pitch: number } {
+ const view = editorView();
+ return { yaw: view?.yaw ?? 0, pitch: view?.pitch ?? 0 };
+ },
+
+ /** Where the world axes point on screen right now — what the axis indicator draws. */
+ viewAxes(): { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis } | null {
+ const view = editorView();
+ return view ? editorViewAxes(view) : null;
},
/** Face the scene head-on again — the 2D view, exactly as it was. */
diff --git a/desktop/src/engine/viewportMath.ts b/desktop/src/engine/viewportMath.ts
index 260e5b815..147b4afe0 100644
--- a/desktop/src/engine/viewportMath.ts
+++ b/desktop/src/engine/viewportMath.ts
@@ -8,7 +8,7 @@
* The one import is the SDK's pure mirror of the renderer's layer rules,
* which picking has to rank by rather than restate.
*/
-import { compareDrawRank, type DrawRank } from 'esengine';
+import { compareDrawRank, type DrawRank, type ScreenAxis } from 'esengine';
/** Oriented bounding box in world space: center, half-extents, Z rotation (radians). */
export interface OBB {
@@ -139,3 +139,43 @@ export function scaleVecBy(
): { x: number; y: number; z: number } {
return { x: (s?.x ?? 1) * factor.x, y: (s?.y ?? 1) * factor.y, z: s?.z ?? 1 };
}
+
+/** One end of the view-axis indicator, placed in its SVG's local pixels. */
+export interface AxisIndicatorEnd {
+ key: string;
+ x: number;
+ y: number;
+ depth: number;
+}
+
+/** The identity of one indicator end — the key its DOM node carries. */
+export function axisEndKey(axis: 'x' | 'y' | 'z', sign: 1 | -1): string {
+ return `${axis}${sign > 0 ? '+' : '-'}`;
+}
+
+/**
+ * The six ends of the view-axis indicator, ordered far to near.
+ *
+ * Screen offsets are the axis direction UNNORMALIZED: an axis leaning toward the
+ * eye draws short, which is the foreshortening that tells a user how far the view
+ * has turned. The order is the painter's — the caller reinserts the elements in
+ * it, so a near knob covers a far one.
+ */
+export function axisIndicatorEnds(
+ axes: { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis },
+ length: number,
+): AxisIndicatorEnd[] {
+ const ends: AxisIndicatorEnd[] = [];
+ for (const axis of ['x', 'y', 'z'] as const) {
+ for (const sign of [1, -1] as const) {
+ const a = axes[axis];
+ ends.push({
+ key: axisEndKey(axis, sign),
+ x: a.dx * sign * length,
+ y: a.dy * sign * length,
+ depth: a.depth * sign,
+ });
+ }
+ }
+ return ends.sort((a, b) => a.depth - b.depth);
+}
diff --git a/desktop/src/i18n/messages/viewport.ts b/desktop/src/i18n/messages/viewport.ts
index d08c4cb5e..b77bca8c1 100644
--- a/desktop/src/i18n/messages/viewport.ts
+++ b/desktop/src/i18n/messages/viewport.ts
@@ -109,6 +109,7 @@ export const viewportMessages = defineMessages({
en: 'Face the scene head-on again (Alt-drag turns the editor eye)',
zh: '恢复正对场景(Alt+拖拽可转动编辑器视角)',
},
+ 'vp.axisLook': { en: 'Look along {axis}', zh: '沿 {axis} 轴观察' },
// — Design-resolution + device-preview dropdowns (UI mode) —
'vp.designResTitle': {
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 4f8e80f12..fb1ff554f 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -27,6 +27,7 @@ import { EngineHost } from '@/engine/EngineHost';
import { PlayRealm } from '@/engine/PlayRealm';
import { ViewportController, type JointGizmoType, type ColliderPointHandle, type MinimapBounds, type MinimapBox } from '@/engine/ViewportController';
import { minimapFit, minimapBox, minimapCamRect, minimapToWorld } from '@/engine/minimapFit';
+import { axisIndicatorEnds, axisEndKey } from '@/engine/viewportMath';
import { ProjectStore } from '@/project/ProjectStore';
import { createFromSource, sourceById, SOURCE_DND_MIME } from '@/engine/entitySources';
import { resizeUINodeAxis, type ResizeSide, type AxisResizeWrites } from '@/engine/uiResize';
@@ -715,6 +716,86 @@ const ViewportMinimap = memo(function ViewportMinimap(
);
});
+// The navigation gizmo a DCC puts in a viewport corner: it answers the two questions
+// a turned eye raises and a reset button cannot — which way am I facing, and how do I
+// get square-on. Clicking an end stands the eye on that axis.
+const AXIS_BOX = 46;
+const AXIS_LEN = 30;
+const AXIS_ENDS = [
+ { axis: 'x', sign: 1, label: 'X' }, { axis: 'x', sign: -1, label: '' },
+ { axis: 'y', sign: 1, label: 'Y' }, { axis: 'y', sign: -1, label: '' },
+ { axis: 'z', sign: 1, label: 'Z' }, { axis: 'z', sign: -1, label: '' },
+] as const;
+
+const ViewAxisGizmo = memo(function ViewAxisGizmo() {
+ const win = usePanelWindow();
+ const svgRef = useRef<SVGSVGElement>(null);
+
+ // Its own rAF, like the minimap's camera rect: the axes track an Alt-drag live,
+ // and re-rendering the gizmo-heavy viewport for it would be the wrong cost.
+ useEffect(() => {
+ let raf = 0;
+ let order = '';
+ const tick = () => {
+ raf = requestAnimationFrame(tick);
+ const svg = svgRef.current;
+ if (!svg) return;
+ const axes = ViewportController.viewAxes();
+ if (!axes) return;
+ const ends = axisIndicatorEnds(axes, AXIS_LEN);
+ for (const end of ends) {
+ const g = svg.querySelector<SVGGElement>(`[data-end="${end.key}"]`);
+ if (!g) continue;
+ g.querySelector('line')?.setAttribute('x2', String(end.x));
+ g.querySelector('line')?.setAttribute('y2', String(end.y));
+ const knob = g.querySelector('circle');
+ knob?.setAttribute('cx', String(end.x));
+ knob?.setAttribute('cy', String(end.y));
+ const text = g.querySelector('text');
+ text?.setAttribute('x', String(end.x));
+ text?.setAttribute('y', String(end.y));
+ // An end pointing away is dimmed: a solid knob reads nearer than a faint
+ // one, the only depth cue a flat overlay has.
+ g.style.opacity = String(0.45 + 0.55 * (end.depth + 1) / 2);
+ }
+ // The ends come back in painter order; reinsert only when it actually changed.
+ const key = ends.map((e) => e.key).join('');
+ if (key !== order) {
+ order = key;
+ for (const end of ends) {
+ const g = svg.querySelector<SVGGElement>(`[data-end="${end.key}"]`);
+ if (g) svg.appendChild(g);
+ }
+ }
+ };
+ raf = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf);
+ }, [win]);
+
+ return (
+ <div className="vp-axes">
+ <svg ref={svgRef} viewBox={`${-AXIS_BOX} ${-AXIS_BOX} ${AXIS_BOX * 2} ${AXIS_BOX * 2}`}>
+ {AXIS_ENDS.map((end) => (
+ <g
+ key={axisEndKey(end.axis, end.sign)}
+ data-end={axisEndKey(end.axis, end.sign)}
+ className={`va-end va-${end.axis}${end.sign > 0 ? ' va-pos' : ''}`}
+ onPointerDown={(e) => {
+ e.stopPropagation();
+ ViewportController.lookAlongAxis(end.axis, end.sign);
+ }}
+ >
+ <title>{t('vp.axisLook', { axis: `${end.sign > 0 ? '+' : '-'}${end.axis.toUpperCase()}` })}</title>
+ {end.sign > 0 && <line x1="0" y1="0" x2="0" y2="0" />}
+ <circle cx="0" cy="0" r={end.sign > 0 ? 9 : 7} />
+ {end.label && <text x="0" y="0">{end.label}</text>}
+ </g>
+ ))}
+ </svg>
+ </div>
+ );
+});
+
export function Viewport() {
// The window this viewport currently lives in — main, or its own OS window once
// popped out. Drives resize re-binding and any window-scoped listeners below.
@@ -737,7 +818,6 @@ export function Viewport() {
const pivotMode = useEditorStore((s) => s.pivotMode);
const viewPerspective = useEditorStore((s) => s.viewPerspective);
const viewOrbited = useEditorStore((s) => s.viewOrbited);
- const setViewOrbited = useEditorStore((s) => s.setViewOrbited);
const snapping = useEditorStore((s) => s.snapping);
const snapStep = useEditorStore((s) => s.snapStep);
const snapAngle = useEditorStore((s) => s.snapAngle);
@@ -1076,15 +1156,18 @@ export function Viewport() {
// (pixels per world unit ×100). Frame Selected, the minimap, and device presets
// all change orthoSize without any wheel event, so a tracked counter drifts.
if (ready) {
- const a = ViewportController.worldToClient(0, 0);
- const b = ViewportController.worldToClient(1, 0);
- if (a && b) {
- const pct = Math.max(1, Math.round(Math.hypot(b.x - a.x, b.y - a.y) * 100));
+ const scale = ViewportController.zoomScale();
+ if (scale != null) {
+ const pct = Math.max(1, Math.round(scale * 100));
if (pct !== zoomPctRef.current) {
zoomPctRef.current = pct;
setZoomPct(pct);
}
}
+ // Same reason for the turned eye: an Alt-drag, a command and the automation
+ // door all move it, so a flag each of them must remember to set is a mirror
+ // that drifts. The setter no-ops on an unchanged value, so this costs a call.
+ useEditorStore.getState().setViewOrbited(ViewportController.isOrbited());
}
// Selection outlines. Below the merge threshold: one div per selected source
@@ -1951,7 +2034,6 @@ export function Viewport() {
if (orbitRef.current) {
ViewportController.orbitByClient(orbitRef.current.px, orbitRef.current.py, e.clientX, e.clientY);
orbitRef.current = { px: e.clientX, py: e.clientY };
- setViewOrbited(ViewportController.isOrbited());
return;
}
@@ -2729,6 +2811,10 @@ export function Viewport() {
tool={tool}
paintHint={inTilePaint && paintTool ? TILE_HINT[paintTool] : null}
/>
+ {/* Only once the eye can see depth: a square-on orthographic view IS the 2D
+ editor, and an axis ball over it would be decoration for an X and a Y that
+ never move. Alt-drag or the projection toggle brings it in. */}
+ {engine.status === 'ready' && (viewPerspective || viewOrbited) && <ViewAxisGizmo />}
{engine.status === 'ready' && showMinimap && <ViewportMinimap data={minimap} selected={selectedIds} />}
{/* Contributed gizmos. Gated on `showGizmos` with the built-in ones — a plugin
overlay is a gizmo, so the same toggle has to silence it. */}
diff --git a/desktop/src/theme/tokens.css b/desktop/src/theme/tokens.css
index 236193a4a..6276d25e1 100644
--- a/desktop/src/theme/tokens.css
+++ b/desktop/src/theme/tokens.css
@@ -96,6 +96,9 @@
--gizmo-particle: #ffb454;
--gizmo-tile: #58b6e6;
--gizmo-joint: #c58cff;
+ /* Depth, joining the transform gizmo's red X and green Y — the axis language is
+ the DCC one, so a third axis had to be its blue. */
+ --gizmo-axis-z: #4a90e2;
/* — Category identity: component header bars / icons read by domain. — */
--cat-transform: #4a8fd6;
diff --git a/desktop/src/theme/viewport.css b/desktop/src/theme/viewport.css
index f3b8ef619..8b2cdfa57 100644
--- a/desktop/src/theme/viewport.css
+++ b/desktop/src/theme/viewport.css
@@ -189,6 +189,48 @@
/* Design-resolution readout pinned to the frame's top-left corner (rAF-positioned). */
.viewport__design-label { position: absolute; top: 0; left: 0; z-index: 6; pointer-events: none; padding: 1px 5px; font-size: var(--fs-2xs); font-variant-numeric: tabular-nums; color: var(--on-accent); background: var(--acc); border-radius: var(--r-sm); white-space: nowrap; }
+/* View axis indicator (top-right, below the docked toolbar) — the world axes as they
+ point on screen, each end a click that stands the eye on that axis. Present only
+ while the eye can be turned, so a 2D project never sees it. */
+.vp-axes {
+ position: absolute;
+ top: 44px;
+ right: 10px;
+ z-index: 4;
+ width: 84px;
+ height: 84px;
+ border-radius: 50%;
+ background: rgba(var(--glass-rgb), 0.55);
+ -webkit-backdrop-filter: blur(10px);
+ backdrop-filter: blur(10px);
+ border: 1px solid var(--border-line);
+}
+.vp-axes svg { display: block; width: 100%; height: 100%; overflow: visible; }
+.vp-axes .va-end { cursor: pointer; }
+.vp-axes .va-end line { stroke-width: 2.5; }
+.vp-axes .va-end circle { stroke-width: 1.5; }
+/* A negative end is the hollow twin of its axis: same colour, no stalk, no letter —
+ Blender's convention, and the only way six knobs stay readable at 84px. */
+.vp-axes .va-end:not(.va-pos) circle { fill: var(--srf-1); }
+.vp-axes .va-end text {
+ font-size: 11px;
+ font-weight: 700;
+ text-anchor: middle;
+ dominant-baseline: central;
+ fill: var(--on-accent);
+ pointer-events: none;
+}
+.vp-axes .va-x line, .vp-axes .va-x circle { stroke: var(--error); }
+.vp-axes .va-x.va-pos circle { fill: var(--error); }
+.vp-axes .va-y line, .vp-axes .va-y circle { stroke: var(--run); }
+.vp-axes .va-y.va-pos circle { fill: var(--run); }
+.vp-axes .va-z line, .vp-axes .va-z circle { stroke: var(--gizmo-axis-z); }
+.vp-axes .va-z.va-pos circle { fill: var(--gizmo-axis-z); }
+.vp-axes .va-end:hover circle { stroke: var(--text); stroke-width: 2.5; }
+/* The gizmo owns the top-right corner while it is up; the perf readout drops below
+ it rather than under it. */
+.viewport:has(.vp-axes) .vp-perf { top: 138px; }
+
/* perf widget (top-right, below the docked toolbar — the bottom-right is the minimap) */
.vp-perf {
position: absolute;
diff --git a/desktop/tests/viewport-math.test.ts b/desktop/tests/viewport-math.test.ts
index f952d7057..2ae3c842b 100644
--- a/desktop/tests/viewport-math.test.ts
+++ b/desktop/tests/viewport-math.test.ts
@@ -17,6 +17,7 @@ import {
clamp,
worldToLocal2D,
rankPickCandidates,
+ axisIndicatorEnds,
type PickCandidate,
} from '@/engine/viewportMath';
import { LayerOrder, layerOrderOf } from 'esengine';
@@ -184,3 +185,36 @@ describe('rankPickCandidates', () => {
expect(LayerOrder.Painter).toBe(0);
});
});
+
+describe('the view-axis indicator', () => {
+ // Head-on: +Z is straight at the eye and every other end lies flat on screen.
+ const headOn = {
+ x: { dx: 1, dy: 0, depth: 0 },
+ y: { dx: 0, dy: -1, depth: 0 },
+ z: { dx: 0, dy: 0, depth: 1 },
+ };
+
+ it('places every end on its axis, both ways from the centre', () => {
+ const at = Object.fromEntries(axisIndicatorEnds(headOn, 30).map((e) => [e.key, e]));
+ expect([at['x+'].x, at['x+'].y]).toEqual([30, 0]);
+ expect([at['x-'].x, at['x-'].y]).toEqual([-30, -0]);
+ expect([at['y+'].x, at['y+'].y]).toEqual([0, -30]);
+ expect([at['z+'].x, at['z+'].y]).toEqual([0, 0]); // pointing at the eye, so no offset
+ expect(at['z+'].depth).toBe(1);
+ expect(at['z-'].depth).toBe(-1);
+ });
+
+ it('draws an axis leaning toward the eye shorter', () => {
+ // A 60° turn: the same axis, foreshortened by cos — the cue that says how far
+ // the view has turned. Normalizing the direction would erase it.
+ const turned = { ...headOn, x: { dx: Math.cos(Math.PI / 3), dy: 0, depth: Math.sin(Math.PI / 3) } };
+ const end = axisIndicatorEnds(turned, 30).find((e) => e.key === 'x+')!;
+ expect(end.x).toBeCloseTo(15, 6);
+ });
+
+ it('orders the ends far to near, so a near knob covers a far one', () => {
+ const keys = axisIndicatorEnds(headOn, 30).map((e) => e.key);
+ expect(keys[0]).toBe('z-');
+ expect(keys[keys.length - 1]).toBe('z+');
+ });
+});
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index a2f332379..c9d78891a 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": 62,
- "experimental": 1526,
+ "experimental": 1529,
"deprecated": 3
},
- "total": 1701,
+ "total": 1704,
"subsystems": [
{
"id": "ecs",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 638adfeec..28bd6c8b0 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 · 55 beta · 1411 experimental · 3 deprecated
+Symbols: 113 public · 55 beta · 1414 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -6420,6 +6420,13 @@ system: string
'work' | 'wait'
```
+## ScreenAxis — interface @experimental
+```
+depth: number
+dx: number
+dy: number
+```
+
## ScreenInfo — class @experimental
```
dpr: number
@@ -9534,6 +9541,16 @@ DragPlugin
() => DragonBonesPlugin
```
+## editorViewAxes — function @experimental
+```
+(view: EditorViewData): { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis; }
+```
+
+## editorViewAxisAngles — function @experimental
+```
+(axis: "x" | "y" | "z", sign: 1 | -1): { yaw: number; pitch: number; }
+```
+
## editorViewHalfExtent — function @experimental
```
(view: EditorViewData, aspect: number): { halfW: number; halfH: number; }
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 65dcd89e2..3b81913d0 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 · 60 beta · 1430 experimental · 3 deprecated
+Symbols: 113 public · 60 beta · 1433 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -6613,6 +6613,13 @@ system: string
'work' | 'wait'
```
+## ScreenAxis — interface @experimental
+```
+depth: number
+dx: number
+dy: number
+```
+
## ScreenInfo — class @experimental
```
dpr: number
@@ -9767,6 +9774,16 @@ DragPlugin
() => DragonBonesPlugin
```
+## editorViewAxes — function @experimental
+```
+(view: EditorViewData): { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis; }
+```
+
+## editorViewAxisAngles — function @experimental
+```
+(axis: "x" | "y" | "z", sign: 1 | -1): { yaw: number; pitch: number; }
+```
+
## editorViewHalfExtent — function @experimental
```
(view: EditorViewData, aspect: number): { halfW: number; halfH: number; }
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 05c136441..17f23efe3 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 · 57 beta · 1410 experimental · 3 deprecated
+Symbols: 113 public · 57 beta · 1413 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -6415,6 +6415,13 @@ system: string
'work' | 'wait'
```
+## ScreenAxis — interface @experimental
+```
+depth: number
+dx: number
+dy: number
+```
+
## ScreenInfo — class @experimental
```
dpr: number
@@ -9529,6 +9536,16 @@ DragPlugin
() => DragonBonesPlugin
```
+## editorViewAxes — function @experimental
+```
+(view: EditorViewData): { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis; }
+```
+
+## editorViewAxisAngles — function @experimental
+```
+(axis: "x" | "y" | "z", sign: 1 | -1): { yaw: number; pitch: number; }
+```
+
## editorViewHalfExtent — function @experimental
```
(view: EditorViewData, aspect: number): { halfW: number; halfH: number; }
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 09ba7d487..aac973d33 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 · 55 beta · 1431 experimental · 3 deprecated
+Symbols: 113 public · 55 beta · 1434 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -6660,6 +6660,13 @@ system: string
'work' | 'wait'
```
+## ScreenAxis — interface @experimental
+```
+depth: number
+dx: number
+dy: number
+```
+
## ScreenInfo — class @experimental
```
dpr: number
@@ -9779,6 +9786,16 @@ DragPlugin
() => DragonBonesPlugin
```
+## editorViewAxes — function @experimental
+```
+(view: EditorViewData): { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis; }
+```
+
+## editorViewAxisAngles — function @experimental
+```
+(axis: "x" | "y" | "z", sign: 1 | -1): { yaw: number; pitch: number; }
+```
+
## editorViewHalfExtent — function @experimental
```
(view: EditorViewData, aspect: number): { halfW: number; halfH: number; }
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 7a4866583..3f016fab0 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 · 55 beta · 1421 experimental · 3 deprecated
+Symbols: 113 public · 55 beta · 1424 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -6422,6 +6422,13 @@ system: string
'work' | 'wait'
```
+## ScreenAxis — interface @experimental
+```
+depth: number
+dx: number
+dy: number
+```
+
## ScreenInfo — class @experimental
```
dpr: number
@@ -9556,6 +9563,16 @@ DragPlugin
() => DragonBonesPlugin
```
+## editorViewAxes — function @experimental
+```
+(view: EditorViewData): { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis; }
+```
+
+## editorViewAxisAngles — function @experimental
+```
+(axis: "x" | "y" | "z", sign: 1 | -1): { yaw: number; pitch: number; }
+```
+
## editorViewHalfExtent — function @experimental
```
(view: EditorViewData, aspect: number): { halfW: number; halfH: number; }
diff --git a/sdk/src/camera/EditorView.ts b/sdk/src/camera/EditorView.ts
index 56c31e17a..4586eb6ae 100644
--- a/sdk/src/camera/EditorView.ts
+++ b/sdk/src/camera/EditorView.ts
@@ -17,6 +17,7 @@
* the camera *configuration* (full-frame, raw orthoSize) differs.
*/
import { defineResource } from '../ecs/resource';
+import { invertViewOrbit } from '../math/mat4';
export interface EditorViewData {
/** When true, the framebuffer + screen<->world use this view, not scene cameras. */
@@ -118,3 +119,35 @@ export const EditorView = defineResource<EditorViewData>({ ...DEFAULT_EDITOR_VIE
export function editorViewIsOrbited(view: EditorViewData): boolean {
return (view.yaw ?? 0) !== 0 || (view.pitch ?? 0) !== 0;
}
+
+/** A world axis as it points on screen: a unit direction (y down, as screens are)
+ * plus how far it leans toward the eye — `1` straight at it, `-1` straight away. */
+export interface ScreenAxis {
+ dx: number;
+ dy: number;
+ depth: number;
+}
+
+/**
+ * Where the world axes point on screen for this view. Read off the very basis the
+ * camera is built from, so an indicator drawn from it cannot disagree with what is
+ * rendered — a second copy of the rotation is exactly how those two drift apart.
+ */
+export function editorViewAxes(view: EditorViewData): { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis } {
+ const rad = Math.PI / 180;
+ const m = invertViewOrbit(0, 0, 0, (view.yaw ?? 0) * rad, (view.pitch ?? 0) * rad, 0);
+ // Column c of the view matrix is a world axis expressed in view space.
+ const axis = (c: number): ScreenAxis => ({ dx: m[c], dy: -m[c + 1], depth: m[c + 2] });
+ return { x: axis(0), y: axis(4), z: axis(8) };
+}
+
+/**
+ * Yaw/pitch that put the eye on a world axis, looking back down it — the standard
+ * views (front, side, top) every DCC offers. `sign` picks which end of the axis the
+ * eye stands on.
+ */
+export function editorViewAxisAngles(axis: 'x' | 'y' | 'z', sign: 1 | -1): { yaw: number; pitch: number } {
+ if (axis === 'y') return { yaw: 0, pitch: 90 * sign };
+ if (axis === 'x') return { yaw: 90 * sign, pitch: 0 };
+ return { yaw: sign > 0 ? 0 : 180, pitch: 0 };
+}
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 9f0b9f303..190b77c01 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -40,8 +40,8 @@ export { TextureFilter, TextureWrap, setTextureFilter, setTextureWrap, setTextur
// =============================================================================
export { CameraView, CameraViewAPI } from './camera/Camera';
-export { EditorView, DEFAULT_EDITOR_VIEW, editorViewHalfHeight, editorViewHalfExtent, setEditorViewHalfHeight, editorViewIsOrbited } from './camera/EditorView';
-export type { EditorViewData } from './camera/EditorView';
+export { EditorView, DEFAULT_EDITOR_VIEW, editorViewHalfHeight, editorViewHalfExtent, setEditorViewHalfHeight, editorViewIsOrbited, editorViewAxes, editorViewAxisAngles } from './camera/EditorView';
+export type { EditorViewData, ScreenAxis } from './camera/EditorView';
export { ScreenScaling, DEFAULT_SCREEN_SCALING, SCREEN_FIT_OFF } from './camera/ScreenScaling';
export type { ScreenScalingData } from './camera/ScreenScaling';
export { EditorGrid, DEFAULT_EDITOR_GRID } from './camera/EditorGrid';
diff --git a/sdk/tests/editor-view-orbit.test.ts b/sdk/tests/editor-view-orbit.test.ts
index b1b1d1739..b131cbfc1 100644
--- a/sdk/tests/editor-view-orbit.test.ts
+++ b/sdk/tests/editor-view-orbit.test.ts
@@ -10,7 +10,9 @@
import { describe, expect, it } from 'vitest';
import { invertViewZ, invertViewOrbit, multiply, perspective, ortho } from '../src/math/mat4';
import { editorCameraInfo } from '../src/camera/CameraPlugin';
-import { DEFAULT_EDITOR_VIEW, editorViewIsOrbited } from '../src/camera/EditorView';
+import {
+ DEFAULT_EDITOR_VIEW, editorViewIsOrbited, editorViewAxes, editorViewAxisAngles, editorViewHalfHeight,
+} from '../src/camera/EditorView';
import { screenToWorld, invertMatrix4 } from '../src/ui/util/math';
const project = (vp: Float32Array, x: number, y: number, z: number) => {
@@ -73,3 +75,64 @@ describe('the editor view, orbited', () => {
expect(centre.y).toBeCloseTo(view.y, 3);
});
});
+
+describe('what the view sees', () => {
+ // The zoom readout is canvas height / (2 × half-height). Were the camera to
+ // frame a different extent, every percentage shown would be off by that factor.
+ it.each([
+ ['orthographic', { orthoSize: 200 }],
+ ['perspective', { perspective: true, fov: 60, distance: 1000 }],
+ ])('puts its half-height on the top edge, %s', (_name, over) => {
+ const view = { ...DEFAULT_EDITOR_VIEW, active: true, ...over };
+ const cam = editorCameraInfo(view, 400, 300, []);
+ expect(project(cam.viewProjection, 0, editorViewHalfHeight(view), 0).y).toBeCloseTo(1);
+ });
+});
+
+describe('where the world axes point on screen', () => {
+ it('is the 2D reading when the eye has not turned', () => {
+ // Signed zero normalized, as in the head-on matrix above.
+ const a = editorViewAxes(DEFAULT_EDITOR_VIEW);
+ const cells = (s: { dx: number; dy: number; depth: number }) => [s.dx + 0, s.dy + 0, s.depth + 0];
+ expect(cells(a.x)).toEqual([1, 0, 0]); // right
+ expect(cells(a.y)).toEqual([0, -1, 0]); // up (screen y is down)
+ expect(cells(a.z)).toEqual([0, 0, 1]); // straight at the eye
+ });
+
+ it('agrees with where the camera actually projects those axes', () => {
+ // The whole point of reading the indicator off the view basis: disagreeing
+ // with the rendered frame would point users the wrong way. One scale factor
+ // for all three asserts foreshortening too — an axis leaning at the eye is SHORT.
+ const view = { ...DEFAULT_EDITOR_VIEW, active: true, yaw: 37, pitch: 21 };
+ const cam = editorCameraInfo(view, 256, 256, []);
+ const o = project(cam.viewProjection, view.x, view.y, 0);
+ const axes = editorViewAxes(view);
+ const shift = (d: readonly number[]) => {
+ const p = project(cam.viewProjection, view.x + d[0]! * 50, view.y + d[1]! * 50, d[2]! * 50);
+ // NDC y is up, screen y is down — the sign the indicator has to carry.
+ return { x: p.x - o.x, y: -(p.y - o.y) };
+ };
+ const first = shift([1, 0, 0]);
+ const k = Math.hypot(first.x, first.y) / Math.hypot(axes.x.dx, axes.x.dy);
+ for (const [name, d] of [['x', [1, 0, 0]], ['y', [0, 1, 0]], ['z', [0, 0, 1]]] as const) {
+ const s = shift(d);
+ expect(s.x).toBeCloseTo(axes[name].dx * k, 6);
+ expect(s.y).toBeCloseTo(axes[name].dy * k, 6);
+ }
+ });
+
+ it('stands the eye on the axis it was asked for, poles included', () => {
+ for (const axis of ['x', 'y', 'z'] as const) {
+ for (const sign of [1, -1] as const) {
+ const a = editorViewAxisAngles(axis, sign);
+ const axes = editorViewAxes({ ...DEFAULT_EDITOR_VIEW, ...a });
+ // The chosen axis comes straight at the eye; the other two are flat
+ // across the screen, which is what "a square-on view" means.
+ expect(axes[axis].depth).toBeCloseTo(sign, 5);
+ for (const other of (['x', 'y', 'z'] as const).filter(k => k !== axis)) {
+ expect(axes[other].depth).toBeCloseTo(0, 5);
+ }
+ }
+ }
+ });
+});