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): the editor's view has a focus in space and a plane it works on

yhh890fd0a84280
diff --git a/CHANGELOG.md b/CHANGELOG.md
index de1c3aacd..f171e5ed1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,32 @@ published separately; it ships inside the editor.
### Added
+- **The editor's view has a focus in space, and a plane it works on.** The editor
+ eye could turn, and everything else about it was still pinned to z = 0: it
+ orbited a point on that plane, panned across it, framed on it, and drew its grid
+ there. A 3D scene stands on the ground (y = 0), so what the grid drew was a wall
+ you turned around, and a pan from a top-down eye slid along a plane seen edge-on.
+
+ `EditorView` gains a `z`, so its focus is a point rather than a place on the 2D
+ plane, and `editorViewBasis` reads the view's own right / up / forward off the
+ matrix the camera is built from. Pan, zoom-about-cursor and Frame move that focus
+ through the basis (`moveEditorViewFocus`) and fit against it
+ (`editorViewBoxExtent`) instead of intersecting a fixed plane; head-on they are
+ the 2D navigation to the bit.
+
+ `editorViewWorkPlane` names the plane the view authors on — the ground under a
+ perspective eye, the plane 2D content lives on under an orthographic one — and
+ the grid draws that. The grid is a per-pixel ray against the plane now, not a
+ quad sized to a visible rect, with `fwidth` of the plane coordinate deciding line
+ width and where lines fade; so a ground plane recedes to its own horizon instead
+ of ending at a quad edge. Its axis lines are coloured by which world axes run in
+ the plane, which is why `EditorGrid` carries one colour per axis.
+
+ Gate `editor-grid-3d`, both backends: the grid from straight above a perspective
+ view has to reach all four quarters of the frame. Pinned back to the 2D plane it
+ lights the lower half and nothing else. The headless host can enter 3D now
+ (`ESTELLA_VERIFY_PERSPECTIVE`), which is what let a gate see any of this.
+
- **A twin written in a template literal is still a twin.** `check-wgsl-twin` read
`.esshader` files, and the SDK writes some of its dual-language shaders into
template literals instead — the editor grid, the post-process effects, the seven
diff --git a/desktop/scripts/headless-verify.mjs b/desktop/scripts/headless-verify.mjs
index b349c27ba..dd906a88f 100644
--- a/desktop/scripts/headless-verify.mjs
+++ b/desktop/scripts/headless-verify.mjs
@@ -301,15 +301,17 @@ app.whenReady().then(async () => {
})()`);
}
- // ESTELLA_VERIFY_ORBIT="<yaw>,<pitch>" turns the editor's eye before the frame
- // is read — the 3D navigation, driven the way Alt-drag drives it.
- if (process.env.ESTELLA_VERIFY_ORBIT) {
- const [yaw, pitch] = process.env.ESTELLA_VERIFY_ORBIT.split(',').map(Number);
+ // ESTELLA_VERIFY_PERSPECTIVE=1 looks at the scene as a 3D one and
+ // ESTELLA_VERIFY_ORBIT="<yaw>,<pitch>" turns the eye. Perspective first: it
+ // parks the eye at an angle of its own, which the orbit then overrides.
+ if (process.env.ESTELLA_VERIFY_PERSPECTIVE || process.env.ESTELLA_VERIFY_ORBIT) {
+ const [yaw, pitch] = (process.env.ESTELLA_VERIFY_ORBIT ?? '0,0').split(',').map(Number);
await exec(`(async () => {
const api = window.__estellaHeadless.api;
- // The orbit belongs to the editor's eye, so the frame has to be drawn
- // through it rather than through the scene's own camera.
+ // The eye belongs to the editor, so the frame has to be drawn through it
+ // rather than through the scene's own camera.
api.useEditorView(true);
+ ${process.env.ESTELLA_VERIFY_PERSPECTIVE ? 'api.setViewPerspective(true);' : ''}
api.setViewOrbit(${yaw || 0}, ${pitch || 0});
await api.step(2, 1 / 60);
})()`);
@@ -599,12 +601,20 @@ app.whenReady().then(async () => {
await exec('window.__estellaHeadless.api.step(2, 1 / 60)');
grid = await readFrame(`
const on = window.__estellaGridOn;
+ const quadrants = [0, 0, 0, 0];
let differing = 0;
- for (let i = 0; i < on.length; i += 4) {
- const d = Math.abs(on[i] - px[i]) + Math.abs(on[i + 1] - px[i + 1]) + Math.abs(on[i + 2] - px[i + 2]);
- if (d > 12) differing++;
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const i = (y * w + x) * 4;
+ const d = Math.abs(on[i] - px[i]) + Math.abs(on[i + 1] - px[i + 1]) + Math.abs(on[i + 2] - px[i + 2]);
+ if (d <= 12) continue;
+ differing++;
+ quadrants[(y < h / 2 ? 0 : 2) + (x < w / 2 ? 0 : 1)]++;
+ }
}
- return { differingPixels: differing, ok: differing > 300 };
+ // A grid is there everywhere you look, so every quarter of the frame has
+ // some of it. A plane seen edge-on lights one band and passes a total.
+ return { differingPixels: differing, quadrants, ok: differing > 300 && quadrants.every((q) => q > 20) };
`);
}
finish({ ok: true, entityCount, drawCalls, draws, capture, expect, resize, preview, meshPreview, grid, deviceLoss, meshResident, meshAsset, meshMaterial, meshPrefab, setField, pick }, server);
diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.ts
index 7dcaec0ab..b59abbff5 100644
--- a/desktop/src/engine/EditorControlSurface.ts
+++ b/desktop/src/engine/EditorControlSurface.ts
@@ -859,6 +859,15 @@ export class EditorControlSurfaceImpl {
return ViewportController.orbitAngles();
}
+ /**
+ * Look at the scene as a 3D one: a perspective eye, and the ground for a work
+ * plane. Turning it on parks the eye at an angle, so a driver that wants a
+ * specific one calls {@link setViewOrbit} after this rather than before.
+ */
+ setViewPerspective(on: boolean): void {
+ EngineHost.setViewPerspective(on);
+ }
+
/** 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/EngineHost.ts b/desktop/src/engine/EngineHost.ts
index 301adfb99..6b5f21e52 100644
--- a/desktop/src/engine/EngineHost.ts
+++ b/desktop/src/engine/EngineHost.ts
@@ -342,6 +342,9 @@ class EngineHostImpl {
if (cam) {
view.x = cam.x;
view.y = cam.y;
+ // Not the camera's z: that is where its EYE stands, and adopting it as a
+ // focus would put everything the camera frames behind the editor's own.
+ view.z = 0;
// The scene camera's framing, as an extent the editor view SEES — under a
// perspective eye that is a distance, not an orthoSize.
setEditorViewHalfHeight(view, cam.orthoSize);
@@ -354,18 +357,21 @@ class EngineHostImpl {
* exact scene view they left (syncEditorViewToScene would otherwise reframe).
* The seen extent rather than the raw field, so a view saved in perspective and
* restored in either projection comes back to the same framing. */
- editorViewState(): { x: number; y: number; orthoSize: number } | null {
+ editorViewState(): { x: number; y: number; z: number; orthoSize: number } | null {
const view = this.getResource(EditorView);
- return view ? { x: view.x, y: view.y, orthoSize: editorViewHalfHeight(view) } : null;
+ return view
+ ? { x: view.x, y: view.y, z: view.z ?? 0, orthoSize: editorViewHalfHeight(view) }
+ : null;
}
/** Restore the editor camera to a saved center + zoom (the inverse read of
* {@link editorViewState}). No-op pre-boot. */
- setEditorView(v: { x: number; y: number; orthoSize: number }): void {
+ setEditorView(v: { x: number; y: number; z?: number; orthoSize: number }): void {
const view = this.getResource(EditorView);
if (!view) return;
view.x = v.x;
view.y = v.y;
+ view.z = v.z ?? 0;
setEditorViewHalfHeight(view, v.orthoSize);
}
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index 7c6ed97f9..c664af3e3 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -17,6 +17,7 @@ import {
layerOrderOf,
editorViewHalfHeight, editorViewHalfExtent, setEditorViewHalfHeight, EDITOR_UI_ANCHOR,
entityWorldBox, uiNodeWorldBox, meshWorldBox, editorViewIsOrbited,
+ moveEditorViewFocus, editorViewBoxExtent,
editorViewAxes, editorViewAxisAngles, cameraFrustumCorners, type ScreenAxis,
rayPlaneHit, type WorldRay, type Vec3,
type TilesetModel, type TileCollisionPiece, type TileGridParams,
@@ -118,6 +119,27 @@ function setZoomAmount(view: EditorViewData, value: number): void {
setEditorViewHalfHeight(view, Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, value)));
}
+/** World units per CSS pixel at the focus — the scale every navigation drag is in. */
+function worldPerPixel(view: EditorViewData): number | null {
+ const canvas = EngineHost.canvas;
+ if (!canvas) return null;
+ const dpr = window.devicePixelRatio || 1;
+ const h = canvas.height / dpr;
+ return h > 0 ? (2 * zoomAmount(view)) / h : null;
+}
+
+/** A client point in normalized device coordinates (-1..1, y up). */
+function clientToNdc(clientX: number, clientY: number): { nx: number; ny: number } | null {
+ const canvas = EngineHost.canvas;
+ if (!canvas) return null;
+ const r = canvas.getBoundingClientRect();
+ if (r.width <= 0 || r.height <= 0) return null;
+ return {
+ nx: ((clientX - r.left) / r.width) * 2 - 1,
+ ny: 1 - ((clientY - r.top) / r.height) * 2,
+ };
+}
+
/** DOM pointer position → engine screen space (buffer px, y-up). */
function clientToScreen(clientX: number, clientY: number): { sx: number; sy: number } | null {
const canvas = EngineHost.canvas;
@@ -191,8 +213,8 @@ export const ViewportController = {
* The default plane is the 2D one, which is the whole answer under an
* orthographic view — a screen point's world x/y do not change with depth
* there. In a perspective view they do, so anything that hits or drags a
- * specific entity should pass that entity's z; navigation (pan, zoom, framing)
- * keeps the 2D plane, which is the plane it is navigating over.
+ * specific entity should pass that entity's z. Navigation asks nothing here:
+ * it moves the focus along the view's own axes.
*/
canvasToWorld(clientX: number, clientY: number, planeZ = 0): { x: number; y: number } | null {
const cv = cameraView();
@@ -481,15 +503,20 @@ export const ViewportController = {
return screenAABB(obbCorners(b).map(([wx, wy]) => toClient(wx, wy)));
},
- /** Pan the editor view by a CSS-pixel drag (prev→cur). Moves only the editor camera. */
+ /**
+ * Pan the editor view by a CSS-pixel drag (prev→cur). Moves only the editor camera.
+ *
+ * The focus slides along the view's OWN right and up, so a drag moves the world
+ * across the screen from any angle. Against a fixed world plane it would slide
+ * along that plane instead, which from a top-down eye is a plane seen edge-on.
+ */
panByClient(prevX: number, prevY: number, curX: number, curY: number): void {
const view = editorView();
if (!view) return;
- const a = this.canvasToWorld(prevX, prevY);
- const b = this.canvasToWorld(curX, curY);
- if (!a || !b) return;
- view.x += a.x - b.x;
- view.y += a.y - b.y;
+ const wpp = worldPerPixel(view);
+ if (wpp == null) return;
+ // Screen y is down, so a drag downward moves the focus up.
+ moveEditorViewFocus(view, -(curX - prevX) * wpp, (curY - prevY) * wpp);
},
/**
@@ -532,11 +559,9 @@ export const ViewportController = {
*/
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;
+ if (!view) return null;
+ const wpp = worldPerPixel(view);
+ return wpp != null && wpp > 0 ? 1 / wpp : null;
},
/** Where the eye stands, in degrees (0/0 = head-on). */
@@ -569,22 +594,25 @@ export const ViewportController = {
setZoomAmount(view, zoomAmount(view) * factor);
},
- /** Zoom about the cursor: the world point under (clientX, clientY) stays put, so
- * you zoom INTO what you're looking at (Figma/Blender/Godot). Analytic — no
- * post-zoom re-project (the engine camera only updates next frame): for an ortho
- * camera the world offset from center scales with orthoSize, so the new center is
- * `view + (W − view)·(1 − factor)`. */
+ /**
+ * Zoom about the cursor: the world point under it stays put (Figma/Blender).
+ *
+ * Analytic rather than a re-project (the engine camera updates next frame):
+ * what the view sees at the focus scales about it, so the focus moves by the
+ * same fraction along the offset the cursor names in the view's own axes.
+ */
zoomAtClient(clientX: number, clientY: number, factor: number): void {
const view = editorView();
+ const canvas = EngineHost.canvas;
+ const n = clientToNdc(clientX, clientY);
if (!view) return;
- const w = this.canvasToWorld(clientX, clientY); // current matrices — read BEFORE zoom
const before = zoomAmount(view);
setZoomAmount(view, before * factor);
const applied = zoomAmount(view) / before; // clamped factor
- if (w) {
- view.x += (w.x - view.x) * (1 - applied);
- view.y += (w.y - view.y) * (1 - applied);
- }
+ if (!n || !canvas) return;
+ const aspect = canvas.height > 0 ? canvas.width / canvas.height : 1;
+ const k = 1 - applied;
+ moveEditorViewFocus(view, n.nx * before * aspect * k, n.ny * before * k);
},
/**
@@ -595,12 +623,15 @@ export const ViewportController = {
frameSelection(ids: readonly EntityId[]): void {
const view = editorView();
const canvas = EngineHost.canvas;
+ const world = EngineHost.world;
if (!view || ids.length === 0) return;
let minX = Infinity;
let minY = Infinity;
+ let minZ = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
+ let maxZ = -Infinity;
for (const id of ids) {
const b = this.entityBounds(id) ?? this.uiEntityWorldOBB(id);
if (!b) continue;
@@ -610,18 +641,28 @@ export const ViewportController = {
maxX = Math.max(maxX, wx);
maxY = Math.max(maxY, wy);
}
+ // Depth comes from the entity until a box carries one of its own; without
+ // it Frame centres on the 2D plane whatever it was asked to look at.
+ const z = world?.has(id, Transform) ? world.get(id, Transform).worldPosition.z : 0;
+ minZ = Math.min(minZ, z);
+ maxZ = Math.max(maxZ, z);
}
if (!Number.isFinite(minX)) return;
view.x = (minX + maxX) / 2;
view.y = (minY + maxY) / 2;
+ view.z = (minZ + maxZ) / 2;
- const spanX = maxX - minX;
- const spanY = maxY - minY;
+ // Fit the box as the EYE sees it. Head-on that is the box's own width and
+ // height; from any other angle it is what the box covers on screen.
+ const span = editorViewBoxExtent(view, {
+ x: (maxX - minX) / 2, y: (maxY - minY) / 2, z: (maxZ - minZ) / 2,
+ });
+ const spanR = span.right;
+ const spanU = span.up;
const aspect = canvas && canvas.height > 0 ? canvas.width / canvas.height : 1;
- // Fit whichever axis is the binding constraint, in SEEN half-height — which
- // the perspective view reaches by moving the camera, not by writing orthoSize
- // (a field it does not render through: framing simply did nothing there).
- const halfH = Math.max(spanY / 2, aspect > 0 ? spanX / 2 / aspect : spanX / 2) * 1.2;
+ // In SEEN half-height, which the perspective view reaches by moving the camera
+ // rather than by writing orthoSize — a field it does not render through.
+ const halfH = Math.max(spanU, aspect > 0 ? spanR / aspect : spanR) * 1.2;
if (halfH > 1) setZoomAmount(view, halfH);
},
@@ -648,6 +689,7 @@ export const ViewportController = {
if (desHalfW <= 0 || desHalfH <= 0) return;
view.x = ci.cx;
view.y = ci.cy;
+ view.z = 0; // the design frame is the 2D plane's, and so is the view of it
const aspect = panel && panel.height > 0 ? panel.width / panel.height : 1;
const halfH = Math.max(desHalfH, aspect > 0 ? desHalfW / aspect : desHalfW) * 1.1;
setZoomAmount(view, halfH);
diff --git a/desktop/src/i18n/messages/viewport.ts b/desktop/src/i18n/messages/viewport.ts
index 03b46d9c1..5c01cbc88 100644
--- a/desktop/src/i18n/messages/viewport.ts
+++ b/desktop/src/i18n/messages/viewport.ts
@@ -102,7 +102,7 @@ export const viewportMessages = defineMessages({
},
'vp.pivot.pivot': { en: 'Pivot', zh: '轴心' },
'vp.pivot.center': { en: 'Center', zh: '中心' },
- 'vp.projectionTitle': { en: 'The editor eye: 3D looks at the scene in perspective, from an angle. Alt-drag turns it further; each mode keeps the angle you left it at. Does not change the game camera.', zh: '编辑器视角:3D 用透视、从一个角度看场景。Alt+拖拽可继续转动;两种模式各自记住你离开时的角度。不影响游戏相机。' },
+ 'vp.projectionTitle': { en: 'The editor eye: 3D looks at the scene in perspective, from an angle, and stands the grid on the ground. 2D keeps the flat view and the grid on the plane 2D content lives on. Alt-drag turns the eye further; each mode keeps the angle you left it at. Does not change the game camera.', zh: '编辑器视角:3D 用透视、从一个角度看场景,网格铺在地面上。2D 保持正面平视,网格在 2D 内容所在的平面上。Alt+拖拽可继续转动;两种模式各自记住你离开时的角度。不影响游戏相机。' },
'vp.proj.ortho': { en: '2D', zh: '2D' },
'vp.proj.perspective': { en: '3D', zh: '3D' },
'vp.resetOrbitTitle': {
diff --git a/desktop/tests/viewport-navigation.test.ts b/desktop/tests/viewport-navigation.test.ts
new file mode 100644
index 000000000..1fcaf8b5f
--- /dev/null
+++ b/desktop/tests/viewport-navigation.test.ts
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Panning and zooming the editor view, which move a focus in three
+ * dimensions through the view's own axes.
+ *
+ * The SDK owns what those axes are; this is the wiring above it — the pixel
+ * scale a drag is measured in, and which way the focus goes. A sign or a scale
+ * wrong here is a viewport that fights the cursor, and no unit test of the basis
+ * would say so.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { DEFAULT_EDITOR_VIEW, editorViewHalfExtent, type EditorViewData } from 'esengine';
+
+const host = vi.hoisted(() => ({
+ view: null as EditorViewData | null,
+ canvas: null as unknown,
+}));
+
+vi.mock('@/engine/EngineHost', () => ({
+ EngineHost: {
+ getResource: () => host.view,
+ get canvas() { return host.canvas; },
+ get world() { return null; },
+ },
+}));
+
+import { ViewportController } from '@/engine/ViewportController';
+
+const W = 800;
+const H = 600;
+const ASPECT = W / H;
+
+// 600 CSS pixels of height over 2 × 300 world units: one world unit per pixel,
+// so every expectation below is the drag in pixels.
+const view = (over: Partial<EditorViewData>): EditorViewData =>
+ ({ ...DEFAULT_EDITOR_VIEW, active: true, orthoSize: 300, ...over });
+
+/** A perspective view that sees the same 300 world units of half-height. */
+const perspectiveView = (over: Partial<EditorViewData>): EditorViewData =>
+ view({ perspective: true, fov: 60, distance: 300 / Math.tan(Math.PI / 6), ...over });
+
+/** Where a normalized screen point lands at the focus, from the view's own extent. */
+function under(v: EditorViewData, nx: number, ny: number): { x: number; y: number } {
+ const { halfW, halfH } = editorViewHalfExtent(v, ASPECT);
+ return { x: v.x + nx * halfW, y: v.y + ny * halfH };
+}
+
+beforeEach(() => {
+ (globalThis as { window?: unknown }).window = { devicePixelRatio: 1 };
+ host.canvas = {
+ width: W,
+ height: H,
+ getBoundingClientRect: () => ({ left: 0, top: 0, width: W, height: H }),
+ };
+});
+
+describe('panning the editor view', () => {
+ it('is the 2D pan it always was, head-on', () => {
+ const v = view({});
+ host.view = v;
+ ViewportController.panByClient(100, 100, 150, 130);
+ // The world follows the cursor: right and down by the drag.
+ expect(v.x).toBeCloseTo(-50, 6);
+ expect(v.y).toBeCloseTo(30, 6);
+ expect(v.z).toBeCloseTo(0, 6);
+ });
+
+ // The 2D plane is edge-on from up here. A pan measured against it would slide
+ // the focus along a plane the eye cannot see, or nowhere at all.
+ it('walks over the ground from a top-down eye', () => {
+ const v = perspectiveView({ pitch: 90 });
+ host.view = v;
+ ViewportController.panByClient(0, 0, 0, 30);
+ expect(v.y).toBeCloseTo(0, 6);
+ expect(Math.hypot(v.x, v.z)).toBeCloseTo(30, 6);
+ });
+
+ it('takes the drag at the zoom it is drawn at', () => {
+ const v = view({ orthoSize: 600 }); // half as zoomed in ⇒ twice the world per pixel
+ host.view = v;
+ ViewportController.panByClient(0, 0, 50, 0);
+ expect(v.x).toBeCloseTo(-100, 6);
+ });
+});
+
+describe('zooming about the cursor', () => {
+ it('leaves the world point under the cursor where it was', () => {
+ const v = view({});
+ host.view = v;
+ const nx = 0.75;
+ const ny = 0.5;
+ const before = under(v, nx, ny);
+
+ ViewportController.zoomAtClient(((nx + 1) / 2) * W, ((1 - ny) / 2) * H, 0.5);
+
+ expect(v.orthoSize).toBeCloseTo(150, 6);
+ const after = under(v, nx, ny);
+ expect(after.x).toBeCloseTo(before.x, 6);
+ expect(after.y).toBeCloseTo(before.y, 6);
+ });
+
+ it('keeps the focus on the ground plane from a top-down eye', () => {
+ const v = perspectiveView({ pitch: 90 });
+ host.view = v;
+ ViewportController.zoomAtClient(W * 0.9, H * 0.1, 0.5);
+ expect(v.y).toBeCloseTo(0, 6);
+ expect(Math.hypot(v.x, v.z)).toBeGreaterThan(1);
+ });
+});
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 285cef863..11badf512 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": 1572,
+ "experimental": 1582,
"deprecated": 3
},
- "total": 1758,
+ "total": 1768,
"subsystems": [
{
"id": "ecs",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 71bb89bd3..84ac8fb1e 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 · 1458 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1468 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1577,7 +1577,7 @@ far: number
fov: number
isActive: boolean
near: number
-orbit: { yaw: number; pitch: number; } | undefined
+orbit: { yaw: number; pitch: number; focusZ: number; } | undefined
orthoSize: number
pixelPerfect: boolean
priority: number
@@ -2795,8 +2795,7 @@ ResourceDef<EditorGridData>
## EditorGridData — interface @experimental
```
-axisX: GridColor
-axisY: GridColor
+axisColors: [GridColor, GridColor, GridColor]
color: GridColor
enabled: boolean
majorColor: GridColor
@@ -2809,6 +2808,13 @@ spacing: number
ResourceDef<EditorViewData>
```
+## EditorViewBasis — interface @experimental
+```
+forward: Vec3
+right: Vec3
+up: Vec3
+```
+
## EditorViewData — interface @experimental
```
active: boolean
@@ -2821,6 +2827,14 @@ uiPreviewAspect: number
x: number
y: number
yaw: number
+z: number
+```
+
+## EditorWorkPlane — interface @experimental
+```
+normal: WorldAxis
+u: WorldAxis
+v: WorldAxis
```
## EffectDef — interface @experimental
@@ -9057,6 +9071,11 @@ static new (): World
static prototype: World
```
+## WorldAxis — type @experimental
+```
+0 | 1 | 2
+```
+
## WorldRay — interface @experimental
```
dir: Vec3
@@ -9886,6 +9905,21 @@ DragPlugin
(axis: "x" | "y" | "z", sign: 1 | -1): { yaw: number; pitch: number; }
```
+## editorViewBasis — function @experimental
+```
+(view: EditorViewData): EditorViewBasis
+```
+
+## editorViewBoxExtent — function @experimental
+```
+(view: EditorViewData, half: Vec3): { right: number; up: number; }
+```
+
+## editorViewEye — function @experimental
+```
+(view: EditorViewData): Vec3
+```
+
## editorViewHalfExtent — function @experimental
```
(view: EditorViewData, aspect: number): { halfW: number; halfH: number; }
@@ -9901,6 +9935,16 @@ DragPlugin
(view: EditorViewData): boolean
```
+## editorViewStandoff — function @experimental
+```
+(view: EditorViewData): number
+```
+
+## editorViewWorkPlane — function @experimental
+```
+(view: EditorViewData): EditorWorkPlane
+```
+
## emptyAnimatorController — function @experimental
```
(): AnimatorControllerDef
@@ -10716,6 +10760,11 @@ Mesh2DPlugin
(def: BtDefinition, id: string, x: number, y: number): BtDefinition
```
+## moveEditorViewFocus — function @experimental
+```
+(view: EditorViewData, right: number, up: number, forward?: number): void
+```
+
## moveNode — function @beta
```
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
@@ -12006,6 +12055,11 @@ VideoPlugin
(config: AssetGroupsConfig | null | undefined, folder: string, mode: AssetGroupMode): AssetGroupsConfig
```
+## worldAxisVector — function @experimental
+```
+(axis: WorldAxis): Vec3
+```
+
## wrapSceneSystem — function @experimental
```
(app: App, sceneName: string, system: SystemDef): SystemDef
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 173a16eea..d50850621 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 · 1477 experimental · 3 deprecated
+Symbols: 113 public · 71 beta · 1487 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1577,7 +1577,7 @@ far: number
fov: number
isActive: boolean
near: number
-orbit: { yaw: number; pitch: number; } | undefined
+orbit: { yaw: number; pitch: number; focusZ: number; } | undefined
orthoSize: number
pixelPerfect: boolean
priority: number
@@ -2803,8 +2803,7 @@ ResourceDef<EditorGridData>
## EditorGridData — interface @experimental
```
-axisX: GridColor
-axisY: GridColor
+axisColors: [GridColor, GridColor, GridColor]
color: GridColor
enabled: boolean
majorColor: GridColor
@@ -2817,6 +2816,13 @@ spacing: number
ResourceDef<EditorViewData>
```
+## EditorViewBasis — interface @experimental
+```
+forward: Vec3
+right: Vec3
+up: Vec3
+```
+
## EditorViewData — interface @experimental
```
active: boolean
@@ -2829,6 +2835,14 @@ uiPreviewAspect: number
x: number
y: number
yaw: number
+z: number
+```
+
+## EditorWorkPlane — interface @experimental
+```
+normal: WorldAxis
+u: WorldAxis
+v: WorldAxis
```
## EffectDef — interface @experimental
@@ -9250,6 +9264,11 @@ static new (): World
static prototype: World
```
+## WorldAxis — type @experimental
+```
+0 | 1 | 2
+```
+
## WorldRay — interface @experimental
```
dir: Vec3
@@ -10119,6 +10138,21 @@ DragPlugin
(axis: "x" | "y" | "z", sign: 1 | -1): { yaw: number; pitch: number; }
```
+## editorViewBasis — function @experimental
+```
+(view: EditorViewData): EditorViewBasis
+```
+
+## editorViewBoxExtent — function @experimental
+```
+(view: EditorViewData, half: Vec3): { right: number; up: number; }
+```
+
+## editorViewEye — function @experimental
+```
+(view: EditorViewData): Vec3
+```
+
## editorViewHalfExtent — function @experimental
```
(view: EditorViewData, aspect: number): { halfW: number; halfH: number; }
@@ -10134,6 +10168,16 @@ DragPlugin
(view: EditorViewData): boolean
```
+## editorViewStandoff — function @experimental
+```
+(view: EditorViewData): number
+```
+
+## editorViewWorkPlane — function @experimental
+```
+(view: EditorViewData): EditorWorkPlane
+```
+
## emptyAnimatorController — function @experimental
```
(): AnimatorControllerDef
@@ -10959,6 +11003,11 @@ Mesh2DPlugin
(def: BtDefinition, id: string, x: number, y: number): BtDefinition
```
+## moveEditorViewFocus — function @experimental
+```
+(view: EditorViewData, right: number, up: number, forward?: number): void
+```
+
## moveNode — function @beta
```
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
@@ -12249,6 +12298,11 @@ VideoPlugin
(config: AssetGroupsConfig | null | undefined, folder: string, mode: AssetGroupMode): AssetGroupsConfig
```
+## worldAxisVector — function @experimental
+```
+(axis: WorldAxis): Vec3
+```
+
## wrapSceneSystem — function @experimental
```
(app: App, sceneName: string, system: SystemDef): SystemDef
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 403d4cd74..3df0a5ed6 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 · 1457 experimental · 3 deprecated
+Symbols: 113 public · 68 beta · 1467 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1572,7 +1572,7 @@ far: number
fov: number
isActive: boolean
near: number
-orbit: { yaw: number; pitch: number; } | undefined
+orbit: { yaw: number; pitch: number; focusZ: number; } | undefined
orthoSize: number
pixelPerfect: boolean
priority: number
@@ -2790,8 +2790,7 @@ ResourceDef<EditorGridData>
## EditorGridData — interface @experimental
```
-axisX: GridColor
-axisY: GridColor
+axisColors: [GridColor, GridColor, GridColor]
color: GridColor
enabled: boolean
majorColor: GridColor
@@ -2804,6 +2803,13 @@ spacing: number
ResourceDef<EditorViewData>
```
+## EditorViewBasis — interface @experimental
+```
+forward: Vec3
+right: Vec3
+up: Vec3
+```
+
## EditorViewData — interface @experimental
```
active: boolean
@@ -2816,6 +2822,14 @@ uiPreviewAspect: number
x: number
y: number
yaw: number
+z: number
+```
+
+## EditorWorkPlane — interface @experimental
+```
+normal: WorldAxis
+u: WorldAxis
+v: WorldAxis
```
## EffectDef — interface @experimental
@@ -9052,6 +9066,11 @@ static new (): World
static prototype: World
```
+## WorldAxis — type @experimental
+```
+0 | 1 | 2
+```
+
## WorldRay — interface @experimental
```
dir: Vec3
@@ -9881,6 +9900,21 @@ DragPlugin
(axis: "x" | "y" | "z", sign: 1 | -1): { yaw: number; pitch: number; }
```
+## editorViewBasis — function @experimental
+```
+(view: EditorViewData): EditorViewBasis
+```
+
+## editorViewBoxExtent — function @experimental
+```
+(view: EditorViewData, half: Vec3): { right: number; up: number; }
+```
+
+## editorViewEye — function @experimental
+```
+(view: EditorViewData): Vec3
+```
+
## editorViewHalfExtent — function @experimental
```
(view: EditorViewData, aspect: number): { halfW: number; halfH: number; }
@@ -9896,6 +9930,16 @@ DragPlugin
(view: EditorViewData): boolean
```
+## editorViewStandoff — function @experimental
+```
+(view: EditorViewData): number
+```
+
+## editorViewWorkPlane — function @experimental
+```
+(view: EditorViewData): EditorWorkPlane
+```
+
## emptyAnimatorController — function @experimental
```
(): AnimatorControllerDef
@@ -10716,6 +10760,11 @@ Mesh2DPlugin
(def: BtDefinition, id: string, x: number, y: number): BtDefinition
```
+## moveEditorViewFocus — function @experimental
+```
+(view: EditorViewData, right: number, up: number, forward?: number): void
+```
+
## moveNode — function @beta
```
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
@@ -12011,6 +12060,11 @@ VideoPlugin
(config: AssetGroupsConfig | null | undefined, folder: string, mode: AssetGroupMode): AssetGroupsConfig
```
+## worldAxisVector — function @experimental
+```
+(axis: WorldAxis): Vec3
+```
+
## wrapSceneSystem — function @experimental
```
(app: App, sceneName: string, system: SystemDef): SystemDef
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 51f981f36..2b57e678b 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 · 1478 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1488 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1572,7 +1572,7 @@ far: number
fov: number
isActive: boolean
near: number
-orbit: { yaw: number; pitch: number; } | undefined
+orbit: { yaw: number; pitch: number; focusZ: number; } | undefined
orthoSize: number
pixelPerfect: boolean
priority: number
@@ -2790,8 +2790,7 @@ ResourceDef<EditorGridData>
## EditorGridData — interface @experimental
```
-axisX: GridColor
-axisY: GridColor
+axisColors: [GridColor, GridColor, GridColor]
color: GridColor
enabled: boolean
majorColor: GridColor
@@ -2804,6 +2803,13 @@ spacing: number
ResourceDef<EditorViewData>
```
+## EditorViewBasis — interface @experimental
+```
+forward: Vec3
+right: Vec3
+up: Vec3
+```
+
## EditorViewData — interface @experimental
```
active: boolean
@@ -2816,6 +2822,14 @@ uiPreviewAspect: number
x: number
y: number
yaw: number
+z: number
+```
+
+## EditorWorkPlane — interface @experimental
+```
+normal: WorldAxis
+u: WorldAxis
+v: WorldAxis
```
## EffectDef — interface @experimental
@@ -9297,6 +9311,11 @@ static new (): World
static prototype: World
```
+## WorldAxis — type @experimental
+```
+0 | 1 | 2
+```
+
## WorldRay — interface @experimental
```
dir: Vec3
@@ -10131,6 +10150,21 @@ DragPlugin
(axis: "x" | "y" | "z", sign: 1 | -1): { yaw: number; pitch: number; }
```
+## editorViewBasis — function @experimental
+```
+(view: EditorViewData): EditorViewBasis
+```
+
+## editorViewBoxExtent — function @experimental
+```
+(view: EditorViewData, half: Vec3): { right: number; up: number; }
+```
+
+## editorViewEye — function @experimental
+```
+(view: EditorViewData): Vec3
+```
+
## editorViewHalfExtent — function @experimental
```
(view: EditorViewData, aspect: number): { halfW: number; halfH: number; }
@@ -10146,6 +10180,16 @@ DragPlugin
(view: EditorViewData): boolean
```
+## editorViewStandoff — function @experimental
+```
+(view: EditorViewData): number
+```
+
+## editorViewWorkPlane — function @experimental
+```
+(view: EditorViewData): EditorWorkPlane
+```
+
## emptyAnimatorController — function @experimental
```
(): AnimatorControllerDef
@@ -10971,6 +11015,11 @@ Mesh2DPlugin
(def: BtDefinition, id: string, x: number, y: number): BtDefinition
```
+## moveEditorViewFocus — function @experimental
+```
+(view: EditorViewData, right: number, up: number, forward?: number): void
+```
+
## moveNode — function @beta
```
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
@@ -12261,6 +12310,11 @@ VideoPlugin
(config: AssetGroupsConfig | null | undefined, folder: string, mode: AssetGroupMode): AssetGroupsConfig
```
+## worldAxisVector — function @experimental
+```
+(axis: WorldAxis): Vec3
+```
+
## wrapSceneSystem — function @experimental
```
(app: App, sceneName: string, system: SystemDef): SystemDef
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 7ce7fb711..8af81aa0c 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 · 1468 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1478 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1572,7 +1572,7 @@ far: number
fov: number
isActive: boolean
near: number
-orbit: { yaw: number; pitch: number; } | undefined
+orbit: { yaw: number; pitch: number; focusZ: number; } | undefined
orthoSize: number
pixelPerfect: boolean
priority: number
@@ -2790,8 +2790,7 @@ ResourceDef<EditorGridData>
## EditorGridData — interface @experimental
```
-axisX: GridColor
-axisY: GridColor
+axisColors: [GridColor, GridColor, GridColor]
color: GridColor
enabled: boolean
majorColor: GridColor
@@ -2804,6 +2803,13 @@ spacing: number
ResourceDef<EditorViewData>
```
+## EditorViewBasis — interface @experimental
+```
+forward: Vec3
+right: Vec3
+up: Vec3
+```
+
## EditorViewData — interface @experimental
```
active: boolean
@@ -2816,6 +2822,14 @@ uiPreviewAspect: number
x: number
y: number
yaw: number
+z: number
+```
+
+## EditorWorkPlane — interface @experimental
+```
+normal: WorldAxis
+u: WorldAxis
+v: WorldAxis
```
## EffectDef — interface @experimental
@@ -9079,6 +9093,11 @@ static new (): World
static prototype: World
```
+## WorldAxis — type @experimental
+```
+0 | 1 | 2
+```
+
## WorldRay — interface @experimental
```
dir: Vec3
@@ -9908,6 +9927,21 @@ DragPlugin
(axis: "x" | "y" | "z", sign: 1 | -1): { yaw: number; pitch: number; }
```
+## editorViewBasis — function @experimental
+```
+(view: EditorViewData): EditorViewBasis
+```
+
+## editorViewBoxExtent — function @experimental
+```
+(view: EditorViewData, half: Vec3): { right: number; up: number; }
+```
+
+## editorViewEye — function @experimental
+```
+(view: EditorViewData): Vec3
+```
+
## editorViewHalfExtent — function @experimental
```
(view: EditorViewData, aspect: number): { halfW: number; halfH: number; }
@@ -9923,6 +9957,16 @@ DragPlugin
(view: EditorViewData): boolean
```
+## editorViewStandoff — function @experimental
+```
+(view: EditorViewData): number
+```
+
+## editorViewWorkPlane — function @experimental
+```
+(view: EditorViewData): EditorWorkPlane
+```
+
## emptyAnimatorController — function @experimental
```
(): AnimatorControllerDef
@@ -10743,6 +10787,11 @@ Mesh2DPlugin
(def: BtDefinition, id: string, x: number, y: number): BtDefinition
```
+## moveEditorViewFocus — function @experimental
+```
+(view: EditorViewData, right: number, up: number, forward?: number): void
+```
+
## moveNode — function @beta
```
(g: MaterialGraph, id: string, x: number, y: number): MaterialGraph
@@ -12033,6 +12082,11 @@ VideoPlugin
(config: AssetGroupsConfig | null | undefined, folder: string, mode: AssetGroupMode): AssetGroupsConfig
```
+## worldAxisVector — function @experimental
+```
+(axis: WorldAxis): Vec3
+```
+
## wrapSceneSystem — function @experimental
```
(app: App, sceneName: string, system: SystemDef): SystemDef
diff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.ts
index 1285c9bc2..25e3d70cb 100644
--- a/sdk/src/camera/CameraPlugin.ts
+++ b/sdk/src/camera/CameraPlugin.ts
@@ -18,7 +18,7 @@ import type { Entity } from '../types';
import { UICameraInfo } from '../ui/core/ui-camera-info';
import { ProjectionType, SceneOwner, ClearFlags } from '../ecs/component';
import { uiLayoutRect, computeEffectiveOrthoSize, EDITOR_VIEW_ENTITY, type CanvasScale } from './uiLayoutRect';
-import { EditorView, DEFAULT_EDITOR_VIEW, editorViewIsOrbited, type EditorViewData } from './EditorView';
+import { EditorView, DEFAULT_EDITOR_VIEW, editorViewStandoff, type EditorViewData } from './EditorView';
import { ScreenScaling, DEFAULT_SCREEN_SCALING, SCREEN_FIT_OFF } from './ScreenScaling';
import { CameraDirector, createDirectorState, resolveMainPOV } from './CameraDirector';
import { RenderPipeline } from '../render/renderPipeline';
@@ -159,9 +159,10 @@ export interface CameraPOV {
* scalar above already says — so turning this on cannot move a 2D scene.
*/
tilt?: { x: number; y: number; z: number; w: number };
- /** Orbit about (x, y, z) in radians — an eye that stands off the -Z axis.
- * Absent (the 2D case) keeps the rotation-about-Z view exactly as it was. */
- orbit?: { yaw: number; pitch: number };
+ /** Orbit in radians about the focus (x, y, focusZ) — an eye that stands off
+ * the -Z axis. Absent (the 2D case) keeps the rotation-about-Z view exactly
+ * as it was; `z` is then the eye's own depth rather than a standoff. */
+ orbit?: { yaw: number; pitch: number; focusZ: number };
projection: number; // ProjectionType
orthoSize: number; // authored ortho half-height
fov: number;
@@ -302,7 +303,7 @@ export function buildCameraInfo(
// (editor navigation), a tilt is the camera's own transform inverted (a scene
// camera on 3D content), and 2D is the rotation-about-Z, untouched.
const view = pov.orbit
- ? invertViewOrbit(camX, camY, 0, pov.orbit.yaw, pov.orbit.pitch, pov.z)
+ ? invertViewOrbit(camX, camY, pov.orbit.focusZ, pov.orbit.yaw, pov.orbit.pitch, pov.z)
: pov.tilt
? invertViewQuat(camX, camY, pov.z, pov.tilt.x, pov.tilt.y, pov.tilt.z, pov.tilt.w)
: invertViewZ(camX, camY, pov.z, Math.cos(pov.rotation), Math.sin(pov.rotation));
@@ -423,16 +424,17 @@ export function editorCameraInfo(
isActive: true,
x: view.x,
y: view.y,
- // Perspective needs the camera to stand somewhere: it is the distance that
- // makes content near or far, where orthographically nothing depends on z.
- // Orthographically nothing depends on z — except where the eye stands,
- // which is what an orbit turns; so an orbited ortho view needs one too.
- z: view.perspective || editorViewIsOrbited(view) ? view.distance : 0,
+ // How far back the eye stands, which is what a perspective projection
+ // needs and what an orbit swings around.
+ z: editorViewStandoff(view),
rotation: 0,
- ...(editorViewIsOrbited(view)
- ? { orbit: { yaw: (view.yaw ?? 0) * Math.PI / 180,
- pitch: (view.pitch ?? 0) * Math.PI / 180 } }
- : {}),
+ // Always an orbit: at yaw = pitch = 0 invertViewOrbit IS the head-on 2D
+ // view, so the editor has one way to stand rather than two.
+ orbit: {
+ yaw: (view.yaw ?? 0) * Math.PI / 180,
+ pitch: (view.pitch ?? 0) * Math.PI / 180,
+ focusZ: view.z ?? 0,
+ },
projection: view.perspective ? ProjectionType.Perspective : ProjectionType.Orthographic,
orthoSize: view.orthoSize,
fov: view.fov,
diff --git a/sdk/src/camera/EditorGrid.ts b/sdk/src/camera/EditorGrid.ts
index 3af72401d..362de6f9c 100644
--- a/sdk/src/camera/EditorGrid.ts
+++ b/sdk/src/camera/EditorGrid.ts
@@ -13,9 +13,9 @@
* exactly like a UE5 / Unity scene grid.
*
* Colors are straight-alpha RGBA in 0..1. `spacing` is the minor line spacing in
- * world units; every `majorEvery`-th line is a heavier major line. The world
- * x=0 / y=0 axis lines use the axis colors (red X / green Y) so the origin reads
- * at a glance.
+ * world units; every `majorEvery`-th line is a heavier major line. The two world
+ * axes that run in the plane are drawn in their own colors, so the origin and
+ * which way the axes point read at a glance.
*/
import { defineResource } from '../ecs/resource';
@@ -32,10 +32,9 @@ export interface EditorGridData {
color: GridColor;
/** Major line color. */
majorColor: GridColor;
- /** World y=0 (horizontal) X-axis line color. */
- axisX: GridColor;
- /** World x=0 (vertical) Y-axis line color. */
- axisY: GridColor;
+ /** One color per world axis, indexed the way a WorldAxis is: x, y, z. Which two
+ * get drawn is the work plane's answer, not this resource's. */
+ axisColors: [GridColor, GridColor, GridColor];
}
export const DEFAULT_EDITOR_GRID: EditorGridData = {
@@ -44,8 +43,11 @@ export const DEFAULT_EDITOR_GRID: EditorGridData = {
majorEvery: 10,
color: [1, 1, 1, 0.05],
majorColor: [1, 1, 1, 0.1],
- axisX: [0.812, 0.357, 0.325, 0.55], // --ax-x #cf5b53
- axisY: [0.502, 0.725, 0.29, 0.55], // --ax-y #80b94a
+ axisColors: [
+ [0.812, 0.357, 0.325, 0.55], // --ax-x #cf5b53
+ [0.502, 0.725, 0.29, 0.55], // --ax-y #80b94a
+ [0.290, 0.561, 0.839, 0.55], // --ax-z #4a8fd6
+ ],
};
export const EditorGrid = defineResource<EditorGridData>({ ...DEFAULT_EDITOR_GRID }, 'EditorGrid');
diff --git a/sdk/src/camera/EditorView.ts b/sdk/src/camera/EditorView.ts
index 4586eb6ae..1b65665f3 100644
--- a/sdk/src/camera/EditorView.ts
+++ b/sdk/src/camera/EditorView.ts
@@ -18,13 +18,17 @@
*/
import { defineResource } from '../ecs/resource';
import { invertViewOrbit } from '../math/mat4';
+import type { Vec3 } from '../types';
export interface EditorViewData {
/** When true, the framebuffer + screen<->world use this view, not scene cameras. */
active: boolean;
- /** World-space camera center. */
+ /** World-space point the view looks at and turns around. */
x: number;
y: number;
+ /** Depth of that point. Zero is the 2D plane, where a project that never
+ * leaves it stays. */
+ z: number;
/** Half-height of the view in world units (zoom; smaller = more zoomed in). */
orthoSize: number;
/**
@@ -66,7 +70,7 @@ export interface EditorViewData {
}
export const DEFAULT_EDITOR_VIEW: EditorViewData = {
- active: false, x: 0, y: 0, orthoSize: 360, uiPreviewAspect: 0,
+ active: false, x: 0, y: 0, z: 0, orthoSize: 360, uiPreviewAspect: 0,
// Off by default: an existing project opens on exactly the view it always had.
perspective: false, fov: 60, distance: 1000, yaw: 0, pitch: 0,
};
@@ -134,13 +138,116 @@ export interface ScreenAxis {
* 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);
+ const m = orbitMatrix(view);
// 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) };
}
+// The one place yaw/pitch become a basis; everything below reads its rows.
+function orbitMatrix(view: EditorViewData): Float32Array {
+ const rad = Math.PI / 180;
+ return invertViewOrbit(0, 0, 0, (view.yaw ?? 0) * rad, (view.pitch ?? 0) * rad, 0);
+}
+
+/** The view's own axes as world directions — unit, and right-handed with forward. */
+export interface EditorViewBasis {
+ right: Vec3;
+ up: Vec3;
+ forward: Vec3;
+}
+
+/**
+ * Where the view's right / up / forward point in the world.
+ *
+ * A drag is a screen direction, and this is what it means in world terms. Read
+ * off the very matrix the camera is built from, so navigation cannot move along
+ * axes the picture was not drawn with.
+ */
+export function editorViewBasis(view: EditorViewData): EditorViewBasis {
+ const m = orbitMatrix(view);
+ return {
+ right: { x: m[0], y: m[4], z: m[8] },
+ up: { x: m[1], y: m[5], z: m[9] },
+ forward: { x: -m[2], y: -m[6], z: -m[10] },
+ };
+}
+
+/**
+ * How far the eye stands off the focus. A perspective eye has to stand
+ * somewhere, and so does an orbited orthographic one; head-on 2D does not.
+ */
+export function editorViewStandoff(view: EditorViewData): number {
+ return view.perspective || editorViewIsOrbited(view) ? view.distance : 0;
+}
+
+/** Where the eye stands in world space. */
+export function editorViewEye(view: EditorViewData): Vec3 {
+ const m = orbitMatrix(view);
+ const d = editorViewStandoff(view);
+ return {
+ x: view.x + m[2] * d,
+ y: view.y + m[6] * d,
+ z: (view.z ?? 0) + m[10] * d,
+ };
+}
+
+/**
+ * Move the focus by an offset in the view's OWN axes, in world units.
+ *
+ * Every navigation that is not a turn is this: a drag, a zoom about the cursor,
+ * a dolly. Expressing them here is what keeps them from each picking a world
+ * plane of their own, which is only the same answer while the eye is head-on.
+ */
+export function moveEditorViewFocus(
+ view: EditorViewData, right: number, up: number, forward = 0,
+): void {
+ const b = editorViewBasis(view);
+ view.x += b.right.x * right + b.up.x * up + b.forward.x * forward;
+ view.y += b.right.y * right + b.up.y * up + b.forward.y * forward;
+ view.z = (view.z ?? 0) + b.right.z * right + b.up.z * up + b.forward.z * forward;
+}
+
+/**
+ * How much of the screen's two axes an axis-aligned box of half-size @p half
+ * covers, in world units — what "fit this in the frame" has to measure.
+ */
+export function editorViewBoxExtent(
+ view: EditorViewData, half: Vec3,
+): { right: number; up: number } {
+ const b = editorViewBasis(view);
+ const along = (a: Vec3): number =>
+ Math.abs(a.x) * half.x + Math.abs(a.y) * half.y + Math.abs(a.z) * half.z;
+ return { right: along(b.right), up: along(b.up) };
+}
+
+/** A world axis, as an index into (x, y, z). */
+export type WorldAxis = 0 | 1 | 2;
+
+/** The world plane a view works on, through the origin: the two axes that run in
+ * it, and the one it is normal to. */
+export interface EditorWorkPlane {
+ u: WorldAxis;
+ v: WorldAxis;
+ normal: WorldAxis;
+}
+
+/**
+ * Which plane that is.
+ *
+ * The perspective toggle is the editor's word for "this view is looking at a 3D
+ * scene", and a 3D scene stands on the ground (y = 0). Orthographic is the 2D
+ * editor, whose plane is the one 2D content lives on.
+ */
+export function editorViewWorkPlane(view: EditorViewData): EditorWorkPlane {
+ return view.perspective ? { u: 0, v: 2, normal: 1 } : { u: 0, v: 1, normal: 2 };
+}
+
+/** A world axis as a unit vector. */
+export function worldAxisVector(axis: WorldAxis): Vec3 {
+ return { x: axis === 0 ? 1 : 0, y: axis === 1 ? 1 : 0, z: axis === 2 ? 1 : 0 };
+}
+
/**
* 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
diff --git a/sdk/src/camera/editorGridRenderer.ts b/sdk/src/camera/editorGridRenderer.ts
index 211d76dc3..ddba87aa5 100644
--- a/sdk/src/camera/editorGridRenderer.ts
+++ b/sdk/src/camera/editorGridRenderer.ts
@@ -2,21 +2,24 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file editorGridRenderer.ts
- * @brief Infinite world-space editor grid, drawn through the editor camera.
+ * @brief Infinite world-space editor grid, drawn on the view's work plane.
*
* `installEditorGrid(app)` registers a pre-scene draw callback (see customDraw /
* RenderPipeline): each editor frame, when `EditorGrid.enabled` and the
- * `EditorView` is active, it draws one full-viewport quad whose fragment shader
- * paints minor / major / axis lines in WORLD space. Because it runs in the
- * pre-scene pass, scene entities occlude the grid (UE5 / Unity behaviour).
+ * `EditorView` is active, it draws one full-screen quad whose fragment shader
+ * intersects that pixel's world ray with the plane the view works on
+ * (`editorViewWorkPlane`) and paints minor / major / axis lines there. Because it
+ * runs in the pre-scene pass, scene entities draw over it (UE5 / Unity
+ * behaviour).
*
- * The quad is a unit quad placed by the `u_rect` param (centre = EditorView.x/y,
- * half-extents = `editorViewHalfExtent`) to cover the camera's visible world rect
- * on the z = 0 plane, so the fragment's interpolated world position is exact and
- * no inverse view-projection is needed — under either projection, since that is
- * the one place the extent is worked out. Line width and minor-line density fade
- * are driven by `worldPerPixel` (= 2·halfH / viewportHeight), so the grid stays
- * crisp and moiré-free at every zoom without relying on GLSL derivatives.
+ * The ray is built from the view's own basis rather than from a matrix inverse:
+ * four vec4 params carry the eye, the two screen axes scaled to what the view
+ * sees, and the forward reach, and one `w` flag decides whether a screen offset
+ * moves the ray's origin (orthographic) or turns its direction (perspective). So
+ * both projections run the same three lines, and the grid is bounded by nothing
+ * — line width and the legibility fade come from `fwidth` of the plane
+ * coordinate, which is what makes a tilted ground plane fade out at its horizon
+ * instead of aliasing or ending at a quad edge.
*
* The shader is a dual-language `.esshader` (GLSL + WGSL twins) on the reflected
* `#pragma param` seam: parameters ride the MaterialConstants UBO and the draw
@@ -32,43 +35,59 @@ import { Geometry, type GeometryHandle } from '../render/geometry';
import { Material, type MaterialHandle } from '../render/material';
import { BlendMode } from '../render/blend';
import { registerPreSceneDrawCallback } from '../render/customDraw';
-import { EditorView, editorViewHalfExtent } from './EditorView';
+import {
+ EditorView, editorViewHalfHeight, editorViewBasis, editorViewEye,
+ editorViewStandoff, editorViewWorkPlane, worldAxisVector,
+} from './EditorView';
import { EditorGrid, DEFAULT_EDITOR_GRID } from './EditorGrid';
/** The grid's dual-language material shader (exported for the twins structure guard). */
export const GRID_ESSHADER = `#pragma shader "EditorGrid"
#pragma version 300 es
-#pragma param u_rect vec4 default(0,0,1,1)
-#pragma param u_gridParams vec4 default(32,10,1,0)
+#pragma param u_planeU vec4 default(1,0,0,0)
+#pragma param u_planeV vec4 default(0,1,0,0)
+#pragma param u_rayOrigin vec4 default(0,0,0,1)
+#pragma param u_rayRight vec4 default(1,0,0,0)
+#pragma param u_rayUp vec4 default(0,1,0,0)
+#pragma param u_rayForward vec4 default(0,0,-1,0)
+#pragma param u_gridParams vec4 default(32,10,0,0)
#pragma param u_minorColor color default(1,1,1,0.05)
#pragma param u_majorColor color default(1,1,1,0.1)
-#pragma param u_axisXColor color default(0.812,0.357,0.325,0.55)
-#pragma param u_axisYColor color default(0.502,0.725,0.29,0.55)
+#pragma param u_axisUColor color default(0.812,0.357,0.325,0.55)
+#pragma param u_axisVColor color default(0.502,0.725,0.29,0.55)
#pragma vertex
layout(location = 0) in vec2 a_position;
-out vec2 v_world;
+out vec2 v_ndc;
void main() {
- // u_rect: xy = view centre, zw = half extents — the unit quad covers the
- // camera's visible world rect, so v_world interpolates exact world coords.
- vec2 world = u_rect.xy + a_position * u_rect.zw;
- v_world = world;
- gl_Position = u_projection * vec4(world, 0.0, 1.0);
+ // Clip space directly: the quad is the screen, and where the world is behind
+ // each pixel is the fragment stage's question.
+ v_ndc = a_position;
+ gl_Position = vec4(a_position, 1.0, 1.0);
}
#pragma end
#pragma fragment
precision highp float;
-in vec2 v_world;
+in vec2 v_ndc;
out vec4 fragColor;
-float lineCov(float coord, float sp, float lw, float aa) {
- float d = abs(mod(coord + sp * 0.5, sp) - sp * 0.5);
- return 1.0 - smoothstep(lw, lw + aa, d);
+// How legible lines of this spacing still are, given world units per pixel.
+float fade(float wpp, float sp) {
+ return smoothstep(3.0, 9.0, sp / max(wpp, 1e-8));
+}
+
+float lineCov(float coord, float wpp, float sp) {
+ float d = abs(mod(coord + sp * 0.5, sp) - sp * 0.5) / max(wpp, 1e-8);
+ return 1.0 - smoothstep(0.5, 1.5, d);
+}
+
+float axisCov(float coord, float wpp) {
+ return 1.0 - smoothstep(0.5, 1.5, abs(coord) / max(wpp, 1e-8));
}
vec4 over(vec4 top, vec4 bot) {
@@ -79,23 +98,39 @@ vec4 over(vec4 top, vec4 bot) {
}
void main() {
- float sp = u_gridParams.x; // minor spacing (world units)
- float major = sp * u_gridParams.y;
- float aa = u_gridParams.z; // worldPerPixel, ~1px in world units
- float lw = aa * 0.5; // ~1px line
+ // One ray for both projections: the w flags say which of the two the screen
+ // offset belongs to.
+ vec3 off = u_rayRight.xyz * v_ndc.x + u_rayUp.xyz * v_ndc.y;
+ vec3 ro = u_rayOrigin.xyz + off * u_rayOrigin.w;
+ vec3 rd = u_rayForward.xyz + off * u_rayForward.w;
+
+ vec3 n = cross(u_planeU.xyz, u_planeV.xyz);
+ float denom = dot(rd, n);
+ // Parallel meets the plane nowhere; a finite huge t leaves the fade below to
+ // remove it, where a division by zero would hand it a NaN.
+ float t = -dot(ro, n) / (abs(denom) < 1e-6 ? 1e-6 : denom);
+ vec3 hit = ro + rd * t;
- // Fade minor lines out as they crowd below a few pixels apart (anti-moiré).
- float minorFade = smoothstep(3.0, 9.0, sp / max(aa, 1e-6));
- float minorC = max(lineCov(v_world.x, sp, lw, aa), lineCov(v_world.y, sp, lw, aa)) * minorFade;
- float majorC = max(lineCov(v_world.x, major, lw, aa), lineCov(v_world.y, major, lw, aa));
- float axisXC = 1.0 - smoothstep(lw, lw + aa, abs(v_world.y)); // world y=0
- float axisYC = 1.0 - smoothstep(lw, lw + aa, abs(v_world.x)); // world x=0
+ vec2 p = vec2(dot(hit, u_planeU.xyz), dot(hit, u_planeV.xyz));
+ vec2 wpp = fwidth(p);
+
+ // Orthographic sees the plane on both sides of the eye; perspective only in front.
+ float inFront = max(step(0.0, t), 1.0 - u_rayForward.w);
+
+ float sp = u_gridParams.x;
+ float major = sp * u_gridParams.y;
+ float minorC = max(lineCov(p.x, wpp.x, sp) * fade(wpp.x, sp),
+ lineCov(p.y, wpp.y, sp) * fade(wpp.y, sp)) * inFront;
+ float majorC = max(lineCov(p.x, wpp.x, major) * fade(wpp.x, major),
+ lineCov(p.y, wpp.y, major) * fade(wpp.y, major)) * inFront;
+ float axisUC = axisCov(p.y, wpp.y) * fade(wpp.y, major) * inFront;
+ float axisVC = axisCov(p.x, wpp.x) * fade(wpp.x, major) * inFront;
vec4 c = vec4(0.0);
c = over(vec4(u_minorColor.rgb, u_minorColor.a * minorC), c);
c = over(vec4(u_majorColor.rgb, u_majorColor.a * majorC), c);
- c = over(vec4(u_axisXColor.rgb, u_axisXColor.a * axisXC), c);
- c = over(vec4(u_axisYColor.rgb, u_axisYColor.a * axisYC), c);
+ c = over(vec4(u_axisUColor.rgb, u_axisUColor.a * axisUC), c);
+ c = over(vec4(u_axisVColor.rgb, u_axisVColor.a * axisVC), c);
if (c.a <= 0.0) discard;
fragColor = c;
}
@@ -105,14 +140,13 @@ void main() {
struct VSIn { @location(0) a_position : vec2f };
struct VSOut {
@builtin(position) pos : vec4f,
- @location(0) v_world : vec2f,
+ @location(0) v_ndc : vec2f,
};
@vertex fn vs_main(v : VSIn) -> VSOut {
var out : VSOut;
- let world = mc.u_rect.xy + v.a_position * mc.u_rect.zw;
- out.v_world = world;
- out.pos = frame.projection * vec4f(world, 0.0, 1.0);
+ out.v_ndc = v.a_position;
+ out.pos = vec4f(v.a_position, 1.0, 1.0);
return out;
}
#pragma end
@@ -120,16 +154,24 @@ struct VSOut {
#pragma fragment wgsl
struct VSOut {
@builtin(position) pos : vec4f,
- @location(0) v_world : vec2f,
+ @location(0) v_ndc : vec2f,
};
// GLSL mod(): floor-based remainder (result follows the divisor's sign) — WGSL's
// % is trunc-based, which would misplace grid lines on the negative world half.
fn gmod(x : f32, y : f32) -> f32 { return x - y * floor(x / y); }
-fn lineCov(coord : f32, sp : f32, lw : f32, aa : f32) -> f32 {
- let d = abs(gmod(coord + sp * 0.5, sp) - sp * 0.5);
- return 1.0 - smoothstep(lw, lw + aa, d);
+fn fade(wpp : f32, sp : f32) -> f32 {
+ return smoothstep(3.0, 9.0, sp / max(wpp, 1e-8));
+}
+
+fn lineCov(coord : f32, wpp : f32, sp : f32) -> f32 {
+ let d = abs(gmod(coord + sp * 0.5, sp) - sp * 0.5) / max(wpp, 1e-8);
+ return 1.0 - smoothstep(0.5, 1.5, d);
+}
+
+fn axisCov(coord : f32, wpp : f32) -> f32 {
+ return 1.0 - smoothstep(0.5, 1.5, abs(coord) / max(wpp, 1e-8));
}
fn over(top : vec4f, bot : vec4f) -> vec4f {
@@ -140,22 +182,34 @@ fn over(top : vec4f, bot : vec4f) -> vec4f {
}
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let off = mc.u_rayRight.xyz * v.v_ndc.x + mc.u_rayUp.xyz * v.v_ndc.y;
+ let ro = mc.u_rayOrigin.xyz + off * mc.u_rayOrigin.w;
+ let rd = mc.u_rayForward.xyz + off * mc.u_rayForward.w;
+
+ let n = cross(mc.u_planeU.xyz, mc.u_planeV.xyz);
+ let denom = dot(rd, n);
+ let t = -dot(ro, n) / select(denom, 1e-6, abs(denom) < 1e-6);
+ let hit = ro + rd * t;
+
+ let p = vec2f(dot(hit, mc.u_planeU.xyz), dot(hit, mc.u_planeV.xyz));
+ let wpp = fwidth(p);
+
+ let inFront = max(step(0.0, t), 1.0 - mc.u_rayForward.w);
+
let sp = mc.u_gridParams.x;
let major = sp * mc.u_gridParams.y;
- let aa = mc.u_gridParams.z;
- let lw = aa * 0.5;
-
- let minorFade = smoothstep(3.0, 9.0, sp / max(aa, 1e-6));
- let minorC = max(lineCov(v.v_world.x, sp, lw, aa), lineCov(v.v_world.y, sp, lw, aa)) * minorFade;
- let majorC = max(lineCov(v.v_world.x, major, lw, aa), lineCov(v.v_world.y, major, lw, aa));
- let axisXC = 1.0 - smoothstep(lw, lw + aa, abs(v.v_world.y));
- let axisYC = 1.0 - smoothstep(lw, lw + aa, abs(v.v_world.x));
+ let minorC = max(lineCov(p.x, wpp.x, sp) * fade(wpp.x, sp),
+ lineCov(p.y, wpp.y, sp) * fade(wpp.y, sp)) * inFront;
+ let majorC = max(lineCov(p.x, wpp.x, major) * fade(wpp.x, major),
+ lineCov(p.y, wpp.y, major) * fade(wpp.y, major)) * inFront;
+ let axisUC = axisCov(p.y, wpp.y) * fade(wpp.y, major) * inFront;
+ let axisVC = axisCov(p.x, wpp.x) * fade(wpp.x, major) * inFront;
var c = vec4f(0.0, 0.0, 0.0, 0.0);
c = over(vec4f(mc.u_minorColor.rgb, mc.u_minorColor.a * minorC), c);
c = over(vec4f(mc.u_majorColor.rgb, mc.u_majorColor.a * majorC), c);
- c = over(vec4f(mc.u_axisXColor.rgb, mc.u_axisXColor.a * axisXC), c);
- c = over(vec4f(mc.u_axisYColor.rgb, mc.u_axisYColor.a * axisYC), c);
+ c = over(vec4f(mc.u_axisUColor.rgb, mc.u_axisUColor.a * axisUC), c);
+ c = over(vec4f(mc.u_axisVColor.rgb, mc.u_axisVColor.a * axisVC), c);
if (c.a <= 0.0) { discard; }
return c;
}
@@ -201,19 +255,37 @@ export function installEditorGrid(app: App): void {
if (!grid.enabled || !view.active || grid.spacing <= 0) return;
if (!ensureResources()) return;
- // The rect the camera actually sees on the z = 0 plane the quad sits on. Under
- // a perspective eye that is NOT orthoSize — reading it there left the grid a
- // bounded island floating in the middle of the viewport, since the quad was
- // sized for a projection the view is no longer using.
- const { halfW, halfH } = editorViewHalfExtent(view, width / height);
- const worldPerPixel = (2 * halfH) / height;
-
- setParam('u_rect', view.x, view.y, halfW, halfH);
- setParam('u_gridParams', grid.spacing, grid.majorEvery, worldPerPixel, 0);
- setParam('u_minorColor', grid.color[0], grid.color[1], grid.color[2], grid.color[3]);
- setParam('u_majorColor', grid.majorColor[0], grid.majorColor[1], grid.majorColor[2], grid.majorColor[3]);
- setParam('u_axisXColor', grid.axisX[0], grid.axisX[1], grid.axisX[2], grid.axisX[3]);
- setParam('u_axisYColor', grid.axisY[0], grid.axisY[1], grid.axisY[2], grid.axisY[3]);
+ const plane = editorViewWorkPlane(view);
+ const u = worldAxisVector(plane.u);
+ const v = worldAxisVector(plane.v);
+ const basis = editorViewBasis(view);
+ const eye = editorViewEye(view);
+
+ // What the view sees at the focus, which is the half-extent the screen axes
+ // span there — the reach a perspective ray turns through, and the offset an
+ // orthographic one is displaced by.
+ const halfH = editorViewHalfHeight(view);
+ const halfW = halfH * (width / height);
+ const perspective = view.perspective ? 1 : 0;
+ const reach = view.perspective ? editorViewStandoff(view) : 1;
+
+ setParam('u_planeU', u.x, u.y, u.z, 0);
+ setParam('u_planeV', v.x, v.y, v.z, 0);
+ setParam('u_rayOrigin', eye.x, eye.y, eye.z, 1 - perspective);
+ setParam('u_rayRight', basis.right.x * halfW, basis.right.y * halfW, basis.right.z * halfW, 0);
+ setParam('u_rayUp', basis.up.x * halfH, basis.up.y * halfH, basis.up.z * halfH, 0);
+ setParam('u_rayForward', basis.forward.x * reach, basis.forward.y * reach,
+ basis.forward.z * reach, perspective);
+ setParam('u_gridParams', grid.spacing, grid.majorEvery, 0, 0);
+
+ const minor = grid.color;
+ const major = grid.majorColor;
+ const axisU = grid.axisColors[plane.u];
+ const axisV = grid.axisColors[plane.v];
+ setParam('u_minorColor', minor[0], minor[1], minor[2], minor[3]);
+ setParam('u_majorColor', major[0], major[1], major[2], major[3]);
+ setParam('u_axisUColor', axisU[0], axisU[1], axisU[2], axisU[3]);
+ setParam('u_axisVColor', axisV[0], axisV[1], axisV[2], axisV[3]);
Draw.drawMeshWithMaterial(quad_, material_);
});
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 888de020e..21d45bcbd 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, editorViewAxes, editorViewAxisAngles } from './camera/EditorView';
-export type { EditorViewData, ScreenAxis } from './camera/EditorView';
+export { EditorView, DEFAULT_EDITOR_VIEW, editorViewHalfHeight, editorViewHalfExtent, setEditorViewHalfHeight, editorViewIsOrbited, editorViewAxes, editorViewAxisAngles, editorViewBasis, editorViewEye, editorViewStandoff, editorViewWorkPlane, worldAxisVector, moveEditorViewFocus, editorViewBoxExtent } from './camera/EditorView';
+export type { EditorViewData, ScreenAxis, EditorViewBasis, EditorWorkPlane, WorldAxis } 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.test.ts b/sdk/tests/editor-view.test.ts
index 6d41eca22..529cac51c 100644
--- a/sdk/tests/editor-view.test.ts
+++ b/sdk/tests/editor-view.test.ts
@@ -64,7 +64,15 @@ import {
editorViewHalfExtent,
editorViewHalfHeight,
setEditorViewHalfHeight,
+ editorViewAxes,
+ editorViewBasis,
+ editorViewBoxExtent,
+ editorViewEye,
+ editorViewWorkPlane,
+ moveEditorViewFocus,
+ worldAxisVector,
} from '../src/camera/EditorView';
+import type { Vec3 } from '../src/types';
const view = (over: Partial<typeof DEFAULT_EDITOR_VIEW>) =>
({ ...DEFAULT_EDITOR_VIEW, active: true, ...over });
@@ -182,3 +190,123 @@ describe('editorViewHalfHeight', () => {
expect(o.distance).toBe(1000);
});
});
+
+// =============================================================================
+// The view's own basis, the plane it works on, and moving the focus through
+// both. A 2D editor can assume the world plane is the screen plane; a view that
+// turns cannot, and every navigation that assumed it moved somewhere else.
+// =============================================================================
+
+const dot = (a: Vec3, b: Vec3): number => a.x * b.x + a.y * b.y + a.z * b.z;
+const len = (a: Vec3): number => Math.sqrt(dot(a, a));
+
+describe('the editor view basis', () => {
+ it('is the 2D one head-on: right +x, up +y, forward -z', () => {
+ const b = editorViewBasis(view({}));
+ expect(b.right.x).toBeCloseTo(1, 6);
+ expect(b.up.y).toBeCloseTo(1, 6);
+ expect(b.forward.z).toBeCloseTo(-1, 6);
+ });
+
+ it('stays orthonormal at every angle, poles included', () => {
+ for (const [yaw, pitch] of [[0, 0], [30, 25], [-115, 60], [0, 90], [180, -45]]) {
+ const b = editorViewBasis(view({ yaw, pitch }));
+ for (const a of [b.right, b.up, b.forward]) expect(len(a)).toBeCloseTo(1, 6);
+ expect(dot(b.right, b.up)).toBeCloseTo(0, 6);
+ expect(dot(b.right, b.forward)).toBeCloseTo(0, 6);
+ expect(dot(b.up, b.forward)).toBeCloseTo(0, 6);
+ }
+ });
+
+ // Two readings of one rotation. A second copy is how the axis ball and the
+ // thing it claims to describe drift apart.
+ it('agrees with the axis indicator', () => {
+ const v = view({ yaw: 37, pitch: 21 });
+ const b = editorViewBasis(v);
+ const axes = editorViewAxes(v);
+ expect(axes.x.dx).toBeCloseTo(b.right.x, 6);
+ expect(axes.x.dy).toBeCloseTo(-b.up.x, 6);
+ expect(axes.y.dx).toBeCloseTo(b.right.y, 6);
+ expect(axes.z.depth).toBeCloseTo(-b.forward.z, 6);
+ });
+
+ it('stands the eye off the focus by the distance, in every direction', () => {
+ const flat = editorViewEye(view({ x: 3, y: 4 }));
+ expect(flat.z).toBeCloseTo(0, 6); // head-on 2D: nothing depends on where it stands
+
+ expect(editorViewEye(view({ perspective: true, distance: 1000 })).z).toBeCloseTo(1000, 4);
+
+ const focus = { x: 10, y: 20, z: 30 };
+ const e = editorViewEye(view({ ...focus, yaw: 47, pitch: 33, distance: 500 }));
+ expect(Math.hypot(e.x - focus.x, e.y - focus.y, e.z - focus.z)).toBeCloseTo(500, 4);
+ });
+});
+
+describe('the work plane', () => {
+ it('is the plane 2D content lives on while the view is the 2D one', () => {
+ const p = editorViewWorkPlane(view({}));
+ expect(worldAxisVector(p.normal)).toEqual({ x: 0, y: 0, z: 1 });
+ });
+
+ it('is the ground once the view is a 3D one', () => {
+ const p = editorViewWorkPlane(view({ perspective: true }));
+ expect(worldAxisVector(p.normal)).toEqual({ x: 0, y: 1, z: 0 });
+ expect(new Set([p.u, p.v, p.normal]).size).toBe(3);
+ });
+});
+
+describe('moving the focus', () => {
+ it('is world x / y head-on, which is the 2D editor exactly as it was', () => {
+ const v = view({ x: 5, y: 7 });
+ moveEditorViewFocus(v, 10, 20);
+ expect(v.x).toBeCloseTo(15, 6);
+ expect(v.y).toBeCloseTo(27, 6);
+ expect(v.z).toBeCloseTo(0, 6);
+ });
+
+ // Looking straight down, the screen's up runs along the floor. A pan that took
+ // the world y axis instead would fly the focus up out of the scene.
+ it('walks over the ground from a top-down eye, not through it', () => {
+ const v = view({ perspective: true, distance: 1000, pitch: 90 });
+ moveEditorViewFocus(v, 0, 100);
+ expect(v.y).toBeCloseTo(0, 6);
+ expect(Math.hypot(v.x, v.z)).toBeCloseTo(100, 6);
+ });
+
+ it('dollies along forward, which is the only way depth moves head-on', () => {
+ const v = view({});
+ moveEditorViewFocus(v, 0, 0, 250);
+ expect(v.z).toBeCloseTo(-250, 6);
+ });
+});
+
+describe('fitting a box in the frame', () => {
+ it('costs nothing for the depth an eye is looking along', () => {
+ const e = editorViewBoxExtent(view({}), { x: 30, y: 40, z: 500 });
+ expect(e.right).toBeCloseTo(30, 6);
+ expect(e.up).toBeCloseTo(40, 6);
+ });
+
+ it('turns depth into screen width once the eye is turned onto it', () => {
+ const e = editorViewBoxExtent(view({ yaw: 90 }), { x: 0, y: 0, z: 500 });
+ expect(e.right).toBeCloseTo(500, 4);
+ expect(e.up).toBeCloseTo(0, 6);
+ });
+});
+
+describe('the focus the view turns around', () => {
+ // The focus is the centre of the frame by definition. It was pinned to z = 0,
+ // so an orbit of a 3D scene swung around a plane the content was not on.
+ it('is the centre of the frame at any depth', () => {
+ const v = view({ x: 100, y: 50, z: -400, perspective: true, distance: 1000, yaw: 30, pitch: 25 });
+ const cam = editorCameraInfo(v, 800, 600, []);
+
+ const focus = ndc3(cam.viewProjection, 100, 50, -400);
+ expect(focus.x).toBeCloseTo(0, 5);
+ expect(focus.y).toBeCloseTo(0, 5);
+
+ // ...and the same x/y on the 2D plane is not, or the depth reached nothing.
+ const onPlane = ndc3(cam.viewProjection, 100, 50, 0);
+ expect(Math.abs(onPlane.x) + Math.abs(onPlane.y)).toBeGreaterThan(0.05);
+ });
+});
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index f26fc9312..6742b6bd2 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -38,6 +38,8 @@ export const SCENES = [
{ id: "sprite-default", tier: "pr", webgpu: true, env: { } },
// Editor grid on/off pixel diff — guards the custom-draw reflected material path (drawMeshWithMaterial + MaterialConstants UBO).
{ id: "editor-grid", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_GRID: "64", ESTELLA_VERIFY_STEPS: "3" } },
+ // The same grid from straight above a 3D view. It stands on the ground there, so it fills the frame; the 2D plane would be edge-on and light one band.
+ { id: "editor-grid-3d", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-instanced.esscene", ESTELLA_VERIFY_GRID: "64", ESTELLA_VERIFY_PERSPECTIVE: "1", ESTELLA_VERIFY_ORBIT: "0,90", ESTELLA_VERIFY_STEPS: "3" } },
{ id: "mesh2d", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh2d.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh2d.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.30,\"y\":0.556,\"rgb\":[255,0,0],\"tol\":40},{\"x\":0.70,\"y\":0.556,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.30,\"y\":0.40,\"rgb\":[255,0,0],\"tol\":40}]" } },
{ id: "parallax-shape", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/parallax-shape.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/parallax-shape.textures.json", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.25,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":40}]" } },
{ id: "tilemap-flip", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/tilemap-flip.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/tilemap-flip.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.40,\"y\":0.36,\"rgb\":[255,0,0]},{\"x\":0.60,\"y\":0.36,\"rgb\":[0,255,0]},{\"x\":0.40,\"y\":0.58,\"rgb\":[0,0,255]},{\"x\":0.60,\"y\":0.58,\"rgb\":[255,255,0]}]" } },