A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(editor): a selection is outlined by its own shape
esengine144f28b7c958
diff --git a/desktop/scripts/editor-checks/selection-outline.mjs b/desktop/scripts/editor-checks/selection-outline.mjsnew file mode 100644index 000000000..d2cc93c4b--- /dev/null+++ b/desktop/scripts/editor-checks/selection-outline.mjs@@ -0,0 +1,151 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file selection-outline — the outline is the shape of the thing, not a box round it.+ *+ * A selected entity is drawn as the convex hull of its projected corners. The hull+ * itself is unit-tested; what no unit test reaches is the overlay — the shape lives+ * in DOM over the canvas, which `capture_viewport` cannot see at all.+ *+ * A square turned 45° is what makes the claim measurable: its outline is a diamond+ * whose vertices sit at the MIDPOINTS of its bounding box's edges, and whose bounding+ * box CORNERS are empty. An outline drawn as that bounding box has exactly the+ * opposite ink. Head-on and in 2D on purpose: the loose box was never a 3D-only+ * problem, a turned sprite always had one.+ */+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');++/** An eighth turn about Z (45°), as the quaternion a scene file stores. A quarter+ * turn would leave the square axis-aligned and the two shapes identical. */+const EIGHTH = Math.PI / 4;+const SIN = Math.sin(EIGHTH / 2);+const COS = Math.cos(EIGHTH / 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 } },+ ],+ },+ {+ id: 1, name: 'Turned', parent: null, children: [], visible: true,+ components: [+ {+ type: 'Transform',+ data: { position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: SIN, w: COS } },+ },+ { type: 'Sprite', data: { size: { x: 220, y: 220 }, color: { r: 1, g: 0, b: 1, a: 1 } } },+ ],+ },+ ],+}, null, 1);++export const name = 'selection-outline';+export const describes = 'a selected entity is outlined by its own shape, not by a box around it';++/** Every pixel that differs between two shots, inside `box`. */+function changed(a, b, box, tol = 10) {+ const pts = [];+ const x1 = Math.floor(Math.min(a.w, b.w, box.x1));+ const y1 = Math.floor(Math.min(a.h, b.h, box.y1));+ for (let y = Math.max(0, Math.ceil(box.y0)); y < y1; y++) {+ for (let x = Math.max(0, Math.ceil(box.x0)); x < x1; x++) {+ const p = a.px(x, y);+ const q = b.px(x, y);+ if (Math.abs(p[0] - q[0]) > tol || Math.abs(p[1] - q[1]) > tol || Math.abs(p[2] - q[2]) > tol) {+ pts.push({ x, y });+ }+ }+ }+ return pts;+}++/** Bounding box of a point set. */+function bounds(pts) {+ const xs = pts.map((p) => p.x);+ const ys = pts.map((p) => p.y);+ return { x0: Math.min(...xs), x1: Math.max(...xs), y0: Math.min(...ys), y1: Math.max(...ys) };+}++/** How many of `pts` fall within `r` of `c`. */+const near = (pts, c, r) => pts.filter((p) => Math.hypot(p.x - c.x, p.y - c.y) <= r).length;++/** Pixels matching `want`, as a point set. */+function match(png, want, tol = 50) {+ const pts = [];+ for (let y = 0; y < png.h; y++) {+ for (let x = 0; x < png.w; x++) {+ const p = png.px(x, y);+ if (Math.abs(p[0] - want[0]) <= tol && Math.abs(p[1] - want[1]) <= tol+ && Math.abs(p[2] - want[2]) <= tol) pts.push({ x, y });+ }+ }+ return pts;+}++export async function run(ed) {+ const root = await makeProject({ 'assets/scenes/main.esscene': SCENE });+ await cp(path.join(EXAMPLE, 'project.esproject'), path.join(root, 'project.esproject'));+ await cp(path.join(EXAMPLE, 'src'), path.join(root, 'src'), { recursive: true });+ const check = checker();+ await ed.open(root, 'assets/scenes/main.esscene');++ // The select tool draws no transform gizmo, so the only ink selecting adds around+ // the entity is the outline itself (and the pivot dot, at the centre).+ await ed.call('run_editor_command', { id: 'tool.select' }, 30000);+ await ed.call('select', { id: null }, 30000);+ await ed.sleep(800);+ const bare = await ed.screenshot('outline-bare');++ const body = match(bare, [255, 0, 255]);+ if (!check(body.length > 500, `the shot shows ${body.length} pixels of the sprite — it is not on screen`)) {+ return check.failures;+ }+ const b = bounds(body);+ const half = Math.max(b.x1 - b.x0, b.y1 - b.y0) / 2;++ await ed.call('select', { id: 1 }, 30000);+ await ed.sleep(800);+ const selected = await ed.screenshot('outline-selected');++ // Around the sprite and nothing else: selecting repaints the outliner and the+ // details panel too, which is most of the window's ink and none of the question.+ const pad = Math.max(12, half * 0.25);+ const ink = changed(bare, selected, {+ x0: b.x0 - pad, x1: b.x1 + pad + 1, y0: b.y0 - pad, y1: b.y1 + pad + 1,+ });+ if (!check(ink.length > 100, `selecting drew ${ink.length} pixels around the sprite — no outline`)) {+ return check.failures;+ }++ const o = bounds(ink);+ const r = Math.max(6, half * 0.12);+ const corners = [+ { x: o.x0, y: o.y0 }, { x: o.x1, y: o.y0 }, { x: o.x1, y: o.y1 }, { x: o.x0, y: o.y1 },+ ];+ const mids = [+ { x: (o.x0 + o.x1) / 2, y: o.y0 }, { x: o.x1, y: (o.y0 + o.y1) / 2 },+ { x: (o.x0 + o.x1) / 2, y: o.y1 }, { x: o.x0, y: (o.y0 + o.y1) / 2 },+ ];+ const atCorners = corners.map((c) => near(ink, c, r)).reduce((a, n) => a + n, 0);+ const atMids = mids.map((c) => near(ink, c, r)).reduce((a, n) => a + n, 0);++ // A diamond's own vertices are the midpoints; a box round it has its ink at the+ // corners instead. Both are measured from the SAME bounding box, so the claim+ // needs no expected pixel count of its own.+ check(+ atMids > 4 * atCorners,+ `the outline has ${atMids} pixels at its bounding box's edge midpoints and ${atCorners} at `+ + 'its corners — a turned square is a diamond, and this is the box around it',+ );++ return check.failures;+}diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.tsindex 40ae4917c..5def20fbc 100644--- a/desktop/src/engine/ViewportController.ts+++ b/desktop/src/engine/ViewportController.ts@@ -35,6 +35,7 @@ import {obbCorners,rectsIntersect,screenAABB,+ screenHull,worldToLocal3D,} from './viewportMath';@@ -551,24 +552,32 @@ export const ViewportController = {},/**- * Screen rect of a UI node's layout box — its world OBB projected through the- * UI camera. Drives the selection outline for UI, which lives in screen space.+ * The OUTLINE of an entity as it projects: the convex hull of its box's corners+ * in CSS px, or null when any corner fails to project. A box is a quadrilateral+ * on screen while it is flat and square to the eye, and a hexagon once it has+ * depth. Every corner goes through its OWN depth, or the outline is the shadow's.*/- uiEntityScreenRect(id: EntityId): ClientRect | null {- const cam = EngineHost.getResource(UICameraInfo) as UICameraData | undefined;- const obb = this.uiEntityWorldOBB(id);- if (!cam?.valid || !obb) return null;- return screenAABB(entityBoxCorners(obb).map((c) => this.uiWorldToClient(cam, c.x, c.y)));+ entityScreenHull(id: EntityId): Array<{ x: number; y: number }> | null {+ const cam = EngineHost.world?.has(id, UINode)+ ? (EngineHost.getResource(UICameraInfo) as UICameraData | undefined)+ : undefined;+ const box = cam ? this.uiEntityWorldOBB(id) : this.entityBounds(id);+ if (!box || (cam !== undefined && !cam.valid)) return null;+ const pts = entityBoxCorners(box).map((c) => (cam+ ? this.uiWorldToClient(cam, c.x, c.y)+ : this.worldToClient(c.x, c.y, c.z)));+ if (pts.some((p) => !p)) return null;+ return screenHull(pts as Array<{ x: number; y: number }>);},- /** Screen-space bounding rect (CSS px rel. canvas) of an entity, for the selection outline. */+ /**+ * Screen-space bounding rect (CSS px rel. canvas) of an entity — the AABB of+ * {@link entityScreenHull}, so what hit-tests against a rect and what is drawn+ * around the entity cannot describe two different shapes.+ */getEntityScreenRect(id: EntityId): ClientRect | null {- if (EngineHost.world?.has(id, UINode)) return this.uiEntityScreenRect(id);- const b = this.entityBounds(id);- if (!b) return null;- // Every corner through its OWN depth: a box with any thickness has corners on- // different planes, and one shared plane would draw the outline of its shadow.- return screenAABB(entityBoxCorners(b).map((c) => this.worldToClient(c.x, c.y, c.z)));+ const hull = this.entityScreenHull(id);+ return hull ? screenAABB(hull) : null;},/**diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex 522fd84a3..f92077b71 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -258,6 +258,20 @@ function worldRectToScreen(return { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), w: Math.abs(b.x - a.x), h: Math.abs(b.y - a.y) };}+/**+ * Shape one outline polygon to the entity's projected hull, or hide it. `sid` null+ * (engine not ready) hides it too — a stale outline on a scene that is not there+ * reads as a selection.+ */+function shapeOutline(el: SVGPolygonElement | null, sid: number | null): void {+ if (!el) return;+ const rt = sid != null ? SceneModel.runtimeFor(sid) : undefined;+ const hull = rt != null ? ViewportController.entityScreenHull(rt) : null;+ if (!hull || hull.length < 2) { el.style.opacity = '0'; return; }+ el.setAttribute('points', hull.map((p) => `${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(' '));+ el.style.opacity = '1';+}+function setRectAttrs(el: Element | null, r: { x: number; y: number; w: number; h: number }): void {if (!el) return;el.setAttribute('x', String(r.x));@@ -930,14 +944,15 @@ export function Viewport() {const pivotHandleRef = useRef<HTMLDivElement>(null);const designSvgRef = useRef<SVGSVGElement>(null);const designLabelRef = useRef<HTMLDivElement>(null);- // One outline div per selected entity, keyed by source id and positioned by the rAF.- const selRefs = useRef(new Map<number, HTMLDivElement | null>());+ // One outline polygon per selected entity, keyed by source id and shaped by the rAF.+ const selRefs = useRef(new Map<number, SVGPolygonElement | null>());// Entities under the pointer in the agent's transcript. A tool row naming// `id: 7` means nothing until 7 lights up where the work actually is.const agentPeeked = useAgent((s) => s.peeked);- const peekRefs = useRef(new Map<number, HTMLDivElement | null>());- // The single merged-selection box shown instead, above the merge threshold.- const mergedSelRef = useRef<HTMLDivElement>(null);+ const peekRefs = useRef(new Map<number, SVGPolygonElement | null>());+ // The single merged-selection box shown instead, above the merge threshold. A+ // bounding box is what it claims to be, so it stays a rect where an outline is a hull.+ const mergedSelRef = useRef<SVGRectElement>(null);const marqueeRef = useRef<HTMLDivElement>(null);const tileSelRef = useRef<HTMLDivElement>(null);const tilePreviewRef = useRef<HTMLDivElement>(null);@@ -1270,9 +1285,7 @@ export function Viewport() {}if (merged) {if (Number.isFinite(minX)) {- merged.style.transform = `translate(${minX}px, ${minY}px)`;- merged.style.width = `${maxX - minX}px`;- merged.style.height = `${maxY - minY}px`;+ setRectAttrs(merged, { x: minX, y: minY, w: maxX - minX, h: maxY - minY });merged.style.opacity = '1';} else {merged.style.opacity = '0';@@ -1280,37 +1293,12 @@ export function Viewport() {}} else {if (merged) merged.style.opacity = '0';- for (const [sid, el] of selRefs.current) {- if (!el) continue;- const rt = ready ? SceneModel.runtimeFor(sid) : undefined;- const rect = rt != null ? ViewportController.getEntityScreenRect(rt) : null;- if (rect) {- el.style.transform = `translate(${rect.x}px, ${rect.y}px)`;- el.style.width = `${rect.w}px`;- el.style.height = `${rect.h}px`;- el.style.opacity = '1';- } else {- el.style.opacity = '0';- }- }+ for (const [sid, el] of selRefs.current) shapeOutline(el, ready ? sid : null);}- // Agent peek outlines, positioned the same way selection is — they follow- // pan and zoom because they are projected from world every frame, not- // placed once.- for (const [sid, el] of peekRefs.current) {- if (!el) continue;- const rt = ready ? SceneModel.runtimeFor(sid) : undefined;- const rect = rt != null ? ViewportController.getEntityScreenRect(rt) : null;- if (rect) {- el.style.transform = `translate(${rect.x}px, ${rect.y}px)`;- el.style.width = `${rect.w}px`;- el.style.height = `${rect.h}px`;- el.style.opacity = '1';- } else {- el.style.opacity = '0';- }- }+ // Agent peek outlines, shaped the same way selection is — they follow pan and+ // zoom because they are projected from world every frame, not placed once.+ for (const [sid, el] of peekRefs.current) shapeOutline(el, ready ? sid : null);// UI resize gizmo: a single selected UINode gets edge/corner handles on its// screen rect (getEntityScreenRect — the same rect the selection outline uses).@@ -2879,33 +2867,37 @@ export function Viewport() {</div>)}- {/* One outline per selected entity (rAF-positioned); primary gets the accent.- Above the merge threshold these collapse to the single merged box below. */}- {selList.length <= SELECTION_OUTLINE_MERGE_THRESHOLD &&- selList.map((id) => (- <div- key={id}+ {/* One outline per selected entity, shaped by the rAF to the entity's projected+ hull; primary reads stronger. Above the merge threshold they collapse to the+ merged bounding box, which is a rect because that is what it claims to be. */}+ <svg className="viewport__selection" aria-hidden="true">+ {selList.length <= SELECTION_OUTLINE_MERGE_THRESHOLD &&+ selList.map((id) => (+ <polygon+ key={id}+ ref={(el) => {+ if (el) selRefs.current.set(id, el);+ else selRefs.current.delete(id);+ }}+ className={`sel-outline${id === primaryId ? ' primary' : ''}`}+ style={{ opacity: 0 }}+ />+ ))}+ <rect ref={mergedSelRef} className="sel-outline" style={{ opacity: 0 }} />+ </svg>+ <svg className="viewport__agentpeek" aria-hidden="true">+ {agentPeeked.map((id) => (+ <polygon+ key={`peek-${id}`}ref={(el) => {- if (el) selRefs.current.set(id, el);- else selRefs.current.delete(id);+ if (el) peekRefs.current.set(id, el);+ else peekRefs.current.delete(id);}}- className={`viewport__selection${id === primaryId ? ' primary' : ''}`}- aria-hidden="true"+ className="peek-outline"+ style={{ opacity: 0 }}/>))}- {agentPeeked.map((id) => (- <div- key={`peek-${id}`}- ref={(el) => {- if (el) peekRefs.current.set(id, el);- else peekRefs.current.delete(id);- }}- className="viewport__agentpeek"- aria-hidden="true"- />- ))}- {/* The merged selection box (shown only above the threshold; rAF-positioned). */}- <div ref={mergedSelRef} className="viewport__selection" style={{ opacity: 0 }} aria-hidden="true" />+ </svg>{/* The selected sprite's pivot dot. One element for the whole viewport (only asingle selection ever gets it); the rAF parks it and stamps the runtime id thedrag reads, so no per-entity element is minted for a handle that shows once. */}diff --git a/desktop/src/theme/agent.css b/desktop/src/theme/agent.cssindex 9b7cc6a16..d2d1d1ba8 100644--- a/desktop/src/theme/agent.css+++ b/desktop/src/theme/agent.css@@ -1073,15 +1073,21 @@each frame, so it tracks pan and zoom rather than sitting where it was drawn. */.viewport__agentpeek {position: absolute;- top: 0; left: 0;+ inset: 0;+ width: 100%;+ height: 100%;pointer-events: none;- opacity: 0;- border: 1px solid var(--nebula);- border-radius: 2px;- box-shadow: 0 0 0 3px var(--nebula-soft);- transition: opacity var(--t-fast);+ overflow: visible;z-index: 3;}+.viewport__agentpeek .peek-outline {+ fill: none;+ stroke: var(--nebula);+ stroke-width: 1;+ stroke-linejoin: round;+ filter: drop-shadow(0 0 3px var(--nebula-soft));+ transition: opacity var(--t-fast);+}/* An entity named in the answer. A hairline under it, not a colour: it is athing in the scene, not a hyperlink out of the editor. */.md-ent {diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.cssindex 0ccba6d5d..10a933b30 100644--- a/desktop/src/theme/app.css+++ b/desktop/src/theme/app.css@@ -248,22 +248,29 @@/* Selection outline around the selected entity (rAF-driven, below the gizmo). *//* Selected-entity outline — the iconic orange, with a dark halo for contrastover any scene color. The blue accent stays reserved for UI chrome. */+/* Selection chrome: one overlay, whose shapes are the entities' projected hulls.+ A box is a quadrilateral on screen only while it is flat and square to the eye. */.viewport__selection {position: absolute;- top: 0;- left: 0;+ inset: 0;+ width: 100%;+ height: 100%;z-index: 1;- opacity: 0;pointer-events: none;- border: 1px solid var(--sel);- box-shadow:- 0 0 0 1px rgba(14, 15, 18, 0.7),- inset 0 0 0 1px rgba(14, 15, 18, 0.4);- will-change: transform, width, height, opacity;+ overflow: visible;+}+.viewport__selection .sel-outline {+ fill: none;+ stroke: var(--sel);+ stroke-width: 1;+ /* The dark hairline the box-shadow used to carry, so the outline reads over+ light artwork as well as dark. */+ paint-order: stroke;+ filter: drop-shadow(0 0 1px rgba(14, 15, 18, 0.7));}/* The primary (active) entity in a multi-selection reads slightly stronger. */-.viewport__selection.primary {- border-width: 1.5px;+.viewport__selection .sel-outline.primary {+ stroke-width: 1.5;}/* The selected sprite's pivot dot: a ring with a centre point, drawn ON the entityorigin. `translate` puts its centre there (hence the -50% pair), and it sits above