Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(editor): a size and a direction, each in the unit its question is asked in

esenginea59134b7b011
diff --git a/desktop/scripts/editor-checks/icon-pick.mjs b/desktop/scripts/editor-checks/icon-pick.mjs
new file mode 100644
index 000000000..2ff3548b6
--- /dev/null
+++ b/desktop/scripts/editor-checks/icon-pick.mjs
@@ -0,0 +1,115 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file icon-pick — clicking the icon an entity is drawn as selects it.
+ *
+ * A camera, a light and an empty draw nothing of their own; the editor draws an
+ * icon for them, and that icon is a fixed number of pixels wherever it stands. The
+ * box a click hits has to be the same size, and a world size can only match it at
+ * one zoom.
+ *
+ * The project is framed on a very large design rect, so the world is many units per
+ * pixel — where a world-sized target has shrunk to under a pixel while the icon on
+ * screen has not moved. The icon locates itself: the camera is at the origin and
+ * its gizmo is the only thing the gizmo toggle paints, so that ink's centre is where
+ * the camera projects.
+ */
+import { cp } from 'node:fs/promises';
+import path from 'node:path';
+import { makeProject, checker, DESKTOP } from '../lib/editorDriver.mjs';
+
+const EXAMPLE = path.resolve(DESKTOP, '..', 'examples', 'sprite-rendering');
+
+/** A design rect big enough that one pixel is tens of world units once framed. */
+const PROJECT = JSON.stringify({
+ formatVersion: '1',
+ name: 'Icon Pick',
+ defaultScene: 'assets/scenes/main.esscene',
+ designResolution: { width: 16000, height: 12000 },
+ spineVersion: 'none',
+}, null, 2);
+
+const SCENE = JSON.stringify({
+ version: '1.0', name: 'Main',
+ entities: [
+ {
+ id: 0, name: 'Camera', parent: null, children: [], visible: true,
+ components: [
+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 10 } } },
+ { type: 'Camera', data: { projectionType: 1, orthoSize: 300, isActive: true, priority: 0 } },
+ ],
+ },
+ ],
+}, null, 1);
+
+export const name = 'icon-pick';
+export const describes = 'an entity drawn as an icon is clickable where the icon is';
+
+/**
+ * Where the grid's coloured axis lines are, which is where the world origin projects
+ * — independent of what the editor draws over it. They are blended at 55% over an
+ * unknown background, so the ARGMAX identifies the line rather than any exact value.
+ */
+function axisAt(png, rgb, vertical, region) {
+ const tally = new Array(vertical ? png.w : png.h).fill(0);
+ for (let y = region.y0; y < region.y1; y++) {
+ for (let x = region.x0; x < region.x1; x++) {
+ const p = png.px(x, y);
+ // The line is the channel ORDER, not the exact value: alpha over an unknown
+ // background moves every channel but keeps which one leads.
+ const lead = p[0] > p[1] && p[0] > p[2];
+ const isGreen = p[1] > p[0] && p[1] > p[2];
+ if ((rgb === 'red' && lead && p[0] > 60) || (rgb === 'green' && isGreen && p[1] > 60)) {
+ tally[vertical ? x : y] += 1;
+ }
+ }
+ }
+ let best = -1;
+ let at = -1;
+ tally.forEach((n, i) => { if (n > best) { best = n; at = i; } });
+ return best > 20 ? at : -1;
+}
+
+export async function run(ed) {
+ const root = await makeProject({
+ 'assets/scenes/main.esscene': SCENE,
+ 'project.esproject': PROJECT,
+ });
+ await cp(path.join(EXAMPLE, 'src'), path.join(root, 'src'), { recursive: true });
+ const check = checker();
+ await ed.open(root, 'assets/scenes/main.esscene');
+ // Scene mode: the design overlay belongs to UI mode, and the editor remembers
+ // the mode across sessions — with it on, its frame is the ink the toggle paints.
+ await ed.call('run_editor_command', { id: 'mode.scene' }, 30000);
+ await ed.call('run_editor_command', { id: 'tool.select' }, 30000);
+ await ed.call('select', { id: null }, 30000);
+ await ed.sleep(800);
+
+ const shot = await ed.screenshot('icon-pick');
+ // The viewport, roughly — enough to keep the panels' own colours out of the tally.
+ const region = { x0: Math.round(shot.w * 0.25), x1: Math.round(shot.w * 0.72),
+ y0: Math.round(shot.h * 0.16), y1: Math.round(shot.h * 0.62) };
+ const cx = axisAt(shot, 'green', true, region);
+ const cy = axisAt(shot, 'red', false, region);
+ if (!check(cx > 0 && cy > 0, `the grid's axis lines were not found (x=${cx}, y=${cy})`)) {
+ return check.failures;
+ }
+
+ const at = async (dx, dy) => ed.json('pick', { clientX: cx + dx, clientY: cy + dy }, 30000);
+ const centre = await at(0, 0);
+ if (!check(centre === 0, `a click on the icon picked ${JSON.stringify(centre)}, not the camera`)) {
+ return check.failures;
+ }
+
+ // How far from the icon a click still selects it. The icon is drawn 15px across,
+ // so its target is about that; a world-sized one at this zoom is under a pixel.
+ let reach = 0;
+ while (reach < 40 && (await at(reach + 1, 0)) === 0) reach += 1;
+ check(
+ reach >= 6 && reach <= 20,
+ `a click selects the camera up to ${reach}px from its icon, which is drawn 15px across — `
+ + 'the target is not the size of the thing it is a target for',
+ );
+
+ return check.failures;
+}
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index 5def20fbc..f051cf242 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -14,12 +14,12 @@ import {
BoxCollider3D, SphereCollider3D, CapsuleCollider3D, MeshCollider3D, CharacterController3D,
readCollider3DShapes, collider3DWireframe, placeCollider3DWireframe,
readJoint3D, rotateVec3ByQuat,
- editorViewHalfHeight, editorViewHalfExtent, setEditorViewHalfHeight, EDITOR_UI_ANCHOR,
+ editorViewHalfHeight, editorViewHalfExtent, editorViewWorldPerPixel, setEditorViewHalfHeight, EDITOR_UI_ANCHOR,
entityWorldBox, uiNodeWorldBox, meshWorldBox, entityBoxCorners, type EntityBox,
pickEntitiesByRay, editorViewIsOrbited,
moveEditorViewFocus, editorViewBoxExtent,
editorViewAxes, editorViewAxisAngles, editorViewBasis, cameraFrustumCorners, type ScreenAxis,
- editorViewWorkPlane, screenNudgeAxes, worldAxisVector, DEFAULT_EDITOR_VIEW, type WorldAxis,
+ editorViewWorkPlane, screenWorkAxes, worldAxisVector, DEFAULT_EDITOR_VIEW, type WorldAxis,
lightAimOf,
rayPlaneHit, type WorldRay, type Vec3,
type TilesetModel, type TileCollisionPiece, type TileGridParams,
@@ -42,9 +42,11 @@ import {
// Half-length of a 3D joint's axis marker, in world units — long enough to read
// against a body, short enough not to look like the link itself.
const JOINT3D_AXIS_WORLD_HALF = 60;
-// World half-size of the pick/outline box for entities without renderable bounds
-// (cameras, lights, empties) — so they're click-selectable like any sprite.
-const ICON_WORLD_HALF = 24;
+// The box for an entity that draws nothing of its own — a camera, a light, an empty.
+// A CLICK has to hit the icon that was drawn, which is CSS pixels wherever it stands.
+const ICON_PICK_SCREEN_HALF = 11;
+// The room a MAP, or "Frame", gives such a marker: world units, fixed under zoom.
+const ICON_MAP_WORLD_HALF = 24;
// Degrees of turn per pixel dragged — the rate a DCC's orbit uses.
// How square-on the work plane has to be before a screen point names a place on it
// rather than a mile of it. ~6°, below which one pixel of cursor is unbounded world.
@@ -263,7 +265,7 @@ export const ViewportController = {
nudgeVector(right: number, up: number): Vec3 {
const view = editorView();
if (!view) return { x: right, y: up, z: 0 };
- const n = screenNudgeAxes(view);
+ const n = screenWorkAxes(view);
const out = { x: 0, y: 0, z: 0 };
for (const [a, amount] of [[n.right, right], [n.up, up]] as const) {
const v = worldAxisVector(a.axis);
@@ -274,6 +276,33 @@ export const ViewportController = {
return out;
},
+ /**
+ * A world point in the work plane's two axes, as the SCREEN names them — right
+ * across, up the screen. What a gesture spelt in those words (align left, nudge
+ * up, distribute across) measures in, and head-on it is world x and y.
+ */
+ worldToPlanePoint(at: Vec3): { u: number; v: number } {
+ const view = editorView();
+ if (!view) return { u: at.x, v: at.y };
+ const n = screenWorkAxes(view);
+ return { u: axisOf(at, n.right.axis) * n.right.sign, v: axisOf(at, n.up.axis) * n.up.sign };
+ },
+
+ /**
+ * The inverse: `at` with its two plane components replaced. The third is carried
+ * through, because a gesture on a plane says nothing about the axis across it.
+ */
+ planePointToWorld(at: Vec3, u: number, v: number): Vec3 {
+ const view = editorView();
+ if (!view) return { x: u, y: v, z: at.z };
+ const n = screenWorkAxes(view);
+ const out = { x: at.x, y: at.y, z: at.z };
+ const key = (['x', 'y', 'z'] as const);
+ out[key[n.right.axis]!] = u * n.right.sign;
+ out[key[n.up.axis]!] = v * n.up.sign;
+ return out;
+ },
+
/** The two world axes the view's work plane runs in, as their letters — what a
* coordinate readout on that plane is naming. */
workPlaneAxes(): [string, string] {
@@ -359,17 +388,27 @@ export const ViewportController = {
* (= transform position). Reads the parent-composed world transform — the same
* fields the renderer draws from — so parented entities pick where they render.
*/
- entityBounds(id: EntityId): EntityBox | null {
+ entityBounds(id: EntityId, iconHalf?: number | ((at: Vec3) => number)): EntityBox | null {
const world = EngineHost.world;
if (!world) return null;
// A mesh's extent is in its vertices, so it is asked for before the icon
// fallback below would answer with a box the size of a camera gizmo.
const mesh = meshWorldBox(world, id);
if (mesh) return mesh;
- // The icon half-size is the editor's own: it is the size of the thing the
- // editor drew for an entity that draws nothing, so a camera is still
- // clickable. The running world has no icons and asks for no box.
- return entityWorldBox(world, id, { iconHalf: ICON_WORLD_HALF });
+ // The icon half-size is the editor's own — the running world draws no icons
+ // and asks for no box. Which size it is depends on what the caller is asking.
+ return entityWorldBox(world, id, { iconHalf: iconHalf ?? this.iconPickHalf() });
+ },
+
+ /** The world half-size an icon covers where it stands, for the zoom it is drawn
+ * at — what a click has to hit. */
+ iconPickHalf(): (at: Vec3) => number {
+ const view = editorView();
+ const canvas = EngineHost.canvas;
+ const dpr = window.devicePixelRatio || 1;
+ const heightPx = canvas ? canvas.height / dpr : 0;
+ if (!view || heightPx <= 0) return () => ICON_MAP_WORLD_HALF;
+ return (at) => ICON_PICK_SCREEN_HALF * editorViewWorldPerPixel(view, heightPx, at);
},
/**
@@ -442,7 +481,7 @@ export const ViewportController = {
if (world && ray) {
const masks = projectSortingLayerModes();
for (const e of pickEntitiesByRay(world, ray, {
- iconHalf: ICON_WORLD_HALF,
+ iconHalf: this.iconPickHalf(),
// Locked / editor-hidden / environment entities aren't click-selectable.
pickable: (e) => {
const src = SceneModel.sourceFor(e as EntityId);
@@ -709,7 +748,7 @@ export const ViewportController = {
let maxY = -Infinity;
let maxZ = -Infinity;
for (const id of ids) {
- const b = this.entityBounds(id) ?? this.uiEntityWorldOBB(id);
+ const b = this.entityBounds(id, ICON_MAP_WORLD_HALF) ?? this.uiEntityWorldOBB(id);
if (!b) continue;
for (const c of entityBoxCorners(b)) {
minX = Math.min(minX, c.x);
@@ -862,7 +901,7 @@ export const ViewportController = {
continue;
}
}
- const b = this.entityBounds(e);
+ const b = this.entityBounds(e, ICON_MAP_WORLD_HALF);
if (!b) continue;
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
for (const c of entityBoxCorners(b)) {
diff --git a/desktop/src/tools/alignTools.ts b/desktop/src/tools/alignTools.ts
index dc2fc1aa3..a5a8da1a0 100644
--- a/desktop/src/tools/alignTools.ts
+++ b/desktop/src/tools/alignTools.ts
@@ -19,34 +19,53 @@ import { pruneDescendants, isFlowUINode, isOrphanUINode } from './transformTools
import { alignTargets, distributeTargets, type AlignBox, type AlignOp, type DistributeAxis } from './alignMath';
import type { EntityId } from '@/types';
-/** Positionable selection → each entity's world AABB. Excludes flex-flow / orphan
- * UI nodes (setEntityWorldPos can't move them) and descendants of a selected ancestor
- * (already carried by their parent's move). */
-function collectBoxes(): Array<{ sid: EntityId; box: AlignBox }> {
+/** One target of an align gesture: where it is, and the box it presents. Boxes are
+ * measured in the work plane's two axes as the SCREEN names them, so "left" and
+ * "top" mean what they say from any eye — head-on that is world x and y. */
+interface AlignTarget {
+ sid: EntityId;
+ at: { x: number; y: number; z: number };
+ box: AlignBox;
+}
+
+/** Positionable selection → each entity's box on the work plane. Excludes flex-flow /
+ * orphan UI nodes (setEntityWorldPos can't move them) and descendants of a selected
+ * ancestor (already carried by their parent's move). */
+function collectBoxes(): AlignTarget[] {
const ids = pruneDescendants([...useSelection.getState().selectedIds]).filter(
(sid) => !isFlowUINode(sid) && !isOrphanUINode(sid),
);
- const out: Array<{ sid: EntityId; box: AlignBox }> = [];
+ const out: AlignTarget[] = [];
for (const sid of ids) {
const rt = SceneModel.runtimeFor(sid);
if (rt == null) continue;
const obb = ViewportController.entityBounds(rt) ?? ViewportController.uiEntityWorldOBB(rt);
- if (!obb) continue;
- const corners = entityBoxCorners(obb);
- const xs = corners.map((c) => c.x);
- const ys = corners.map((c) => c.y);
+ const at = rt != null ? ViewportController.getEntityWorldPos(rt) : null;
+ if (!obb || !at) continue;
+ const uv = entityBoxCorners(obb).map((c) => ViewportController.worldToPlanePoint(c));
+ const us = uv.map((p) => p.u);
+ const vs = uv.map((p) => p.v);
+ const origin = ViewportController.worldToPlanePoint({ x: obb.cx, y: obb.cy, z: obb.cz });
out.push({
sid,
- box: { minX: Math.min(...xs), maxX: Math.max(...xs), minY: Math.min(...ys), maxY: Math.max(...ys), cx: obb.cx, cy: obb.cy },
+ at,
+ box: {
+ minX: Math.min(...us), maxX: Math.max(...us),
+ minY: Math.min(...vs), maxY: Math.max(...vs),
+ cx: origin.u, cy: origin.v,
+ },
});
}
return out;
}
-function apply(boxes: Array<{ sid: EntityId; box: AlignBox }>, targets: Array<{ cx: number; cy: number }>, label: string): void {
+function apply(targets: AlignTarget[], moved: Array<{ cx: number; cy: number }>, label: string): void {
SceneCommands.beginGesture(label);
try {
- boxes.forEach((b, i) => SceneCommands.setEntityWorldPos(b.sid, targets[i].cx, targets[i].cy));
+ targets.forEach((t, i) => {
+ const p = ViewportController.planePointToWorld(t.at, moved[i].cx, moved[i].cy);
+ SceneCommands.setEntityWorldPos(t.sid, p.x, p.y, p.z);
+ });
} finally {
SceneCommands.endGesture();
}
diff --git a/desktop/tests/viewport-navigation.test.ts b/desktop/tests/viewport-navigation.test.ts
index 2dbe6be23..938b3305a 100644
--- a/desktop/tests/viewport-navigation.test.ts
+++ b/desktop/tests/viewport-navigation.test.ts
@@ -10,7 +10,7 @@
* would say so.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { DEFAULT_EDITOR_VIEW, editorViewHalfExtent, type EditorViewData } from 'esengine';
+import { DEFAULT_EDITOR_VIEW, editorViewHalfExtent, editorViewWorldPerPixel, type EditorViewData } from 'esengine';
const host = vi.hoisted(() => ({
view: null as EditorViewData | null,
@@ -225,3 +225,52 @@ describe('the minimap plots the plane the view works on', () => {
expect(v.y).toBeCloseTo(1, 6);
});
});
+
+describe('world units per screen pixel', () => {
+ it('is the seen height over the pixel height, orthographically the same everywhere', () => {
+ const v = view({ orthoSize: 300 });
+ expect(editorViewWorldPerPixel(v, 600)).toBeCloseTo(1, 9);
+ // Depth cannot change it: an orthographic screen point's scale is constant.
+ expect(editorViewWorldPerPixel(v, 600, { x: 0, y: 0, z: -5000 })).toBeCloseTo(1, 9);
+ });
+
+ // In perspective it is the distance ALONG the view axis that the projection
+ // divides by, so a thing twice as far covers twice the world per pixel.
+ it('grows with the distance along the view axis in perspective', () => {
+ const v = perspectiveView({});
+ const standoff = v.distance;
+ expect(editorViewWorldPerPixel(v, 600, { x: 0, y: 0, z: 0 })).toBeCloseTo(1, 6);
+ expect(editorViewWorldPerPixel(v, 600, { x: 0, y: 0, z: -standoff })).toBeCloseTo(2, 6);
+ });
+
+ it('behind the eye reports the focus scale rather than a negative one', () => {
+ const v = perspectiveView({});
+ expect(editorViewWorldPerPixel(v, 600, { x: 0, y: 0, z: v.distance * 2 })).toBeCloseTo(1, 6);
+ });
+});
+
+describe('the plane a gesture is spelt on', () => {
+ it('head-on it is world x and y, and round-trips', () => {
+ host.view = view({});
+ expect(ViewportController.worldToPlanePoint({ x: 3, y: 4, z: 5 })).toEqual({ u: 3, v: 4 });
+ expect(ViewportController.planePointToWorld({ x: 3, y: 4, z: 5 }, 10, 20))
+ .toEqual({ x: 10, y: 20, z: 5 });
+ });
+
+ // Looking down at the ground, "up the screen" is −Z; the axis the plane is across
+ // (here y, the height) is carried through untouched, because "align left" is not
+ // an instruction about height.
+ it('over the ground it is x and −z, and leaves the third axis alone', () => {
+ host.view = perspectiveView({ pitch: 90 });
+ expect(ViewportController.worldToPlanePoint({ x: 3, y: 4, z: 5 })).toEqual({ u: 3, v: -5 });
+ expect(ViewportController.planePointToWorld({ x: 3, y: 4, z: 5 }, 10, 20))
+ .toEqual({ x: 10, y: 4, z: -20 });
+ });
+
+ it('is its own inverse, over the ground', () => {
+ host.view = perspectiveView({ yaw: 35, pitch: 40 });
+ const p = { x: -12, y: 7, z: 31 };
+ const uv = ViewportController.worldToPlanePoint(p);
+ expect(ViewportController.planePointToWorld(p, uv.u, uv.v)).toEqual(p);
+ });
+});
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index b4ffe6cdd..02526f3cb 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": 1592,
+ "experimental": 1593,
"deprecated": 3
},
- "total": 1778,
+ "total": 1779,
"subsystems": [
{
"id": "ecs",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 7bacd0ab4..06cb510a3 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 · 1478 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1479 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2900,7 +2900,7 @@ rot: Quat
## EntityBoxOptions — interface @experimental
```
-iconHalf: number | undefined
+iconHalf: number | ((at: Vec3) => number) | undefined
```
## EntityCommands — class @public
@@ -2953,7 +2953,7 @@ ResourceDef<EntityEventQueue>
## EntityPickOptions — interface @experimental
```
depthLayers: number | undefined
-iconHalf: number | undefined
+iconHalf: number | ((at: Vec3) => number) | undefined
pickable: ((entity: Entity) => boolean) | undefined
ySortLayers: number | undefined
```
@@ -9971,6 +9971,11 @@ DragPlugin
(view: EditorViewData): EditorWorkPlane
```
+## editorViewWorldPerPixel — function @experimental
+```
+(view: EditorViewData, heightPx: number, at?: Vec3): number
+```
+
## emptyAnimatorController — function @experimental
```
(): AnimatorControllerDef
@@ -11511,11 +11516,6 @@ Plugin
(name: string): string
```
-## screenNudgeAxes — function @experimental
-```
-(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
-```
-
## screenRay — function @experimental
```
(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): WorldRay
@@ -11531,6 +11531,11 @@ Plugin
(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number, planeZ?: number): { x: number; y: number; }
```
+## screenWorkAxes — function @experimental
+```
+(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
+```
+
## selectBlendClip — function @experimental
```
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 61a455649..188110e6c 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 · 1497 experimental · 3 deprecated
+Symbols: 113 public · 71 beta · 1498 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2908,7 +2908,7 @@ rot: Quat
## EntityBoxOptions — interface @experimental
```
-iconHalf: number | undefined
+iconHalf: number | ((at: Vec3) => number) | undefined
```
## EntityCommands — class @public
@@ -2961,7 +2961,7 @@ ResourceDef<EntityEventQueue>
## EntityPickOptions — interface @experimental
```
depthLayers: number | undefined
-iconHalf: number | undefined
+iconHalf: number | ((at: Vec3) => number) | undefined
pickable: ((entity: Entity) => boolean) | undefined
ySortLayers: number | undefined
```
@@ -10204,6 +10204,11 @@ DragPlugin
(view: EditorViewData): EditorWorkPlane
```
+## editorViewWorldPerPixel — function @experimental
+```
+(view: EditorViewData, heightPx: number, at?: Vec3): number
+```
+
## emptyAnimatorController — function @experimental
```
(): AnimatorControllerDef
@@ -11754,11 +11759,6 @@ Plugin
(name: string): string
```
-## screenNudgeAxes — function @experimental
-```
-(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
-```
-
## screenRay — function @experimental
```
(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): WorldRay
@@ -11774,6 +11774,11 @@ Plugin
(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number, planeZ?: number): { x: number; y: number; }
```
+## screenWorkAxes — function @experimental
+```
+(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
+```
+
## selectBlendClip — function @experimental
```
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 43bb96460..1240f97cd 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 · 1477 experimental · 3 deprecated
+Symbols: 113 public · 68 beta · 1478 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2895,7 +2895,7 @@ rot: Quat
## EntityBoxOptions — interface @experimental
```
-iconHalf: number | undefined
+iconHalf: number | ((at: Vec3) => number) | undefined
```
## EntityCommands — class @public
@@ -2948,7 +2948,7 @@ ResourceDef<EntityEventQueue>
## EntityPickOptions — interface @experimental
```
depthLayers: number | undefined
-iconHalf: number | undefined
+iconHalf: number | ((at: Vec3) => number) | undefined
pickable: ((entity: Entity) => boolean) | undefined
ySortLayers: number | undefined
```
@@ -9966,6 +9966,11 @@ DragPlugin
(view: EditorViewData): EditorWorkPlane
```
+## editorViewWorldPerPixel — function @experimental
+```
+(view: EditorViewData, heightPx: number, at?: Vec3): number
+```
+
## emptyAnimatorController — function @experimental
```
(): AnimatorControllerDef
@@ -11516,11 +11521,6 @@ Plugin
(name: string): string
```
-## screenNudgeAxes — function @experimental
-```
-(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
-```
-
## screenRay — function @experimental
```
(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): WorldRay
@@ -11536,6 +11536,11 @@ Plugin
(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number, planeZ?: number): { x: number; y: number; }
```
+## screenWorkAxes — function @experimental
+```
+(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
+```
+
## selectBlendClip — function @experimental
```
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index f9a3587f2..46a11734f 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 · 1498 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1499 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2895,7 +2895,7 @@ rot: Quat
## EntityBoxOptions — interface @experimental
```
-iconHalf: number | undefined
+iconHalf: number | ((at: Vec3) => number) | undefined
```
## EntityCommands — class @public
@@ -2948,7 +2948,7 @@ ResourceDef<EntityEventQueue>
## EntityPickOptions — interface @experimental
```
depthLayers: number | undefined
-iconHalf: number | undefined
+iconHalf: number | ((at: Vec3) => number) | undefined
pickable: ((entity: Entity) => boolean) | undefined
ySortLayers: number | undefined
```
@@ -10216,6 +10216,11 @@ DragPlugin
(view: EditorViewData): EditorWorkPlane
```
+## editorViewWorldPerPixel — function @experimental
+```
+(view: EditorViewData, heightPx: number, at?: Vec3): number
+```
+
## emptyAnimatorController — function @experimental
```
(): AnimatorControllerDef
@@ -11766,11 +11771,6 @@ Plugin
(name: string): string
```
-## screenNudgeAxes — function @experimental
-```
-(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
-```
-
## screenRay — function @experimental
```
(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): WorldRay
@@ -11786,6 +11786,11 @@ Plugin
(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number, planeZ?: number): { x: number; y: number; }
```
+## screenWorkAxes — function @experimental
+```
+(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
+```
+
## selectBlendClip — function @experimental
```
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index a635ec9f4..daaf87f2e 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 · 1488 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1489 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2895,7 +2895,7 @@ rot: Quat
## EntityBoxOptions — interface @experimental
```
-iconHalf: number | undefined
+iconHalf: number | ((at: Vec3) => number) | undefined
```
## EntityCommands — class @public
@@ -2948,7 +2948,7 @@ ResourceDef<EntityEventQueue>
## EntityPickOptions — interface @experimental
```
depthLayers: number | undefined
-iconHalf: number | undefined
+iconHalf: number | ((at: Vec3) => number) | undefined
pickable: ((entity: Entity) => boolean) | undefined
ySortLayers: number | undefined
```
@@ -9993,6 +9993,11 @@ DragPlugin
(view: EditorViewData): EditorWorkPlane
```
+## editorViewWorldPerPixel — function @experimental
+```
+(view: EditorViewData, heightPx: number, at?: Vec3): number
+```
+
## emptyAnimatorController — function @experimental
```
(): AnimatorControllerDef
@@ -11538,11 +11543,6 @@ Plugin
(name: string): string
```
-## screenNudgeAxes — function @experimental
-```
-(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
-```
-
## screenRay — function @experimental
```
(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): WorldRay
@@ -11558,6 +11558,11 @@ Plugin
(screenX: number, screenY: number, inverseVP: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number, planeZ?: number): { x: number; y: number; }
```
+## screenWorkAxes — function @experimental
+```
+(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }
+```
+
## selectBlendClip — function @experimental
```
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
diff --git a/sdk/src/camera/EditorView.ts b/sdk/src/camera/EditorView.ts
index e8422f4d2..b397c7575 100644
--- a/sdk/src/camera/EditorView.ts
+++ b/sdk/src/camera/EditorView.ts
@@ -100,6 +100,26 @@ export function editorViewHalfExtent(
return { halfW: halfH * (aspect > 0 ? aspect : 1), halfH };
}
+/**
+ * World units per screen pixel at @p at — what a thing drawn at a fixed number of
+ * pixels measures in the world where it stands. Orthographically the same
+ * everywhere; in perspective it grows with the distance along the view axis, which
+ * is the axis the projection divides by. Without @p at, the focus answers.
+ */
+export function editorViewWorldPerPixel(
+ view: EditorViewData, heightPx: number, at?: Vec3,
+): number {
+ const base = heightPx > 0 ? (2 * editorViewHalfHeight(view)) / heightPx : 0;
+ const standoff = editorViewStandoff(view);
+ if (!view.perspective || !at || standoff <= 0) return base;
+ const eye = editorViewEye(view);
+ const f = editorViewBasis(view).forward;
+ const along = (at.x - eye.x) * f.x + (at.y - eye.y) * f.y + (at.z - eye.z) * f.z;
+ // Behind the eye there is no size to report; the focus's own scale is the
+ // nearest honest answer and keeps a marker there clickable rather than infinite.
+ return along > 0 ? base * (along / standoff) : base;
+}
+
/**
* Zoom the view until it sees @p halfH world units of height, writing whichever
* field this projection zooms with. The inverse of {@link editorViewHalfHeight},
@@ -260,10 +280,11 @@ const PLANE_SEEN_MIN = 0.1;
/**
* The work-plane axis a screen direction names, with the sign pointing that way —
- * what an arrow key nudges along. `right` resolves first and `up` takes the plane's
- * other axis, so the pair is never one axis twice. Head-on: +X right, +Y up.
+ * what "right" and "up" mean for a gesture on that plane. `right` resolves first
+ * and `up` takes the plane's other axis, so the pair is never one axis twice.
+ * Head-on: +X right, +Y up.
*/
-export function screenNudgeAxes(
+export function screenWorkAxes(
view: EditorViewData,
): { right: { axis: WorldAxis; sign: number }; up: { axis: WorldAxis; sign: number } } {
const plane = editorViewWorkPlane(view);
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 7d57873ef..212a2b629 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -42,7 +42,7 @@ export { TextureFilter, TextureWrap, setTextureFilter, setTextureWrap, setTextur
// =============================================================================
export { CameraView, CameraViewAPI } from './camera/Camera';
-export { EditorView, DEFAULT_EDITOR_VIEW, editorViewHalfHeight, editorViewHalfExtent, setEditorViewHalfHeight, editorViewIsOrbited, editorViewAxes, editorViewAxisAngles, editorViewBasis, editorViewEye, editorViewStandoff, editorViewWorkPlane, screenNudgeAxes, worldAxisVector, moveEditorViewFocus, editorViewBoxExtent } from './camera/EditorView';
+export { EditorView, DEFAULT_EDITOR_VIEW, editorViewHalfHeight, editorViewHalfExtent, editorViewWorldPerPixel, setEditorViewHalfHeight, editorViewIsOrbited, editorViewAxes, editorViewAxisAngles, editorViewBasis, editorViewEye, editorViewStandoff, editorViewWorkPlane, screenWorkAxes, 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';
diff --git a/sdk/src/ecs/entityBox.ts b/sdk/src/ecs/entityBox.ts
index 6f2fe81ff..00b5ea1db 100644
--- a/sdk/src/ecs/entityBox.ts
+++ b/sdk/src/ecs/entityBox.ts
@@ -49,8 +49,12 @@ export interface EntityBoxOptions {
* World half-size for an entity that draws nothing of its own — a camera, a
* light, an empty. Zero (the default) reports no box for those; an editor
* that wants them clickable passes the size of the icon it drew.
+ *
+ * A function when that size is not a world size: an icon drawn at a fixed
+ * number of PIXELS covers a world extent that depends on where it is, and the
+ * caller is handed the entity's world position to answer for it.
*/
- iconHalf?: number;
+ iconHalf?: number | ((at: Vec3) => number);
}
/** The rotation an entity is drawn with, defaulted for a partial write. */
@@ -75,7 +79,8 @@ export function entityWorldBox(world: ReadableWorld, entity: Entity, opts?: Enti
const t = world.get(entity, Transform);
const rot = worldRot(t);
- const iconHalf = opts?.iconHalf ?? 0;
+ const spec = opts?.iconHalf ?? 0;
+ const iconHalf = typeof spec === 'function' ? spec(t.worldPosition as Vec3) : spec;
// An icon is a marker in space rather than a card, so it is a cube: it reads
// and clicks the same from wherever the view has been turned to.
let w = iconHalf * 2;
diff --git a/sdk/src/ecs/entityPick.ts b/sdk/src/ecs/entityPick.ts
index f2de6fe21..c9cb34f8e 100644
--- a/sdk/src/ecs/entityPick.ts
+++ b/sdk/src/ecs/entityPick.ts
@@ -8,7 +8,7 @@
* boxes. They asked it twice, and the two answers had drifted: one knew a mesh's
* extent and the other boxed a model as a point.
*/
-import type { Entity } from '../types';
+import type { Entity, Vec3 } from '../types';
import type { World } from './world';
import type { WorldRay } from '../ui/util/math';
import { Transform, Sprite } from './component';
@@ -34,9 +34,10 @@ export interface EntityPickOptions {
/**
* World half-size of the box given to entities that draw nothing — a camera,
* a light, an empty. Zero (the default) leaves them unpickable, which is what
- * a realm that draws no gizmo for them wants.
+ * a realm that draws no gizmo for them wants. A function when the icon's size
+ * is a screen size (see {@link EntityBoxOptions.iconHalf}).
*/
- iconHalf?: number;
+ iconHalf?: number | ((at: Vec3) => number);
/** Entities this realm refuses to select. Everything is selectable by default. */
pickable?(entity: Entity): boolean;
/** The project's sorting-layer masks, so hits rank the way the frame stacked them. */
@@ -57,7 +58,9 @@ export function pickEntitiesByRay(
world: PickWorld, ray: WorldRay, opts: EntityPickOptions = {},
): Entity[] {
const iconHalf = opts.iconHalf ?? 0;
- const unlayered = iconHalf > 0 ? GIZMO_PICK_LAYER : 0;
+ // Whether icons are pickable at all, which is the question here — how big one is
+ // where it stands is entityWorldBox's.
+ const unlayered = (typeof iconHalf === 'function' || iconHalf > 0) ? GIZMO_PICK_LAYER : 0;
const hits: PickCandidate<Entity>[] = [];
for (const entity of world.getAllEntities()) {
if (!world.valid(entity) || !world.has(entity, Transform)) continue;