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): one hierarchy, and gizmos on the running game

yhh57d39c4fdd90
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index 8a5193a01..009fe3d2a 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -212,7 +212,6 @@ export function App() {
const players = useEditorStore.getState().playPlayers;
void PlayRealms.startSession(payload, players);
PlayInspect.start(); // poll the running game for live inspect/debug
- useEditorStore.getState().setInspectWorld('game'); // flip Outliner/Details to the live game
// 'window' → a Game dock tab; 'viewport' → the Viewport mounts it (PIE).
if (useEditorStore.getState().playTarget === 'window') dockApi.openGame();
// Client players each get their own Game tab beside player 1.
@@ -228,7 +227,6 @@ export function App() {
} else {
PlayRealms.stopSession();
PlayInspect.stop();
- useEditorStore.getState().setInspectWorld('editor');
if (autoMaximized.current) {
dockApi.exitMaximized();
autoMaximized.current = false;
diff --git a/desktop/src/engine/PlayInspect.ts b/desktop/src/engine/PlayInspect.ts
index 0505b77eb..41ff28bb9 100644
--- a/desktop/src/engine/PlayInspect.ts
+++ b/desktop/src/engine/PlayInspect.ts
@@ -1,26 +1,28 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file PlayInspect.ts — the editor's "Game" inspection source.
- * While playing, it samples the running realm for a live SceneData snapshot
- * (via PlayRealm.snapshot → serializeScene of the realm's World) and holds
- * the user's live selection. The Outliner/Details build their view-models
- * from this snapshot (reusing buildSceneTree/buildInspector) when in Game
- * mode; field edits route to PlayRealm.setField (live, reverts on Stop).
+ * @file PlayInspect.ts — the editor's window into the running world.
+ * While playing, it samples the realm for a live SceneData snapshot
+ * (via PlayRealm.snapshot → the realm's own World walk) and resolves the
+ * editor's {@link EntityRef} selection against it. The Outliner/Details
+ * build their view-models from this snapshot; field edits route to
+ * PlayRealm.setField (live, reverts on Stop).
*
* Sampling is a COALESCED loop, not a fixed-interval poll: one request is
* in flight at a time and the next is armed only after the reply. It runs
- * ONLY while a game-mode panel is actually subscribed (the GameTree /
- * GameDetails views mount only in Game mode), and at split rates: the
+ * ONLY while a consumer is actually subscribed, and at split rates: the
* O(entities) tree at ~7Hz, the selected entity's full data at ~30Hz
* (detail-only samples skip the realm's tree walk entirely).
*
- * Selection here is a REALM runtime id — distinct from the editor's
- * source-id selection (selectionStore), never mixed.
+ * Selection lives in selectionStore, as a ref — this holds only the
+ * mapping that resolves one to a realm runtime id.
*/
import { createStore } from 'zustand/vanilla';
import type { SceneData } from 'esengine';
import type { EntityId } from '@/types';
+import type { LiveOrigin, PlayOverlayBox } from './playProtocol';
+import { useSelection } from '@/store/selectionStore';
+import { refOfLive, type EntityRef } from './entityRef';
import { PlayRealm } from './PlayRealm';
interface PlayInspectState {
@@ -28,7 +30,8 @@ interface PlayInspectState {
snapshot: SceneData | null;
/** Full data of the selected entity (Details), fetched alongside the tree. */
selectedEntity: SceneData['entities'][number] | null;
- selection: EntityId | null;
+ /** Where that entity is drawn on the realm's canvas (the viewport overlay). */
+ overlay: PlayOverlayBox | null;
}
/** Minimum gap between STRUCTURAL tree samples (ms) — the Outliner doesn't need
@@ -38,24 +41,29 @@ const TREE_GAP_MS = 150;
* live values smoothly; the realm decodes data only for that one entity. */
const DETAIL_GAP_MS = 33;
+type LiveEntity = SceneData['entities'][number] & LiveOrigin;
+
/** A cheap structural signature of the shallow tree (ids / parent / name / component
* types) — drives keeping the tree reference stable when only values changed.
*
- * `hidden` rides along despite being a value: it is the one value the TREE shows,
- * so leaving it out would hold the old reference and the eye you just clicked
- * would not change. */
+ * `hidden` and `src` ride along despite not being structure: they are what the
+ * TREE shows and what its rows are keyed by, so leaving them out would hold the
+ * old reference and the eye you just clicked would not change. */
function treeSig(t: SceneData): string {
return t.entities
- .map((e) => `${e.id},${e.parent ?? ''},${e.name},${(e as { hidden?: boolean }).hidden ? 'h' : ''},${e.components.map((c) => c.type).join('+')}`)
+ .map((e) => {
+ const live = e as LiveEntity & { hidden?: boolean };
+ return `${e.id},${e.parent ?? ''},${e.name},${live.hidden ? 'h' : ''},${live.src ?? ''},${e.components.map((c) => c.type).join('+')}`;
+ })
.join('|');
}
class PlayInspectImpl {
- private readonly store = createStore<PlayInspectState>(() => ({ snapshot: null, selectedEntity: null, selection: null }));
+ private readonly store = createStore<PlayInspectState>(() => ({ snapshot: null, selectedEntity: null, overlay: null }));
private active = false;
private timer: ReturnType<typeof setTimeout> | null = null;
- // Consumers of the live snapshot (the game-mode Outliner/Details views). Zero
- // subscribers = nobody is looking = don't sample the realm at all.
+ // Consumers of the live snapshot. Zero subscribers = nobody is looking = don't
+ // sample the realm at all.
private subscribers = 0;
// One loop at a time: `scheduled` covers a queued-or-in-flight tick; `epoch`
// invalidates an in-flight tick across stop()/start() so it can't double-arm.
@@ -65,6 +73,10 @@ class PlayInspectImpl {
// Signature of the CURRENT tree snapshot — computed once when a tree arrives,
// cached so a new sample hashes only itself (not the old tree again).
private curTreeSig = '';
+ // Identity, both ways, for the tree currently held. Rebuilt with it.
+ private srcToLive = new Map<EntityId, EntityId>();
+ private liveToSrc = new Map<EntityId, EntityId>();
+ private liveIds = new Set<EntityId>();
subscribe = (fn: () => void): (() => void) => {
const unsub = this.store.subscribe(fn);
@@ -78,11 +90,19 @@ class PlayInspectImpl {
getSnapshot = (): PlayInspectState => this.store.getState();
/** Identity-stable slices so Details-only ticks don't re-render the Outliner. */
getTree = (): SceneData | null => this.store.getState().snapshot;
- getSelection = (): EntityId | null => this.store.getState().selection;
- select(selection: EntityId | null): void {
- this.store.setState({ ...this.store.getState(), selection });
- void this.poll(false); // fetch the newly-selected entity's full data immediately
+ /** The realm runtime id `ref` names right now, or null when the running world
+ * has no such entity (never spawned, or already destroyed). */
+ liveIdOf(ref: EntityRef | null): EntityId | null {
+ if (ref == null) return null;
+ if (ref.world === 'spawned') return this.liveIds.has(ref.live) ? ref.live : null;
+ return this.srcToLive.get(ref.src) ?? null;
+ }
+
+ /** Identity of a realm runtime id — authored when the realm reported a document
+ * id for it, else spawned. */
+ refOf(live: EntityId): EntityRef {
+ return refOfLive(live, this.liveToSrc.get(live));
}
/** Begin sampling (call on Play). Idempotent; idles until a consumer subscribes. */
@@ -101,7 +121,24 @@ class PlayInspectImpl {
this.timer = null;
this.lastTreeAt = 0;
this.curTreeSig = '';
- this.store.setState({ snapshot: null, selectedEntity: null, selection: null });
+ this.srcToLive = new Map();
+ this.liveToSrc = new Map();
+ this.liveIds = new Set();
+ this.store.setState({ snapshot: null, selectedEntity: null, overlay: null });
+ // A selection the realm owned outlives nothing: with the realm gone there is
+ // no entity behind it and no row to show it on.
+ useSelection.getState().dropSpawnedSelection();
+ }
+
+ /** Where the selection is drawn on the realm's canvas, as of the last sample. */
+ getOverlay = (): PlayOverlayBox | null => this.store.getState().overlay;
+
+ /** The live data of `comp` on `id`, for a write that has to merge into it.
+ * Only the SELECTED entity's data is sampled, so anything else answers empty. */
+ componentData(id: EntityId, comp: string): Record<string, unknown> {
+ const sel = this.store.getState().selectedEntity;
+ if (!sel || sel.id !== id) return {};
+ return (sel.components.find((c) => c.type === comp)?.data as Record<string, unknown>) ?? {};
}
/** Live-edit a field of the running game; refresh immediately for snappy feedback. */
@@ -117,6 +154,11 @@ class PlayInspectImpl {
void this.poll(true);
}
+ /** Re-sample now (a selection change wants its entity's data without waiting). */
+ refresh(): void {
+ void this.poll(false);
+ }
+
// Start the loop if it should run and isn't already (called on start + on the
// first subscriber appearing while playing).
private arm(): void {
@@ -140,13 +182,17 @@ class PlayInspectImpl {
this.scheduled = false;
return;
}
- const gap = this.store.getState().selection != null ? DETAIL_GAP_MS : TREE_GAP_MS;
+ const gap = this.selectedLiveId() != null ? DETAIL_GAP_MS : TREE_GAP_MS;
const wait = Math.max(0, gap - (performance.now() - t0));
this.timer = setTimeout(() => void this.tick(epoch), wait);
}
+ private selectedLiveId(): EntityId | null {
+ return this.liveIdOf(useSelection.getState().selectedRef);
+ }
+
private async poll(withTree: boolean): Promise<void> {
- const sel = this.store.getState().selection;
+ const sel = this.selectedLiveId();
const res = await PlayRealm.snapshot(sel, { tree: withTree });
if (!res) return;
const cur = this.store.getState();
@@ -157,19 +203,38 @@ class PlayInspectImpl {
if (res.tree) {
this.lastTreeAt = performance.now();
const sig = treeSig(res.tree);
- if (cur.snapshot == null || sig !== this.curTreeSig) snapshot = res.tree;
+ if (cur.snapshot == null || sig !== this.curTreeSig) {
+ snapshot = res.tree;
+ this.reindex(res.tree);
+ }
this.curTreeSig = sig;
}
const sameSelected = cur.selectedEntity === res.selected
|| (cur.selectedEntity != null && res.selected != null
&& JSON.stringify(cur.selectedEntity) === JSON.stringify(res.selected));
- if (snapshot === cur.snapshot && sameSelected) return;
+ // The overlay moves with the game whether or not any value changed — a
+ // gizmo that only redrew when the Inspector did would lag the sprite it is
+ // drawn around by however long that took.
+ const sameOverlay = JSON.stringify(cur.overlay) === JSON.stringify(res.overlay ?? null);
+ if (snapshot === cur.snapshot && sameSelected && sameOverlay) return;
this.store.setState({
snapshot,
selectedEntity: sameSelected ? cur.selectedEntity : res.selected,
- selection: cur.selection,
+ overlay: sameOverlay ? cur.overlay : (res.overlay ?? null),
});
}
+
+ private reindex(tree: SceneData): void {
+ this.srcToLive = new Map();
+ this.liveToSrc = new Map();
+ this.liveIds = new Set();
+ for (const e of tree.entities as LiveEntity[]) {
+ this.liveIds.add(e.id);
+ if (e.src === undefined) continue;
+ this.srcToLive.set(e.src, e.id);
+ this.liveToSrc.set(e.id, e.src);
+ }
+ }
}
export const PlayInspect = new PlayInspectImpl();
diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.ts
index f9bf8e8f2..714ac720f 100644
--- a/desktop/src/engine/PlayRealm.ts
+++ b/desktop/src/engine/PlayRealm.ts
@@ -24,7 +24,7 @@ import { t } from '@/i18n';
import { playProtocolMismatch } from './playProtocol';
import { bootProfiler } from './bootProfiler';
import { projectReplacing } from '@/project/projectReplacing';
-import type { PlayOutbound, PlayInbound, PlayPayload, PlaySnapshot, PlayStatsReply, PlayStepReply } from './playProtocol';
+import type { PlayOutbound, PlayInbound, PlayPayload, PlaySnapshot, PlayStatsReply, PlayStepReply, PlayPickReply } from './playProtocol';
export type { PlayPayload, PlaySnapshot } from './playProtocol';
@@ -375,6 +375,24 @@ export class PlayRealmInstance {
});
}
+ /** The topmost running entity at a canvas point (normalized, top-left origin),
+ * or null. Null too if no realm is up. */
+ pick(x: number, y: number): Promise<number | null> {
+ if (!this.iframe?.contentWindow || !this.store.getState().ready) return Promise.resolve(null);
+ const reqId = ++this.reqSeq;
+ return new Promise((resolve) => {
+ this.pending.set(reqId, (data) => resolve((data as PlayPickReply)?.entityId ?? null));
+ this.post({ type: 'estella:play:query', kind: 'pick', reqId, x, y });
+ setTimeout(() => { if (this.pending.delete(reqId)) resolve(null); }, 2000);
+ });
+ }
+
+ /** Drag a running entity's origin to a canvas point (reverts on Stop). Fire and
+ * forget: the next snapshot is the confirmation, at the rate the overlay draws. */
+ dragTo(entityId: number, x: number, y: number, axis?: 'x' | 'y'): void {
+ this.post({ type: 'estella:play:dragTo', entityId, x, y, ...(axis ? { axis } : {}) });
+ }
+
/** Live-edit a field of a running entity (debug; reverts on Stop). */
setField(entityId: number, comp: string, key: string, value: unknown): void {
this.post({ type: 'estella:play:setField', entityId, comp, key, value });
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index 9ddc9756f..3aa104deb 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -13,6 +13,7 @@ import {
readColliderShapes, colliderShapeOutline, shapeCenter,
layerOrderOf,
editorViewHalfHeight, editorViewHalfExtent, setEditorViewHalfHeight, EDITOR_UI_ANCHOR,
+ entityWorldBox,
type TilesetModel, type TileCollisionPiece, type TileGridParams,
} from 'esengine';
import type { EntityId } from '@/types';
@@ -235,34 +236,11 @@ export const ViewportController = {
*/
entityBounds(id: EntityId): OBB | null {
const world = EngineHost.world;
- if (!world || !world.valid(id) || !world.has(id, Transform)) return null;
- // UI nodes are screen-space; they're picked via the UI hit-test, not a world OBB.
- if (world.has(id, UINode)) return null;
- const t = world.get(id, Transform);
- const rot = quatAngleZ(t.worldRotation as { w: number; x: number; y: number; z: number });
-
- let w = ICON_WORLD_HALF * 2;
- let h = ICON_WORLD_HALF * 2;
- let px = 0.5;
- let py = 0.5;
- if (world.has(id, Sprite)) {
- const sp = world.get(id, Sprite);
- w = sp.size.x * t.worldScale.x;
- h = sp.size.y * t.worldScale.y;
- px = sp.pivot?.x ?? 0.5;
- py = sp.pivot?.y ?? 0.5;
- }
- const ox = w * (0.5 - px);
- const oy = h * (0.5 - py);
- const c = Math.cos(rot);
- const s = Math.sin(rot);
- return {
- cx: t.worldPosition.x + ox * c - oy * s,
- cy: t.worldPosition.y + ox * s + oy * c,
- hw: Math.abs(w) / 2,
- hh: Math.abs(h) / 2,
- rot,
- };
+ if (!world) return null;
+ // 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 });
},
/**
diff --git a/desktop/src/engine/entityOps.ts b/desktop/src/engine/entityOps.ts
new file mode 100644
index 000000000..191578dc2
--- /dev/null
+++ b/desktop/src/engine/entityOps.ts
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file entityOps.ts — writing to an entity without knowing which world it is in.
+ *
+ * The same three gestures — set a field, hide a row, move a thing — mean one
+ * write to the scene document and a different one to the running realm. Leaving
+ * that choice to each caller is how a panel ends up branching on the play state,
+ * and how one of the two paths quietly stops being maintained.
+ *
+ * So the choice is made once, here: the document sink records undo and reaches
+ * disk, the live sink posts to the realm and evaporates on Stop. Callers name
+ * an entity by {@link EntityRef} and say what they want.
+ */
+import type { EntityId, FieldWrite, InspectorFieldType } from '@/types';
+import { useEditorStore } from '@/store/editorStore';
+import { SceneCommands, toModelValue } from './SceneCommands';
+import { PlayInspect } from './PlayInspect';
+import { PlayRealm } from './PlayRealm';
+import { srcIdOf, type EntityRef } from './entityRef';
+
+/** The value vocabulary every inspector control commits in. */
+type FieldValue = Parameters<FieldWrite>[2];
+
+/** Which world a write went to; `null` = nowhere, the ref named nothing writable. */
+export type OpWorld = 'document' | 'live' | null;
+
+/** True while the running game owns the entities on screen. */
+const liveNow = (): boolean => useEditorStore.getState().isPlaying;
+
+export const EntityOps = {
+ /** The world a write for `ref` would land in — what a panel asks to label an
+ * edit as temporary, never to pick a code path. */
+ worldFor(ref: EntityRef | null): OpWorld {
+ if (ref == null) return null;
+ if (liveNow()) return PlayInspect.liveIdOf(ref) != null ? 'live' : null;
+ return srcIdOf(ref) != null ? 'document' : null;
+ },
+
+ setField(ref: EntityRef, comp: string, key: string, type: InspectorFieldType, value: FieldValue): OpWorld {
+ if (liveNow()) {
+ const live = PlayInspect.liveIdOf(ref);
+ if (live == null) return null;
+ // The document sink is handed an inspector value and merges it into the
+ // model itself; the realm takes a whole component value, so the same merge
+ // happens here against what the realm last reported.
+ PlayInspect.setField(live, comp, key, toModelValue(PlayInspect.componentData(live, comp), type, key, value as never));
+ return 'live';
+ }
+ const src = srcIdOf(ref);
+ if (src == null) return null;
+ SceneCommands.setField(src, comp, key, type, value as never);
+ return 'document';
+ },
+
+ setVisible(ref: EntityRef, visible: boolean): OpWorld {
+ if (liveNow()) {
+ const live = PlayInspect.liveIdOf(ref);
+ if (live == null) return null;
+ PlayInspect.setVisible(live, visible);
+ return 'live';
+ }
+ const src = srcIdOf(ref);
+ if (src == null) return null;
+ SceneCommands.setEntityVisible(src, visible);
+ return 'document';
+ },
+
+ /**
+ * Put an entity's origin at a point on the surface it is drawn on.
+ *
+ * Each world is given the point in the space it can answer in: the editor
+ * projects its own viewport and writes world x/y, the realm is handed a point
+ * on its canvas. Neither reimplements the other's projection.
+ */
+ moveToPoint(ref: EntityRef, point: { world?: { x: number; y: number }; canvas?: { x: number; y: number } }, axis?: 'x' | 'y'): OpWorld {
+ if (liveNow()) {
+ const live = PlayInspect.liveIdOf(ref);
+ if (live == null || !point.canvas) return null;
+ PlayRealm.dragTo(live, point.canvas.x, point.canvas.y, axis);
+ return 'live';
+ }
+ const src = srcIdOf(ref);
+ if (src == null || !point.world) return null;
+ SceneCommands.setEntityXY(src, point.world.x, point.world.y);
+ return 'document';
+ },
+} as const;
+
+/** The realm id a ref names right now — for callers that must speak to the realm
+ * directly (a query, not a write). */
+export const liveIdOf = (ref: EntityRef | null): EntityId | null => PlayInspect.liveIdOf(ref);
diff --git a/desktop/src/engine/entityRef.ts b/desktop/src/engine/entityRef.ts
new file mode 100644
index 000000000..196df84db
--- /dev/null
+++ b/desktop/src/engine/entityRef.ts
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file entityRef.ts — what "the same entity" means across the play boundary.
+ *
+ * The editor's scene document and the running realm are two worlds with two id
+ * spaces: a document `src` id, and a realm runtime handle. A ref names an entity
+ * in whichever of the two owns it, so one tree, one selection and one inspector
+ * can span both instead of being switched between.
+ *
+ * A ref is pure identity — it holds no live id for an authored entity, because
+ * that changes with every play session. Ask {@link liveIdOf} for the current one.
+ */
+import type { EntityId } from '@/types';
+
+export type EntityRef =
+ /** An entity the open scene document declares; `src` is its document id. */
+ | { world: 'authored'; src: EntityId }
+ /** An entity only the running game has — it despawns with the realm. */
+ | { world: 'spawned'; live: EntityId };
+
+export const authoredRef = (src: EntityId): EntityRef => ({ world: 'authored', src });
+export const spawnedRef = (live: EntityId): EntityRef => ({ world: 'spawned', live });
+
+/** Row/expansion key. Authored keys match the plain-scene ones, so a saved
+ * expansion set still opens the same rows after a play session. */
+export const refKey = (ref: EntityRef): string =>
+ ref.world === 'authored' ? `e${ref.src}` : `l${ref.live}`;
+
+export const sameRef = (a: EntityRef | null, b: EntityRef | null): boolean =>
+ a === b || (a != null && b != null && refKey(a) === refKey(b));
+
+/** The document id, or null for something only the running game has. */
+export const srcIdOf = (ref: EntityRef | null): EntityId | null =>
+ ref?.world === 'authored' ? ref.src : null;
+
+/** Where a live tree entity's identity comes from: its `src` when the realm
+ * reported one, else the realm handle itself. */
+export const refOfLive = (id: EntityId, src: number | undefined): EntityRef =>
+ src === undefined ? spawnedRef(id) : authoredRef(src);
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index ac9fa2df2..bf9c3544c 100644
--- a/desktop/src/engine/playProtocol.ts
+++ b/desktop/src/engine/playProtocol.ts
@@ -18,7 +18,7 @@ import type { SceneData, PhysicsPluginConfig, AudioProjectConfig, ThemeOverrides
* compares it against its own and refuses a mismatch (P1) rather than failing
* obscurely on a shape it doesn't understand. Bump on any incompatible message change.
*/
-export const PLAY_PROTOCOL_VERSION = 3;
+export const PLAY_PROTOCOL_VERSION = 5;
/**
* The handshake check: `null` if the realm's reported protocol version is compatible
@@ -103,12 +103,36 @@ export interface PlayPayload {
* `tree` is null for a detail-only sample (`withTree: false`) — the editor polls
* the selected entity faster than the O(entities) tree.
*
- * Each tree entity carries {@link LiveVisibility} alongside the fields SceneData
- * declares, so the running world's Outliner reads the same `hidden` bit an
- * edited scene does and the shared tree builder needs no live-specific branch. */
+ * Each tree entity carries {@link LiveVisibility} and {@link LiveOrigin} alongside
+ * the fields SceneData declares, so the running world's Outliner reads the same
+ * `hidden` bit an edited scene does and the shared tree builder needs no
+ * live-specific branch. */
export interface PlaySnapshot {
tree: SceneData | null;
selected: SceneData['entities'][number] | null;
+ /** Where the selected entity sits on the realm's own canvas — null when
+ * nothing is selected, or it has no place on screen (a UI node, off camera). */
+ overlay: PlayOverlayBox | null;
+}
+
+/**
+ * A point on the realm's canvas, normalized 0..1 from the TOP-LEFT.
+ *
+ * Normalized because the two sides disagree about pixels — device ratio, a
+ * letterboxed camera viewport, an iframe scaled to a device preset — and each
+ * disagreement is a gizmo drawn off the thing it points at.
+ */
+export interface CanvasPoint {
+ x: number;
+ y: number;
+}
+
+/** An entity's drawn box, as the realm's own camera projects it. */
+export interface PlayOverlayBox {
+ /** The four corners, counter-clockwise from the box's local -x,-y. */
+ corners: CanvasPoint[];
+ /** The transform origin — where a move gizmo is anchored. */
+ origin: CanvasPoint;
}
/** The visibility half of a live tree entity — what the Outliner's eye reads.
@@ -121,7 +145,24 @@ export interface LiveVisibility {
hideable?: boolean;
}
-export type PlayQueryKind = 'snapshot' | 'subsystems' | 'stats' | 'step';
+/**
+ * The authoring identity of a live entity: the id it carries in the scene
+ * DOCUMENT the editor has open. Absent means the running game spawned it, so
+ * nothing in the editor's scene corresponds to it. A row keyed by `src` is the
+ * same row before, during and after a play session.
+ */
+export interface LiveOrigin {
+ src?: number;
+}
+
+export type PlayQueryKind = 'snapshot' | 'subsystems' | 'stats' | 'step' | 'pick';
+
+/** What `query { kind: 'pick' }` answers with: the topmost entity at that canvas
+ * point, or null. Asked of the realm rather than computed in the editor because
+ * the side holding the camera and the renderer is the side that knows. */
+export interface PlayPickReply {
+ entityId: number | null;
+}
/** What `query { kind: 'step' }` answers with: the clock AFTER the advance, so a
* caller can tell frames that ran from a request that reached no app. */
@@ -169,13 +210,23 @@ export type PlayOutbound =
selectedId?: number | null; withTree?: boolean;
// `step` only: how far to advance, and with what fixed delta.
frames?: number; dt?: number;
+ // `pick` only: the canvas point to ask about.
+ x?: number; y?: number;
}
| { type: 'estella:play:setField'; entityId: number; comp: string; key: string; value: unknown }
// Show/hide a live entity (the Outliner's eye). An operation rather than a
// field write: WHICH components carry visibility is the engine's knowledge, and
// the realm answers it with the SDK's own setEntityVisible so the editor never
// has to keep a second list of what counts as a renderer.
- | { type: 'estella:play:setVisible'; entityId: number; visible: boolean };
+ | { type: 'estella:play:setVisible'; entityId: number; visible: boolean }
+ /**
+ * Put an entity's origin at a canvas point, optionally locked to a world axis.
+ *
+ * A drag is a screen-space gesture, so it is sent as one; the conversion to a
+ * world position, and to the parent-local write a Transform holds, happens
+ * where the camera is. The axis lock resolves after it, in world space.
+ */
+ | { type: 'estella:play:dragTo'; entityId: number; x: number; y: number; axis?: 'x' | 'y' };
/** realm → editor. Discriminated by `type`. */
export type PlayInbound =
diff --git a/desktop/src/i18n/messages/details.ts b/desktop/src/i18n/messages/details.ts
index 35a0ba902..2c3a288c5 100644
--- a/desktop/src/i18n/messages/details.ts
+++ b/desktop/src/i18n/messages/details.ts
@@ -150,6 +150,10 @@ export const detailsMessages = defineMessages({
en: 'Select a running entity in the Outliner to inspect + tweak it live.',
zh: '在大纲中选择一个运行中的实体,即可实时检视和调整。',
},
+ 'det.gameGone': {
+ en: 'The running game no longer has this entity.',
+ zh: '运行中的游戏里已经没有这个实体了。',
+ },
// — Material asset inspector —
'det.loadingMaterial': { en: 'Loading material…', zh: '正在加载材质…' },
diff --git a/desktop/src/i18n/messages/outliner.ts b/desktop/src/i18n/messages/outliner.ts
index eed961932..d2f3bfcd7 100644
--- a/desktop/src/i18n/messages/outliner.ts
+++ b/desktop/src/i18n/messages/outliner.ts
@@ -6,11 +6,10 @@
import { defineMessages } from './types';
export const outlinerMessages = defineMessages({
- // — World picker (edit vs live game) + the live-game tree —
- 'out.inspectedWorld': { en: 'Inspected world', zh: '检视的世界' },
- 'out.worldEditor': { en: 'Editor', zh: '编辑器' },
- 'out.worldGame': { en: 'Game', zh: '游戏' },
+ // — The tree while the game runs —
+ 'out.liveWorld': { en: 'Live — edits end at Stop', zh: '运行中 · 改动在停止时结束' },
'out.waitingGame': { en: 'Waiting for the running game…', zh: '正在等待运行中的游戏…' },
+ 'out.spawnedTip': { en: 'Spawned by the running game', zh: '由运行中的游戏创建' },
// — Header strip (search / sort / create buttons) —
// `type:` / `comp:` are literal query tokens (parseQuery grammar) — never translated.
diff --git a/desktop/src/i18n/messages/viewport.ts b/desktop/src/i18n/messages/viewport.ts
index 5e74ecfa0..e37de8aae 100644
--- a/desktop/src/i18n/messages/viewport.ts
+++ b/desktop/src/i18n/messages/viewport.ts
@@ -141,6 +141,11 @@ export const viewportMessages = defineMessages({
// — Play chrome (Play-in-viewport + Game panel) —
'vp.playFailed': { en: 'Play failed: {error}', zh: '运行失败:{error}' },
'vp.startingGame': { en: 'Starting game…', zh: '正在启动游戏…' },
+ 'vp.inspectPlay': { en: 'Inspect', zh: '检视' },
+ 'vp.inspectPlayTip': {
+ en: 'Select and move entities in the running game. While on, clicks go to the editor instead of the game.',
+ zh: '在运行中的游戏里选择和移动实体。开启期间点击归编辑器,不再传给游戏。',
+ },
'vp.pausedFlag': { en: '⏸ PAUSED', zh: '⏸ 已暂停' },
'vp.openModePanels': { en: 'Open {mode} panels', zh: '打开{mode}面板' },
'vp.pressPlay': { en: 'Press Play to run the game.', zh: '点击“运行”启动游戏。' },
diff --git a/desktop/src/outliner/OutlinerController.ts b/desktop/src/outliner/OutlinerController.ts
index 8ff76aead..3afef6bbb 100644
--- a/desktop/src/outliner/OutlinerController.ts
+++ b/desktop/src/outliner/OutlinerController.ts
@@ -8,16 +8,15 @@
* drivable by EditorControlSurface / the editor MCP — the panel is a thin
* renderer over this + {@link buildOutlinerItems}.
*
- * Expansion is keyed by stable string ITEM KEYS (`e<id>` for entities, `f:<path>`
- * for folders), so one set covers both row kinds. One store per tree: the edited
- * scene has one, the running world another — their ids come from different
- * spaces (source ids vs realm runtime ids) and must never share an expansion set.
+ * Expansion is keyed by stable string ITEM KEYS (`e<id>` for a document entity,
+ * `l<id>` for one the running game spawned, `f:<path>` for folders), so ONE set
+ * covers every row kind — a row keeps its twist through Play and Stop.
*
- * Self-healing follows the shape of the source. A model announces a removal, so
- * the scene store prunes on `entityRemoved` and resets on `reset`; a snapshot
- * source announces nothing, so the live store prunes with {@link retainIds} on
- * each arriving tree — the running world recycles entity ids, and a recycled id
- * would otherwise inherit a dead entity's expansion.
+ * Self-healing follows the shape of each source. The model announces a removal,
+ * so document keys prune on `entityRemoved` and reset on `reset`; the running
+ * world announces nothing, so its keys prune with {@link retainLiveIds} on each
+ * arriving tree — it recycles entity ids, and a recycled id would otherwise
+ * inherit a dead entity's expansion.
*/
import { create } from 'zustand';
import { SceneModel, SceneModelImpl } from '@/engine/SceneModel';
@@ -70,8 +69,9 @@ interface OutlinerState {
/** Prune a removed entity's key (self-heal on the model's `entityRemoved`). */
dropId: (id: EntityId) => void;
- /** Keep only these entities' keys — the snapshot-source self-heal. */
- retainIds: (ids: ReadonlySet<EntityId>) => void;
+ /** Keep only these realm ids among the SPAWNED keys — the live self-heal.
+ * Document keys are untouched: they answer to the model, not to a snapshot. */
+ retainLiveIds: (ids: ReadonlySet<EntityId>) => void;
/** Reset the view on a scene swap (the model's `reset`). */
reset: () => void;
}
@@ -150,9 +150,9 @@ export function createOutlinerStore(source: OutlinerSource) {
next.delete(k);
return { expanded: next, cursor };
}),
- retainIds: (ids) =>
+ retainLiveIds: (ids) =>
set((s) => {
- const stale = [...s.expanded].filter((k) => k.startsWith('e') && !ids.has(Number(k.slice(1))));
+ const stale = [...s.expanded].filter((k) => k.startsWith('l') && !ids.has(Number(k.slice(1))));
const cursor = s.cursor && stale.includes(s.cursor) ? null : s.cursor;
if (stale.length === 0) return cursor === s.cursor ? s : { cursor };
const next = new Set(s.expanded);
diff --git a/desktop/src/outliner/OutlinerModel.ts b/desktop/src/outliner/OutlinerModel.ts
index ff3411833..a72dfc8fe 100644
--- a/desktop/src/outliner/OutlinerModel.ts
+++ b/desktop/src/outliner/OutlinerModel.ts
@@ -5,8 +5,9 @@
*
* Flattens a SceneData into a render-ordered list of {@link OutlinerItem}s — a
* tagged union of `entity` and `folder` rows — honoring the expansion set (keyed
- * by stable string item keys) + a name filter. The same builder feeds the editor
- * tree and the always-expanded live "Game" tree.
+ * by stable string item keys) + a name filter. One builder, two sources: the
+ * edited scene and the running world, whose rows carry the same keys through
+ * `refOf` so the tree does not reshuffle when the game starts.
*
* Folders are organizational PATHS (orthogonal to the transform `parent`): they
* group **root** entities only; a parented entity always nests under its parent.
@@ -17,6 +18,7 @@
*/
import type { SceneData } from 'esengine';
import type { SceneNode, EntityId } from '@/types';
+import { authoredRef, refKey, type EntityRef } from '@/engine/entityRef';
import { buildSceneTree } from '@/engine/SceneQuery';
import { ROOT_FOLDER, normalizeFolder, folderName, folderParent, folderPrefixes, isFolderUnder } from './folders';
@@ -35,7 +37,11 @@ interface OutlinerItemBase {
}
export interface OutlinerEntityItem extends OutlinerItemBase {
kind: 'entity';
+ /** The id in the world this tree was built from — a source id for the scene
+ * document, a realm handle for the running game. Live ops take this one. */
id: EntityId;
+ /** Who this row IS, independent of which world is showing. */
+ ref: EntityRef;
node: SceneNode;
}
export interface OutlinerFolderItem extends OutlinerItemBase {
@@ -70,8 +76,11 @@ export interface BuildOutlinerOpts {
folders?: readonly string[];
/** Free-text name filter; matches + their ancestors survive (case-insensitive). */
query?: string;
- /** Render every node expanded — the live-game tree, and implicitly while filtering. */
+ /** Render every node expanded — implicitly on while filtering. */
expandAll?: boolean;
+ /** Row identity when the ids are not the document's (the running world).
+ * Absent ⇒ every id is a document source id. */
+ refOf?: (id: EntityId) => EntityRef;
}
/** A parsed search query: bare-word name text + `type:`/`comp:` token filters. */
@@ -143,6 +152,8 @@ export function buildOutlinerItems(data: SceneData | null, opts: BuildOutlinerOp
const expandAll = !!opts.expandAll || active;
const folderOf = opts.folderOf ?? (() => ROOT_FOLDER);
const sort = opts.sort ?? 'manual';
+ const refOf = opts.refOf ?? authoredRef;
+ const keyOf = (id: EntityId): string => refKey(refOf(id));
// Group the shown roots by their folder path, and gather every folder to show:
// each root path's prefixes, plus the scene's explicit folders (only when not
@@ -191,11 +202,12 @@ export function buildOutlinerItems(data: SceneData | null, opts: BuildOutlinerOp
const emitEntity = (node: SceneNode, depth: number, parentKey: string | null, sortKey: number): void => {
const hasChildren = !!node.children?.length;
- const expanded = expandAll || opts.expanded.has(entityKey(node.id));
- out.push({ kind: 'entity', key: entityKey(node.id), id: node.id, node, depth, hasChildren, expanded, parentKey, sortKey });
+ const key = keyOf(node.id);
+ const expanded = expandAll || opts.expanded.has(key);
+ out.push({ kind: 'entity', key, id: node.id, ref: refOf(node.id), node, depth, hasChildren, expanded, parentKey, sortKey });
if (hasChildren && expanded) {
sortNodes(node.children!, sort).forEach((c, i) =>
- emitEntity(c, depth + 1, entityKey(node.id), sort === 'manual' ? (entityIndex.get(c.id) ?? i) : i),
+ emitEntity(c, depth + 1, key, sort === 'manual' ? (entityIndex.get(c.id) ?? i) : i),
);
}
};
@@ -225,14 +237,15 @@ export function buildOutlinerItems(data: SceneData | null, opts: BuildOutlinerOp
}
/** Every expandable key (folders + entity parents) — the auto-expand set for a fresh scene. */
-export function collectExpandableKeys(data: SceneData | null, opts?: Pick<BuildOutlinerOpts, 'folderOf' | 'folders'>): string[] {
+export function collectExpandableKeys(data: SceneData | null, opts?: Pick<BuildOutlinerOpts, 'folderOf' | 'folders' | 'refOf'>): string[] {
const folderOf = opts?.folderOf ?? (() => ROOT_FOLDER);
+ const refOf = opts?.refOf ?? authoredRef;
const out: string[] = [];
const folders = new Set<string>();
const walk = (nodes: SceneNode[]): void => {
for (const n of nodes) {
if (n.children?.length) {
- out.push(entityKey(n.id));
+ out.push(refKey(refOf(n.id)));
walk(n.children);
}
}
diff --git a/desktop/src/outliner/OutlinerRow.tsx b/desktop/src/outliner/OutlinerRow.tsx
index 378c165e4..51dc9b39a 100644
--- a/desktop/src/outliner/OutlinerRow.tsx
+++ b/desktop/src/outliner/OutlinerRow.tsx
@@ -43,6 +43,9 @@ export interface OutlinerRowProps {
agentFresh?: boolean;
/** The pointer is over a transcript row that names this entity. */
agentPeeked?: boolean;
+ /** The running game made this entity; no document row corresponds to it, and
+ * it is gone on Stop. */
+ spawned?: boolean;
/** Keyboard-focus row (shows a focus ring; distinct from selection). */
cursored?: boolean;
/** Lowercased substring to highlight in the name (the search bare text). */
@@ -109,7 +112,8 @@ function OutlinerRowInner(props: OutlinerRowProps) {
`${dropPos === 'after' ? ' drop-after' : ''}` +
`${props.agentTouched ? ' agent-touched' : ''}` +
`${props.agentFresh ? ' agent-fresh' : ''}` +
- `${props.agentPeeked ? ' agent-peek' : ''}`
+ `${props.agentPeeked ? ' agent-peek' : ''}` +
+ `${props.spawned ? ' spawned' : ''}`
}
style={{ paddingLeft: depth * 14 }}
role="treeitem"
diff --git a/desktop/src/outliner/playOutliner.ts b/desktop/src/outliner/playOutliner.ts
deleted file mode 100644
index 750081be9..000000000
--- a/desktop/src/outliner/playOutliner.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file playOutliner.ts — the running world's tree view-state.
- *
- * The second {@link createOutlinerStore} instance, over the live realm snapshot
- * instead of the edited scene. It is a separate store rather than a mode of the
- * editor one because the two speak different id spaces — source ids and realm
- * runtime ids — and one expansion set across both would open rows at random.
- *
- * The live world has no folders (nothing organizes a running game but its own
- * hierarchy), so `folderOf` is always the root.
- */
-import { PlayInspect } from '@/engine/PlayInspect';
-import type { EntityId } from '@/types';
-import { createOutlinerStore } from './OutlinerController';
-import { ROOT_FOLDER } from './folders';
-
-export const usePlayOutliner = createOutlinerStore({
- parentOf: (id) => PlayInspect.getTree()?.entities.find((e) => e.id === id)?.parent ?? null,
- folderOf: () => ROOT_FOLDER,
-});
-
-/**
- * Drop expansion for entities the running world no longer has.
- *
- * Not housekeeping: the ECS recycles entity ids, so without this a bullet
- * spawned into a despawned parent's id arrives already expanded — and rows open
- * on their own while you are reading somewhere else in the tree.
- */
-export function pruneToLiveEntities(ids: ReadonlySet<EntityId>): void {
- usePlayOutliner.getState().retainIds(ids);
-}
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index 62bcab779..86d340cd0 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -61,7 +61,8 @@ import { SceneStore } from '@/engine/SceneStore';
import { SceneQuery, buildEntityInfo, buildInspector } from '@/engine/SceneQuery';
import { SceneModel } from '@/engine/SceneModel';
import { InspectorClipboard } from '@/engine/inspectorClipboard';
-import { SceneCommands, toModelValue } from '@/engine/SceneCommands';
+import { SceneCommands } from '@/engine/SceneCommands';
+import { EntityOps } from '@/engine/entityOps';
import { PlayInspect } from '@/engine/PlayInspect';
import { parseLocaleTable, EasingType, BUILTIN_SHADER_TEMPLATES } from 'esengine';
import type { SceneData, InputMapAsset, ActionType, Binding, LocaleTableAsset, PluralCategory, GearValue, GearTween, MaterialAssetData } from 'esengine';
@@ -974,7 +975,9 @@ function ComponentSection({
// routes edits to the realm (live, reverts on Stop). Structure is read-only here
// (no add/remove/rename of the running game) — just live value debugging.
function GameDetails() {
- const { selectedEntity, selection } = useSyncExternalStore(PlayInspect.subscribe, PlayInspect.getSnapshot);
+ const { selectedEntity } = useSyncExternalStore(PlayInspect.subscribe, PlayInspect.getSnapshot);
+ const selectedRef = useSelection((s) => s.selectedRef);
+ const selection = PlayInspect.liveIdOf(selectedRef);
// Persisted, shared collapse — a folded section stays folded across selections and
// restarts (chrome components default folded via the store's policy).
const collapseMap = useInspectorCollapse((s) => s.explicit);
@@ -986,15 +989,12 @@ function GameDetails() {
const selData = selectedEntity ? ({ entities: [selectedEntity] } as SceneData) : null;
const info = selection != null ? buildEntityInfo(selData, selection) : null;
const inspector = selection != null ? buildInspector(selData, selection) : [];
- const compData = (name: string): Record<string, unknown> =>
- (selectedEntity?.components.find((c) => c.type === name)?.data as Record<string, unknown>) ?? {};
-
return (
<div className="insp">
<div className="game-live">{t('det.playingLive')}</div>
{selection == null || !info ? (
<div className="empty">
- <p>{t('det.gameSelectHint')}</p>
+ <p>{selectedRef == null ? t('det.gameSelectHint') : t('det.gameGone')}</p>
</div>
) : (
<>
@@ -1023,9 +1023,7 @@ function GameDetails() {
extra={decoratorExtra(ctx)}
fieldExtra={(f) => decoratorFieldExtra({ ...ctx, field: f })}
hideFields={decoratorOwnedFields(ctx)}
- write={(key, type, value) =>
- PlayInspect.setField(selection, comp.name, key, toModelValue(compData(comp.name), type, key, value as never))
- }
+ write={(key, type, value) => EntityOps.setField(selectedRef!, comp.name, key, type, value)}
/>
);
})}
@@ -2164,14 +2162,15 @@ function SourceInspector({ source }: { source: InspectSource }) {
);
}
-// Dispatcher: the live game inspector during PIE, the edit inspector otherwise.
-// Both halves of "during PIE" matter — Stop takes the Outliner's world picker
-// away, so a choice that outlived the realm would strand this panel on a world
-// that no longer exists, with nothing on screen able to switch it back.
+// One inspector over whichever world is running the show: while the game is up
+// the selection names a live entity, so this reads and writes that one.
export function Details() {
const isPlaying = useEditorStore((s) => s.isPlaying);
- const inspectWorld = useEditorStore((s) => s.inspectWorld);
- return isPlaying && inspectWorld === 'game' ? <GameDetails /> : <EditorDetails />;
+ const selectedRef = useSelection((s) => s.selectedRef);
+ // An asset selection is a document fact and outranks the running world — it is
+ // the one thing you can still legitimately be inspecting mid-session.
+ const selectedAsset = useSelection((s) => s.selectedAsset);
+ return isPlaying && selectedAsset == null && selectedRef != null ? <GameDetails /> : <EditorDetails />;
}
function EditorDetails() {
diff --git a/desktop/src/panels/GamePanel.tsx b/desktop/src/panels/GamePanel.tsx
index b30d97a89..6ba883a8b 100644
--- a/desktop/src/panels/GamePanel.tsx
+++ b/desktop/src/panels/GamePanel.tsx
@@ -1,11 +1,13 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { useEffect, useRef, useSyncExternalStore } from 'react';
+import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
+import { MousePointer2 } from 'lucide-react';
import { t } from '@/i18n';
import { PlayRealm, PlayRealms } from '@/engine/PlayRealm';
import { useEditorStore } from '@/store/editorStore';
import { useEditorMode } from '@/store/editorModeStore';
import { TargetScreenDropdown, playHostAspectStyle, targetScreenLabel, useProjectScreenPresets } from '@/mode/TargetScreen';
+import { PlayOverlay } from './PlayOverlay';
// The "Game" dock panel: hosts the isolated play-realm iframe (the realm owns the
// element + re-parents it here, so the realm survives panel remounts). The host
@@ -13,7 +15,8 @@ import { TargetScreenDropdown, playHostAspectStyle, targetScreenLabel, useProjec
// status overlay is a separate absolutely-positioned sibling.
//
// The overlay bar carries the target-screen control, so a game can be run at a
-// device's shape instead of at whatever aspect the dock was last dragged to.
+// device's shape instead of at whatever aspect the dock was last dragged to, and
+// the Inspect toggle that hands the pointer to the editor's gizmos.
function overlayFor(snap: { playing: boolean; ready: boolean; error: string | null }): string | null {
return snap.error
@@ -32,6 +35,11 @@ export function GamePanel() {
const device = useEditorMode((s) => s.device);
const orientation = useEditorMode((s) => s.orientation);
const presets = useProjectScreenPresets();
+ // Whether the editor or the game gets the pointer over the frame; see PlayOverlay.
+ const [inspect, setInspect] = useState(false);
+ useEffect(() => {
+ if (!snap.ready) setInspect(false);
+ }, [snap.ready]);
// Only host the realm iframe in 'window' mode — in 'viewport' mode the Viewport
// owns it (one iframe, one mount). Guards against a stale Game tab stealing it.
@@ -52,9 +60,22 @@ export function GamePanel() {
<div className="game-panel__bar">
<TargetScreenDropdown />
{sizeLabel && <span className="game-panel__size">{sizeLabel}</span>}
+ {playTarget === 'window' && snap.ready && (
+ <button
+ type="button"
+ className={`game-panel__inspect${inspect ? ' on' : ''}`}
+ title={t('vp.inspectPlayTip')}
+ onClick={() => setInspect((v) => !v)}
+ >
+ <MousePointer2 size={13} strokeWidth={2} />
+ {t('vp.inspectPlay')}
+ </button>
+ )}
</div>
<div className="game-panel__stage">
- <div className="game-panel__host" style={aspect ?? undefined} ref={hostRef} />
+ <div className="game-panel__host" style={aspect ?? undefined} ref={hostRef}>
+ {playTarget === 'window' && snap.ready && <PlayOverlay interactive={inspect} />}
+ </div>
</div>
{overlay && <div className={`game-panel__overlay${snap.error ? ' error' : ''}`}>{overlay}</div>}
</div>
diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsx
index fac5a64d3..25c05b263 100644
--- a/desktop/src/panels/Outliner.tsx
+++ b/desktop/src/panels/Outliner.tsx
@@ -22,25 +22,25 @@ import { buildOutlinerItems, collectExpandableKeys, entityKey, folderKey, parseQ
import { useOutliner } from '@/outliner/OutlinerController';
import { OutlinerRow } from '@/outliner/OutlinerRow';
import { useAgent, touchedEntities } from '@/store/AgentStore';
-import { usePlayOutliner, pruneToLiveEntities } from '@/outliner/playOutliner';
+import { authoredRef, refKey } from '@/engine/entityRef';
+import { EntityOps } from '@/engine/entityOps';
import { OUTLINER_COLUMNS, TYPE_COLUMN, VIS_COLUMN, type OutlinerColumnContext } from '@/outliner/columns';
import { joinFolder, folderParent, folderName, normalizeFolder, isFolderUnder } from '@/outliner/folders';
import type { EntityId } from '@/types';
import type { LiveVisibility } from '@/engine/playProtocol';
import { createFromSource, type EntitySource } from '@/engine/entitySources';
import { CreatePopover } from '@/components/CreatePopover';
-import { Segmented } from '@/components/Segmented';
import { IconButton } from '@/components/IconButton';
import { useAgentFresh } from '@/outliner/agentFresh';
// Must match .row height in outliner.css — the fixed row size the virtual list windows by.
const ROW_H = 24;
const NO_EXPANSION: ReadonlySet<string> = new Set();
-// Stable props so the memoized game-tree rows don't all re-render on selection.
-const GAME_COLUMNS = [TYPE_COLUMN, VIS_COLUMN];
-const gameOnClick = (item: OutlinerItem) => {
- if (item.kind === 'entity') PlayInspect.select(item.id);
-};
+// While playing, the rows describe a running world: no lock, no prefab bar.
+const LIVE_COLUMNS = [TYPE_COLUMN, VIS_COLUMN];
+// Where entities the game spawned collect — they belong to no authored folder,
+// and a few thousand bullets must not bury the scene you are reading.
+const RUNTIME_FOLDER = 'Runtime';
const SORT_MODE_LABEL: Record<SortMode, string> = {
manual: t('out.sortManual'),
@@ -53,82 +53,6 @@ const COL_ID_LABEL: Record<string, string> = { lock: t('out.colLock'), vis: t('o
const entityIds = (items: OutlinerItem[]): EntityId[] =>
items.filter((i): i is Extract<OutlinerItem, { kind: 'entity' }> => i.kind === 'entity').map((i) => i.id);
-// The live "Game" tree: the running realm, over the same builder, row and
-// virtualization as the editor tree. No folders (nothing organizes a running
-// game but its own hierarchy) and no authoring — what it does offer is the two
-// things you need to READ a world of a few thousand entities: rows that fold,
-// and an eye that turns one off to find out what it was.
-function GameTree() {
- const snapshot = useSyncExternalStore(PlayInspect.subscribe, PlayInspect.getTree);
- const selection = useSyncExternalStore(PlayInspect.subscribe, PlayInspect.getSelection);
- const expanded = usePlayOutliner((s) => s.expanded);
- const query = usePlayOutliner((s) => s.query);
- const setQuery = usePlayOutliner((s) => s.setQuery);
- const toggleExpanded = usePlayOutliner((s) => s.toggleExpanded);
-
- // Keyed on the snapshot REFERENCE, which PlayInspect holds stable unless the
- // tree actually differs — so a steady game rebuilds neither set per sample.
- const liveIds = useMemo(() => new Set((snapshot?.entities ?? []).map((e) => e.id)), [snapshot]);
- const hideable = useMemo(
- () => new Set((snapshot?.entities ?? []).filter((e) => (e as LiveVisibility).hideable).map((e) => e.id)),
- [snapshot],
- );
- useEffect(() => pruneToLiveEntities(liveIds), [liveIds]);
-
- const items = useMemo(() => buildOutlinerItems(snapshot, { expanded, query }), [snapshot, expanded, query]);
- const highlight = useMemo(() => parseQuery(query).text, [query]);
- const columnCtx = useMemo<OutlinerColumnContext>(
- () => ({
- onToggleVisible: (id, visible) => PlayInspect.setVisible(id, visible),
- canToggleVisible: (id) => hideable.has(id),
- }),
- [hideable],
- );
- const expandAll = () => usePlayOutliner.getState().setExpanded(collectExpandableKeys(snapshot));
-
- return (
- <>
- <div className="phead">
- <SearchField placeholder={t('out.searchPlaceholder')} value={query} onChange={setQuery} />
- <IconButton title={t('out.expandAll')} onClick={expandAll}>
- <ChevronsUpDown size={14} strokeWidth={2} />
- </IconButton>
- <IconButton title={t('out.collapseAll')} onClick={() => usePlayOutliner.getState().setExpanded([])}>
- <ChevronsDownUp size={14} strokeWidth={2} />
- </IconButton>
- </div>
- {items.length === 0 ? (
- <div className="pbody">
- <EmptyState
- icon={Search}
- title={liveIds.size === 0 ? t('out.waitingGame') : t('out.noMatch', { query })}
- />
- </div>
- ) : (
- <VirtualTree
- className="pbody"
- role="tree"
- aria-label={t('out.treeGame')}
- items={items}
- rowHeight={ROW_H}
- getKey={(it) => it.key}
- renderRow={(it) => (
- <OutlinerRow
- item={it}
- selected={it.kind === 'entity' && selection === it.id}
- highlight={highlight}
- columns={GAME_COLUMNS}
- columnCtx={columnCtx}
- onToggle={toggleExpanded}
- onClick={gameOnClick}
- />
- )}
- />
- )}
- </>
- );
-}
-
/** Right-click prefab-instance actions (Select Source / Apply / Revert), or [] if
* the entity isn't a prefab instance — the Outliner twin of the Inspector's
* prefab-bar, backed by the same ProjectStore methods. */
@@ -166,10 +90,13 @@ export function Outliner() {
const hiddenColumns = useOutliner((s) => s.hiddenColumns);
const selectedIds = useSelection((s) => s.selectedIds);
const selectedId = useSelection((s) => s.selectedId);
+ const selectedRef = useSelection((s) => s.selectedRef);
const selectedAsset = useSelection((s) => s.selectedAsset);
- const isPlaying = useEditorStore((s) => s.isPlaying);
- const inspectWorld = useEditorStore((s) => s.inspectWorld);
- const setInspectWorld = useEditorStore((s) => s.setInspectWorld);
+ // While the game runs, the tree IS the running world — that is where the
+ // entities are. The document is not a second view to switch to; it is what the
+ // running world was built from, and its rows keep their identity here.
+ const live = useEditorStore((s) => s.isPlaying);
+ const liveTree = useSyncExternalStore(PlayInspect.subscribe, PlayInspect.getTree);
const initRef = useRef(false);
const dragIds = useRef<EntityId[] | null>(null);
const dragFolder = useRef<string | null>(null); // the folder path being dragged (vs entities)
@@ -189,9 +116,25 @@ export function Outliner() {
() => (engine.status === 'ready' ? (SceneModel.current?.entities.length ?? 0) : 0),
[engine.status, structRev],
);
+ // An authored row keeps the folder it was filed under while the game runs; a
+ // spawned one has no document to be filed in, so it collects under Runtime.
+ const liveFolderOf = (id: EntityId): string => {
+ const ref = PlayInspect.refOf(id);
+ return ref.world === 'authored' ? SceneModel.folderOf(ref.src) : RUNTIME_FOLDER;
+ };
const items = useMemo(
- () =>
- engine.status === 'ready'
+ () => {
+ if (live) {
+ return buildOutlinerItems(liveTree, {
+ expanded,
+ query,
+ sort: sortMode,
+ folderOf: liveFolderOf,
+ folders: SceneModel.sceneFolders(),
+ refOf: (id) => PlayInspect.refOf(id),
+ });
+ }
+ return engine.status === 'ready'
? buildOutlinerItems(SceneModel.current, {
expanded,
query,
@@ -200,9 +143,23 @@ export function Outliner() {
folderOrderOf: (p) => SceneModel.folderOrderOf(p),
folders: SceneModel.sceneFolders(),
})
- : [],
- [engine.status, structRev, expanded, query, sortMode],
+ : [];
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [live, liveTree, engine.status, structRev, expanded, query, sortMode],
+ );
+ // Keyed on the snapshot REFERENCE, which PlayInspect holds stable unless the
+ // tree actually differs — so a steady game rebuilds neither set per sample.
+ const liveIds = useMemo(() => new Set((liveTree?.entities ?? []).map((e) => e.id)), [liveTree]);
+ const hideable = useMemo(
+ () => new Set((liveTree?.entities ?? []).filter((e) => (e as LiveVisibility).hideable).map((e) => e.id)),
+ [liveTree],
);
+ // Stop empties this too, so a spawned row's expansion cannot outlive the realm
+ // and greet a recycled handle already open on the next Play.
+ useEffect(() => {
+ useOutliner.getState().retainLiveIds(live ? liveIds : new Set());
+ }, [live, liveIds]);
const flatIds = useMemo(() => entityIds(items), [items]);
const highlight = useMemo(() => parseQuery(query).text, [query]);
// What the agent changed, and what the pointer is over in its transcript. The
@@ -218,14 +175,25 @@ export function Outliner() {
// elsewhere in the tree arrives with no more emphasis than one from four
// turns ago. So the arrival gets its own moment, and then stops.
const agentFresh = useAgentFresh(agentTouched);
- const activeColumns = useMemo(() => OUTLINER_COLUMNS.filter((c) => !hiddenColumns.has(c.id)), [hiddenColumns]);
+ const activeColumns = useMemo(
+ () => (live ? LIVE_COLUMNS : OUTLINER_COLUMNS.filter((c) => !hiddenColumns.has(c.id))),
+ [live, hiddenColumns],
+ );
+ // The eye means one thing and lands in whichever world is showing — which is
+ // the op layer's job, not this panel's.
const columnCtx = useMemo<OutlinerColumnContext>(
- () => ({
- onToggleVisible: (id, visible) => SceneCommands.setEntityVisible(id, visible),
- onToggleLock: (id, locked) => SceneCommands.setEntityLocked(id, locked),
- isPrefab: (id) => SceneModel.prefabTag(id) != null,
- }),
- [],
+ () =>
+ live
+ ? {
+ onToggleVisible: (id, visible) => EntityOps.setVisible(PlayInspect.refOf(id), visible),
+ canToggleVisible: (id) => hideable.has(id),
+ }
+ : {
+ onToggleVisible: (id, visible) => EntityOps.setVisible(authoredRef(id), visible),
+ onToggleLock: (id, locked) => SceneCommands.setEntityLocked(id, locked),
+ isPrefab: (id) => SceneModel.prefabTag(id) != null,
+ },
+ [live, hideable],
);
// A scene swap resets the model ('reset' event). This panel is a persistent dock
@@ -259,25 +227,27 @@ export function Outliner() {
// Reveal-on-select: when the primary selection changes (e.g. a viewport pick),
// expand its ancestors + folder and scroll it into view. If it isn't in the flat
// list yet (ancestors collapsed), expand once — items rebuild and this re-runs.
- const handledSel = useRef<EntityId | null>(null);
- const expandedSel = useRef<EntityId | null>(null);
+ // Keyed by ref, so a row found again after Play is the row you had selected.
+ const selKey = selectedRef ? refKey(selectedRef) : null;
+ const handledSel = useRef<string | null>(null);
+ const expandedSel = useRef<string | null>(null);
useEffect(() => {
- if (selectedId == null) {
+ if (selKey == null) {
handledSel.current = expandedSel.current = null;
return;
}
- if (handledSel.current === selectedId) return;
- const idx = items.findIndex((i) => i.kind === 'entity' && i.id === selectedId);
+ if (handledSel.current === selKey) return;
+ const idx = items.findIndex((i) => i.key === selKey);
if (idx >= 0) {
- handledSel.current = selectedId;
+ handledSel.current = selKey;
expandedSel.current = null;
- useOutliner.getState().setCursor(entityKey(selectedId));
+ useOutliner.getState().setCursor(selKey);
scrollToIndex(idx);
- } else if (expandedSel.current !== selectedId) {
- expandedSel.current = selectedId; // attempt expansion once (avoids a loop when filtered out)
- useOutliner.getState().revealEntity(selectedId);
+ } else if (expandedSel.current !== selKey) {
+ expandedSel.current = selKey; // attempt expansion once (avoids a loop when filtered out)
+ if (selectedId != null) useOutliner.getState().revealEntity(selectedId);
}
- }, [selectedId, items]);
+ }, [selKey, selectedId, items]);
// — Keyboard navigation (↑↓ move · ←→ collapse/expand/jump · Enter toggle · F2/Del) —
const cursorItem = (): OutlinerItem | null => items.find((i) => i.key === cursor) ?? null;
@@ -287,7 +257,7 @@ export function Outliner() {
useOutliner.getState().setCursor(it.key);
if (it.kind === 'entity') {
useOutliner.getState().selectFolder(null);
- select(it.id);
+ useSelection.getState().selectRef(it.ref);
} else {
useOutliner.getState().selectFolder(it.path);
useSelection.getState().select(null);
@@ -346,12 +316,12 @@ export function Outliner() {
}
case 'F2': {
e.preventDefault();
- if (cursor) setRenaming(cursor);
+ if (cursor && !live) setRenaming(cursor);
break;
}
case 'Delete':
case 'Backspace': {
- const sel = [...useSelection.getState().selectedIds];
+ const sel = live ? [] : [...useSelection.getState().selectedIds];
if (sel.length) {
e.preventDefault();
SceneCommands.deleteEntities(sel);
@@ -392,8 +362,15 @@ export function Outliner() {
return;
}
useOutliner.getState().selectFolder(null); // an entity selection clears the folder one
- const id = item.id;
const store = useSelection.getState();
+ // The running world's rows select one at a time: the multi-selection exists
+ // for the commands that edit the document, and those are off while playing.
+ if (live) {
+ store.selectRef(item.ref);
+ PlayInspect.refresh();
+ return;
+ }
+ const id = item.id;
if (e.metaKey || e.ctrlKey) {
store.toggleSelect(id);
} else if (e.shiftKey && store.selectedId != null) {
@@ -411,17 +388,21 @@ export function Outliner() {
const onContextMenu = (e: React.MouseEvent, item: OutlinerItem) => {
e.preventDefault();
e.stopPropagation(); // a row menu pre-empts the empty-space menu on the container
+ if (live) return; // every row action writes the document; the game owns it now
if (item.kind === 'entity' && !useSelection.getState().selectedIds.has(item.id)) select(item.id);
setCtx({ x: e.clientX, y: e.clientY, item });
};
// Right-click on empty space (below the rows / no entities) → the scene menu.
const onBodyContextMenu = (e: React.MouseEvent) => {
e.preventDefault();
+ if (live) return;
setCtx({ x: e.clientX, y: e.clientY, item: null });
};
const expandAll = () =>
useOutliner.getState().setExpanded(
- collectExpandableKeys(SceneModel.current, { folderOf: (id) => SceneModel.folderOf(id), folders: SceneModel.sceneFolders() }),
+ live
+ ? collectExpandableKeys(liveTree, { folderOf: liveFolderOf, refOf: (id) => PlayInspect.refOf(id) })
+ : collectExpandableKeys(SceneModel.current, { folderOf: (id) => SceneModel.folderOf(id), folders: SceneModel.sceneFolders() }),
);
const onStartRename = (item: OutlinerItem) => setRenaming(item.key);
@@ -679,12 +660,6 @@ export function Outliner() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ctx]);
- // While playing, a world picker switches the outliner (+ Details) between the
- // edit scene and the live running game. Gated on `isPlaying` as well as the
- // choice: Stop takes the picker away, and a mode you can no longer leave would
- // strand the panel on a world that no longer exists.
- const gameMode = isPlaying && inspectWorld === 'game';
-
// Stable handlers (latest-ref) so the memoized rows skip on a selection change.
const rowFns = {
onRowClick, onContextMenu, onStartRename, commitRename, onDragStartRow, onDragOverRow, onDropRow,
@@ -709,16 +684,25 @@ export function Outliner() {
const renderRow = (it: OutlinerItem) => (
<OutlinerRow
item={it}
- selected={it.kind === 'folder' ? selectedFolder === it.path : selectedIds.has(it.id)}
+ selected={
+ it.kind === 'folder'
+ ? selectedFolder === it.path
+ : live
+ ? it.key === selKey
+ : selectedIds.has(it.id)
+ }
cursored={cursor === it.key}
highlight={highlight}
- agentTouched={it.kind === 'entity' && agentTouched.has(it.id)}
- agentFresh={it.kind === 'entity' && agentFresh.has(it.id)}
- agentPeeked={it.kind === 'entity' && agentPeeked.includes(it.id)}
+ // The document's marks — an agent's edits, a prefab's role — are facts
+ // about rows in the document, not about entities in a running game.
+ agentTouched={!live && it.kind === 'entity' && agentTouched.has(it.id)}
+ agentFresh={!live && it.kind === 'entity' && agentFresh.has(it.id)}
+ agentPeeked={!live && it.kind === 'entity' && agentPeeked.includes(it.id)}
+ spawned={it.kind === 'entity' && it.ref.world === 'spawned'}
renaming={renaming === it.key}
dropPos={drop?.key === it.key ? drop.pos : undefined}
prefabRole={
- it.kind === 'entity'
+ !live && it.kind === 'entity'
? SceneModel.isInstanceRoot(it.id)
? 'root'
: SceneModel.prefabTag(it.id) != null
@@ -728,7 +712,7 @@ export function Outliner() {
}
columns={activeColumns}
columnCtx={columnCtx}
- draggable
+ draggable={!live}
onToggle={toggleExpanded}
onClick={H.onClick}
onContextMenu={H.onContextMenu}
@@ -741,110 +725,111 @@ export function Outliner() {
/>
);
+ const empty = live ? liveIds.size === 0 : sceneCount === 0;
return (
<div className="panel">
- {isPlaying && (
- <div className="world-pick">
- <Segmented
- grow
- ariaLabel={t('out.inspectedWorld')}
- value={gameMode ? 'game' : 'editor'}
- options={[
- { value: 'editor', label: t('out.worldEditor') },
- { value: 'game', label: t('out.worldGame') },
- ]}
- onChange={(v) => setInspectWorld(v)}
- />
- </div>
- )}
- {gameMode ? (
- <GameTree />
- ) : (
- <>
- <div className="phead">
- <SearchField placeholder={t('out.searchPlaceholder')} value={query} onChange={setQuery} />
- <IconButton
- active={sortMode !== 'manual'}
- title={t('out.sortLabel', { mode: SORT_MODE_LABEL[sortMode] })}
- onClick={(e) => {
- const r = e.currentTarget.getBoundingClientRect();
- setSortMenu({ x: r.left, y: r.bottom + 2 });
- }}
- >
- <ArrowDownUp size={14} strokeWidth={2} />
+ <div className="phead">
+ <SearchField placeholder={t('out.searchPlaceholder')} value={query} onChange={setQuery} />
+ <IconButton
+ active={sortMode !== 'manual'}
+ title={t('out.sortLabel', { mode: SORT_MODE_LABEL[sortMode] })}
+ onClick={(e) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ setSortMenu({ x: r.left, y: r.bottom + 2 });
+ }}
+ >
+ <ArrowDownUp size={14} strokeWidth={2} />
+ </IconButton>
+ {live ? (
+ // A running world is read, not authored: what it needs is a way to
+ // fold a few thousand rows down to the ones being looked at.
+ <>
+ <IconButton title={t('out.expandAll')} onClick={expandAll}>
+ <ChevronsUpDown size={14} strokeWidth={2} />
</IconButton>
+ <IconButton title={t('out.collapseAll')} onClick={() => useOutliner.getState().setExpanded([])}>
+ <ChevronsDownUp size={14} strokeWidth={2} />
+ </IconButton>
+ </>
+ ) : (
+ <>
<IconButton title={t('out.newFolderTip')} onClick={() => newFolder('', null)}>
<FolderPlus size={15} strokeWidth={2} />
</IconButton>
<IconButton title={t('out.addEntityTip')} onClick={() => setCreateFor({ parent: null })}>
<Plus size={15} strokeWidth={2} />
</IconButton>
- </div>
- {sceneCount > 0 && (
- <div
- className="outliner-cols"
- title={t('out.columnsTip')}
- onContextMenu={(e) => {
- e.preventDefault();
- setColsMenu({ x: e.clientX, y: e.clientY });
- }}
- >
- <span className="c-name">{t('out.colName')}</span>
- {activeColumns.map((col) => (
- <span key={col.id} className="c-col" data-col={col.id} style={{ width: col.width }}>
- {col.header}
- </span>
- ))}
- </div>
- )}
- {sceneCount === 0 ? (
- <div className="pbody" onDragOver={onBodyDragOver} onDrop={onBodyDrop} onContextMenu={onBodyContextMenu}>
- <EmptyState
- icon={Boxes}
- title={engine.status === 'ready' ? t('out.emptyScene') : t('out.waitingEngine')}
- hint={engine.status === 'ready' ? t('out.emptyHint') : undefined}
- >
- {engine.status === 'ready' && (
- <button type="button" className="empty-state__action" onClick={() => setCreateFor({ parent: null })}>
- <Plus size={14} /> {t('out.addEntity')}
- </button>
- )}
- </EmptyState>
- </div>
- ) : items.length === 0 ? (
- <div className="pbody" onDragOver={onBodyDragOver} onDrop={onBodyDrop} onContextMenu={onBodyContextMenu}>
- <EmptyState icon={Search} title={t('out.noMatch', { query })} />
- </div>
+ </>
+ )}
+ </div>
+ {live && <div className="out-live">{t('out.liveWorld')}</div>}
+ {!empty && (
+ <div
+ className="outliner-cols"
+ title={live ? undefined : t('out.columnsTip')}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ if (!live) setColsMenu({ x: e.clientX, y: e.clientY });
+ }}
+ >
+ <span className="c-name">{t('out.colName')}</span>
+ {activeColumns.map((col) => (
+ <span key={col.id} className="c-col" data-col={col.id} style={{ width: col.width }}>
+ {col.header}
+ </span>
+ ))}
+ </div>
+ )}
+ {empty ? (
+ <div className="pbody" onDragOver={onBodyDragOver} onDrop={onBodyDrop} onContextMenu={onBodyContextMenu}>
+ {live ? (
+ <EmptyState icon={Search} title={t('out.waitingGame')} />
) : (
- <VirtualTree
- className="pbody"
- tabIndex={0}
- role="tree"
- aria-label={t('out.tree')}
- aria-multiselectable
- items={items}
- rowHeight={ROW_H}
- getKey={(it) => it.key}
- renderRow={renderRow}
- scrollToIndex={scrollTo.index}
- scrollNonce={scrollTo.nonce}
- onKeyDown={onKeyDown}
- onDragOver={onBodyDragOver}
- onDrop={onBodyDrop}
- onContextMenu={onBodyContextMenu}
- />
+ <EmptyState
+ icon={Boxes}
+ title={engine.status === 'ready' ? t('out.emptyScene') : t('out.waitingEngine')}
+ hint={engine.status === 'ready' ? t('out.emptyHint') : undefined}
+ >
+ {engine.status === 'ready' && (
+ <button type="button" className="empty-state__action" onClick={() => setCreateFor({ parent: null })}>
+ <Plus size={14} /> {t('out.addEntity')}
+ </button>
+ )}
+ </EmptyState>
)}
- </>
+ </div>
+ ) : items.length === 0 ? (
+ <div className="pbody" onDragOver={onBodyDragOver} onDrop={onBodyDrop} onContextMenu={onBodyContextMenu}>
+ <EmptyState icon={Search} title={t('out.noMatch', { query })} />
+ </div>
+ ) : (
+ <VirtualTree
+ className="pbody"
+ tabIndex={0}
+ role="tree"
+ aria-label={live ? t('out.treeGame') : t('out.tree')}
+ aria-multiselectable={!live}
+ items={items}
+ rowHeight={ROW_H}
+ getKey={(it) => it.key}
+ renderRow={renderRow}
+ scrollToIndex={scrollTo.index}
+ scrollNonce={scrollTo.nonce}
+ onKeyDown={onKeyDown}
+ onDragOver={onBodyDragOver}
+ onDrop={onBodyDrop}
+ onContextMenu={onBodyContextMenu}
+ />
)}
- {ctx && !gameMode && <ContextMenu x={ctx.x} y={ctx.y} items={ctxItems} onClose={() => setCtx(null)} />}
+ {ctx && !live && <ContextMenu x={ctx.x} y={ctx.y} items={ctxItems} onClose={() => setCtx(null)} />}
{createFor && (
<CreatePopover
onClose={() => setCreateFor(null)}
onPick={(t) => createTemplate(t, createFor.parent)}
/>
)}
- {sortMenu && !gameMode && (
+ {sortMenu && (
<ContextMenu
x={sortMenu.x}
y={sortMenu.y}
@@ -855,7 +840,7 @@ export function Outliner() {
}))}
/>
)}
- {colsMenu && !gameMode && (
+ {colsMenu && !live && (
<ContextMenu
x={colsMenu.x}
y={colsMenu.y}
diff --git a/desktop/src/panels/PlayOverlay.tsx b/desktop/src/panels/PlayOverlay.tsx
new file mode 100644
index 000000000..dacb9e567
--- /dev/null
+++ b/desktop/src/panels/PlayOverlay.tsx
@@ -0,0 +1,171 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file PlayOverlay.tsx — the editor's gizmos, over the running game.
+ *
+ * The game draws into an iframe the editor cannot read, so this draws nothing of
+ * the game: it draws where the REALM says the selection is, in points normalized
+ * to the realm's own canvas, which this scales into the host box. Every question
+ * about the frame — where a thing is, what is at a point, where a drag lands —
+ * goes to the side holding the camera.
+ *
+ * Pointer events belong to the game by default; a running game you cannot click
+ * is not a running game. `interactive` is the editor taking them, for as long as
+ * the user asks for it.
+ */
+import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
+import { PlayInspect } from '@/engine/PlayInspect';
+import { PlayRealm } from '@/engine/PlayRealm';
+import { EntityOps } from '@/engine/entityOps';
+import { useSelection } from '@/store/selectionStore';
+import type { CanvasPoint, PlayOverlayBox } from '@/engine/playProtocol';
+
+/** Half-size of the origin handle, in CSS px. */
+const HANDLE = 5;
+/** Pointer travel before a press becomes a drag rather than a click-to-select. */
+const DRAG_SLOP = 3;
+
+interface Props {
+ /** Whether the editor, rather than the game, receives pointer events here. */
+ interactive: boolean;
+}
+
+/** Normalized canvas point → CSS px within a box of `w`×`h`. */
+const toPx = (p: CanvasPoint, w: number, h: number): [number, number] => [p.x * w, p.y * h];
+
+/** Whether a press at `p` landed ON the selection: inside its outline, or within
+ * reach of the origin handle for something that has no outline to speak of. */
+function grabbed(box: PlayOverlayBox, p: CanvasPoint, size: { w: number; h: number }): boolean {
+ const [ox, oy] = toPx(box.origin, size.w, size.h);
+ const [px, py] = toPx(p, size.w, size.h);
+ if (Math.hypot(px - ox, py - oy) <= HANDLE * 2) return true;
+ if (box.corners.length !== 4) return false;
+ const poly = box.corners.map((c) => toPx(c, size.w, size.h));
+ let inside = false;
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
+ const [xi, yi] = poly[i];
+ const [xj, yj] = poly[j];
+ if ((yi > py) !== (yj > py) && px < ((xj - xi) * (py - yi)) / (yj - yi) + xi) inside = !inside;
+ }
+ return inside;
+}
+
+export function PlayOverlay({ interactive }: Props) {
+ const overlay = useSyncExternalStore(PlayInspect.subscribe, PlayInspect.getOverlay);
+ const selectedRef = useSelection((s) => s.selectedRef);
+ const hostRef = useRef<HTMLDivElement>(null);
+ const [size, setSize] = useState({ w: 0, h: 0 });
+ // The grab offset in normalized canvas units, so the thing does not jump its
+ // origin to the cursor the moment it is picked up.
+ const drag = useRef<{
+ dx: number; dy: number; axis?: 'x' | 'y'; moved: boolean;
+ /** The press did not land on the selection, so it can only end in a pick. */
+ pickOnly: boolean;
+ from: { x: number; y: number };
+ } | null>(null);
+
+ useEffect(() => {
+ const el = hostRef.current;
+ if (!el) return;
+ const measure = () => setSize({ w: el.clientWidth, h: el.clientHeight });
+ measure();
+ const ro = new ResizeObserver(measure);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, []);
+
+ const pointOf = (e: React.PointerEvent): CanvasPoint => {
+ const box = hostRef.current?.getBoundingClientRect();
+ if (!box || box.width === 0 || box.height === 0) return { x: 0, y: 0 };
+ return { x: (e.clientX - box.left) / box.width, y: (e.clientY - box.top) / box.height };
+ };
+
+ const onPointerDown = (e: React.PointerEvent) => {
+ if (!interactive || e.button !== 0) return;
+ e.preventDefault();
+ (e.target as Element).setPointerCapture?.(e.pointerId);
+ const p = pointOf(e);
+ const axis = (e.target as HTMLElement).dataset?.axis as 'x' | 'y' | undefined;
+ // A press only picks the selection UP if it landed on it — on a handle, or
+ // inside the outline. Anywhere else is a click that selects something new,
+ // not an invisible grip on whatever happened to be selected.
+ const onIt = axis != null || (overlay != null && grabbed(overlay, p, size));
+ if (!onIt) {
+ drag.current = { dx: 0, dy: 0, moved: false, pickOnly: true, from: { x: e.clientX, y: e.clientY } };
+ return;
+ }
+ drag.current = {
+ dx: overlay ? overlay.origin.x - p.x : 0,
+ dy: overlay ? overlay.origin.y - p.y : 0,
+ axis,
+ moved: false,
+ pickOnly: false,
+ from: { x: e.clientX, y: e.clientY },
+ };
+ };
+
+ const onPointerMove = (e: React.PointerEvent) => {
+ const d = drag.current;
+ if (!interactive || !d || d.pickOnly) return;
+ if (!d.moved) {
+ if (Math.hypot(e.clientX - d.from.x, e.clientY - d.from.y) < DRAG_SLOP) return;
+ d.moved = true;
+ }
+ if (selectedRef == null) return;
+ const p = pointOf(e);
+ EntityOps.moveToPoint(selectedRef, { canvas: { x: p.x + d.dx, y: p.y + d.dy } }, d.axis);
+ };
+
+ const onPointerUp = (e: React.PointerEvent) => {
+ const d = drag.current;
+ drag.current = null;
+ if (!interactive || !d) return;
+ (e.target as Element).releasePointerCapture?.(e.pointerId);
+ // A press that never moved is a selection, and the realm is the one that can
+ // say what is under the pointer.
+ if (d.moved) return;
+ const p = pointOf(e);
+ void PlayRealm.pick(p.x, p.y).then((id) => {
+ useSelection.getState().selectRef(id == null ? null : PlayInspect.refOf(id));
+ PlayInspect.refresh();
+ });
+ };
+
+ const box = overlay && size.w > 0 ? overlay : null;
+ const origin = box ? toPx(box.origin, size.w, size.h) : null;
+ const outline = box && box.corners.length === 4
+ ? box.corners.map((c) => toPx(c, size.w, size.h).join(',')).join(' ')
+ : null;
+
+ return (
+ <div
+ ref={hostRef}
+ className={`play-ov${interactive ? ' interactive' : ''}`}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={() => { drag.current = null; }}
+ >
+ {origin && (
+ <svg className="play-ov__svg" width={size.w} height={size.h} aria-hidden="true">
+ {outline && <polygon className="play-ov__box" points={outline} />}
+ {interactive && (
+ <>
+ <line className="play-ov__axis x" x1={origin[0]} y1={origin[1]} x2={origin[0] + 44} y2={origin[1]} />
+ <line className="play-ov__axis y" x1={origin[0]} y1={origin[1]} x2={origin[0]} y2={origin[1] - 44} />
+ <rect className="play-ov__grab x" data-axis="x" x={origin[0] + 30} y={origin[1] - 6} width={16} height={12} />
+ <rect className="play-ov__grab y" data-axis="y" x={origin[0] - 6} y={origin[1] - 46} width={12} height={16} />
+ </>
+ )}
+ <rect
+ className="play-ov__origin"
+ x={origin[0] - HANDLE}
+ y={origin[1] - HANDLE}
+ width={HANDLE * 2}
+ height={HANDLE * 2}
+ />
+ </svg>
+ )}
+ </div>
+ );
+}
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 966f1f7b5..abdd9043f 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -44,6 +44,7 @@ import { PluginOverlays } from '@/plugins/PluginOverlays';
import { Perf } from '@/components/Perf';
import { OvDropdown, DdRadio } from '@/components/OverlayMenu';
import { TargetScreenDropdown, playHostAspectStyle } from '@/mode/TargetScreen';
+import { PlayOverlay } from './PlayOverlay';
import { usePanelWindow, eventWindow } from '@/components/PanelWindow';
import type { ToolMode, EntityId } from '@/types';
import { resolveActiveTool, type EditorTool, type ToolContext, type PointerInput } from '@/tools';
@@ -1018,6 +1019,13 @@ export function Viewport() {
// to the new window, so PlayRealm must re-bind its message listener to that window
// (attach does), or the realm→editor handshake is stranded on the old one.
const playInViewport = isPlaying && playTarget === 'viewport';
+ // Whether the editor or the game gets the pointer over the running frame. Off
+ // by default: a game you cannot click is not a game. Cleared on Stop so the
+ // next session starts playable.
+ const [inspectPlay, setInspectPlay] = useState(false);
+ useEffect(() => {
+ if (!playInViewport) setInspectPlay(false);
+ }, [playInViewport]);
useEffect(() => {
if (playTarget !== 'viewport') return;
const host = playHostRef.current;
@@ -2529,8 +2537,23 @@ export function Viewport() {
className="viewport__play-host"
style={playHostAspectStyle(device, orientation, projectState?.screenPresets) ?? undefined}
ref={playHostRef}
- />
+ >
+ {/* Inside the host box, so it is exactly the rect the realm's canvas
+ fills — the overlay's coordinates are normalized to that canvas. */}
+ {playInViewport && realm.ready && <PlayOverlay interactive={inspectPlay} />}
+ </div>
</div>
+ {playInViewport && realm.ready && (
+ <button
+ type="button"
+ className={`viewport__inspect${inspectPlay ? ' on' : ''}`}
+ title={t('vp.inspectPlayTip')}
+ onClick={() => setInspectPlay((v) => !v)}
+ >
+ <MousePointer2 size={13} strokeWidth={2} />
+ {t('vp.inspectPlay')}
+ </button>
+ )}
{playInViewport && (!realm.ready || realm.error) && (
<div className={`viewport__play-status${realm.error ? ' error' : ''}`}>
{realm.error ? t('vp.playFailed', { error: realm.error }) : t('vp.startingGame')}
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index 51177caba..a176f829f 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -14,12 +14,13 @@
* Everything is same-origin estella:// (host, sdk, bundle, wasm, assets),
* sidestepping the custom-scheme cross-fetch ban.
*/
-import { uiPickWorld, uiWorldToScreen, createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations, Net, MessagePortTransport, Assets, Ads, createMockAdProvider, Leaderboard, createLocalLeaderboard, registerPackagedSideModules, Input, inputEventCallbacks, isEntityVisible, setEntityVisible, hasVisibility, takeCensus } from 'esengine';
+import { uiPickWorld, uiWorldToScreen, createWebApp, setEditorMode, setPlayMode, enableSceneOrigins, sceneOriginOf, entityWorldBox, entityBoxCorners, CameraView, layerOrderOf, quaternionToAngle2D, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations, Net, MessagePortTransport, Assets, Ads, createMockAdProvider, Leaderboard, createLocalLeaderboard, registerPackagedSideModules, Input, inputEventCallbacks, isEntityVisible, setEntityVisible, hasVisibility, takeCensus } from 'esengine';
import type { App, SceneData, InputState, UICameraData } from 'esengine';
import type { ESEngineModule } from 'esengine/wasm';
import { PLAY_PROTOCOL_VERSION } from './engine/playProtocol';
-import type { PlayOutbound, PlayInbound, LiveVisibility } from './engine/playProtocol';
+import type { PlayOutbound, PlayInbound, LiveVisibility, CanvasPoint, PlayOverlayBox } from './engine/playProtocol';
import { translateAssetHandles, projectRelative } from './engine/liveAssetRefs';
+import { pointInOBB, rankPickCandidates, worldToLocal2D, type PickCandidate } from '@/engine/viewportMath';
import {
inspectEntity, findEntities, readResources, readSystems,
type Realm, type EntityFilter,
@@ -184,7 +185,124 @@ function realm(): Realm {
};
}
-function liveSnapshot(world: App['world'], selectedId: number | null, withTree: boolean): { tree: SceneData | null; selected: LiveEntity | null } {
+// — Where things are on the frame this realm drew —
+// Points cross the boundary normalized to THIS canvas; `worldToScreen` answers
+// in framebuffer pixels with y up.
+
+const normalizePoint = (glX: number, glY: number): CanvasPoint => ({
+ x: canvas.width > 0 ? glX / canvas.width : 0,
+ y: canvas.height > 0 ? 1 - glY / canvas.height : 0,
+});
+const denormalizePoint = (nx: number, ny: number): { x: number; y: number } => ({
+ x: nx * canvas.width,
+ y: (1 - ny) * canvas.height,
+});
+
+/** Where `entity` is drawn, for the editor's overlay. Null when it has no place
+ * on screen — no transform, a UI node, or no camera to project through. */
+function overlayBoxOf(world: App['world'], entity: number): PlayOverlayBox | null {
+ const view = app?.getResource(CameraView);
+ const transformDef = getComponent('Transform');
+ if (!view || !transformDef) return null;
+ const t = world.tryGet(entity as never, transformDef) as { worldPosition?: { x: number; y: number; z?: number } } | null;
+ const at = t?.worldPosition;
+ if (!at) return null;
+ const z = at.z ?? 0;
+ const originScreen = view.worldToScreen(at.x, at.y, z);
+ if (!originScreen) return null;
+ // No box is not no overlay: an empty or a camera still has an origin to put a
+ // move gizmo on, it just has no outline to draw.
+ const box = entityWorldBox(world, entity as never);
+ const corners = box
+ ? entityBoxCorners(box)
+ .map((c) => view.worldToScreen(c.x, c.y, z))
+ .filter((p): p is { x: number; y: number } => p !== null)
+ .map((p) => normalizePoint(p.x, p.y))
+ : [];
+ return { corners: corners.length === 4 ? corners : [], origin: normalizePoint(originScreen.x, originScreen.y) };
+}
+
+/** The topmost entity at a canvas point, ranked the way the frame stacked it. */
+function pickAt(world: App['world'], nx: number, ny: number): number | null {
+ const view = app?.getResource(CameraView);
+ const transformDef = getComponent('Transform');
+ const spriteDef = getComponent('Sprite');
+ if (!view || !transformDef) return null;
+ const gl = denormalizePoint(nx, ny);
+ const hits: PickCandidate<number>[] = [];
+ for (const e of world.getAllEntities()) {
+ const id = e as never as number;
+ const t = world.tryGet(e, transformDef) as { worldPosition?: { x: number; y: number; z?: number } } | null;
+ if (!t?.worldPosition) continue;
+ // Each candidate is tested on ITS OWN plane: under a perspective camera one
+ // shared world point is where a sprite's shadow falls, not where it is drawn.
+ const wp = view.screenToWorld(gl.x, gl.y, t.worldPosition.z ?? 0);
+ const box = entityWorldBox(world, e);
+ if (!wp || !box || !pointInOBB(wp.x, wp.y, box)) continue;
+ const sprite = spriteDef ? (world.tryGet(e, spriteDef) as { layer?: number } | null) : null;
+ const layer = sprite?.layer ?? 0;
+ hits.push({
+ entity: id,
+ index: hits.length,
+ rank: {
+ layer,
+ order: layerOrderOf(layer, lastInit?.ySortLayers ?? 0, lastInit?.depthLayers ?? 0),
+ worldY: t.worldPosition.y,
+ worldZ: t.worldPosition.z ?? 0,
+ },
+ });
+ }
+ return rankPickCandidates(hits)[0] ?? null;
+}
+
+/**
+ * Put an entity's origin at a canvas point. `Transform.position` is
+ * parent-local, so a parented entity's world target is re-expressed in its
+ * parent's live world frame — the same rule the editor's own move obeys.
+ */
+function dragTo(world: App['world'], entity: number, nx: number, ny: number, axis?: 'x' | 'y'): void {
+ const view = app?.getResource(CameraView);
+ const transformDef = getComponent('Transform');
+ const parentDef = getComponent('Parent');
+ if (!view || !transformDef || !world.valid(entity as never)) return;
+ const t = world.tryGet(entity as never, transformDef) as
+ { position?: { x: number; y: number; z?: number }; worldPosition?: { x: number; y: number; z?: number } } | null;
+ if (!t?.worldPosition || !t.position) return;
+ const z = t.worldPosition.z ?? 0;
+ const gl = denormalizePoint(nx, ny);
+ const target = view.screenToWorld(gl.x, gl.y, z);
+ if (!target) return;
+ // The lock resolves HERE, in world space, so a rotated camera cannot turn
+ // "along X" into a diagonal.
+ const wantX = axis === 'y' ? t.worldPosition.x : target.x;
+ const wantY = axis === 'x' ? t.worldPosition.y : target.y;
+
+ // `position` is parent-local, so the world target is re-expressed in the
+ // parent's live frame — through the same inverse-TRS the editor's own move
+ // uses, because a parent's rotation and scale are part of the answer.
+ const parent = parentDef ? (world.tryGet(entity as never, parentDef) as { entity?: number } | null) : null;
+ const pt = parent?.entity !== undefined && world.valid(parent.entity as never)
+ ? (world.tryGet(parent.entity as never, transformDef) as {
+ worldPosition?: { x: number; y: number };
+ worldRotation?: { z: number; w: number };
+ worldScale?: { x: number; y: number };
+ } | null)
+ : null;
+ const local = pt?.worldPosition
+ ? worldToLocal2D(wantX, wantY, {
+ x: pt.worldPosition.x,
+ y: pt.worldPosition.y,
+ rot: quaternionToAngle2D(pt.worldRotation?.z ?? 0, pt.worldRotation?.w ?? 1),
+ sx: pt.worldScale?.x ?? 1,
+ sy: pt.worldScale?.y ?? 1,
+ })
+ : { x: wantX, y: wantY };
+ const data = { ...(world.get(entity as never, transformDef) as Record<string, unknown>) };
+ data.position = { x: local.x, y: local.y, z: t.position.z ?? 0 };
+ world.set(entity as never, transformDef, data as never);
+}
+
+function liveSnapshot(world: App['world'], selectedId: number | null, withTree: boolean): { tree: SceneData | null; selected: LiveEntity | null; overlay: PlayOverlayBox | null } {
const nameDef = getComponent('Name');
const parentDef = getComponent('Parent');
const all = world.getAllEntities();
@@ -210,6 +328,17 @@ function liveSnapshot(world: App['world'], selectedId: number | null, withTree:
? { hideable: true, hidden: !isEntityVisible(world, e as never) }
: {};
+ // The document id this entity was loaded from — the editor's half of its
+ // identity. Only the ENTRY scene's entities have one the editor can use: it is
+ // the document open in the editor, and another scene's ids mean nothing there.
+ const ownerDef = getComponent('SceneOwner');
+ const entryScene = lastInit?.entrySceneName ?? '__play';
+ const srcOf = (e: number): number | undefined => {
+ const owner = ownerDef ? (world.tryGet(e as never, ownerDef) as { scene?: string } | null) : null;
+ if ((owner?.scene ?? '') !== entryScene) return undefined;
+ return app ? sceneOriginOf(app, e as never) : undefined;
+ };
+
// The tree walk is O(entities) — a detail-only sample (withTree false) skips it
// so the editor can poll the selected entity faster than the tree.
const tree = withTree
@@ -219,7 +348,8 @@ function liveSnapshot(world: App['world'], selectedId: number | null, withTree:
entities: all.map((e): LiveEntity => {
const id = e as never as number;
// Component TYPES only — no data decode (the Outliner reads kind from types).
- return { id, name: nameOf(id), parent: parentOf.get(id) ?? null, children: childrenOf.get(id) ?? [], components: inspectableTypes(world, id).map((type) => ({ type, data: {} })), ...visibilityOf(id) } as LiveEntity;
+ const src = srcOf(id);
+ return { id, name: nameOf(id), parent: parentOf.get(id) ?? null, children: childrenOf.get(id) ?? [], components: inspectableTypes(world, id).map((type) => ({ type, data: {} })), ...visibilityOf(id), ...(src === undefined ? {} : { src }) } as LiveEntity;
}),
} as unknown as SceneData)
: null;
@@ -243,9 +373,14 @@ function liveSnapshot(world: App['world'], selectedId: number | null, withTree:
const p = assets?.pathForHandle(kind, handle) ?? null;
return p === null ? null : projectRelative(p, projectBase);
});
- selected = { id: selectedId, name: nameOf(selectedId), parent: parentOf.get(selectedId) ?? null, children: childrenOf.get(selectedId) ?? [], components } as unknown as LiveEntity;
+ const src = srcOf(selectedId);
+ selected = { id: selectedId, name: nameOf(selectedId), parent: parentOf.get(selectedId) ?? null, children: childrenOf.get(selectedId) ?? [], components, ...(src === undefined ? {} : { src }) } as unknown as LiveEntity;
}
- return { tree, selected };
+ // Rides with the selected entity's data rather than a query of its own: the
+ // overlay has to be as fresh as the values beside it, and a second round-trip
+ // per frame would make it a frame staler than what it points at.
+ const overlay = selectedId != null && world.valid(selectedId as never) ? overlayBoxOf(world, selectedId) : null;
+ return { tree, selected, overlay };
}
type InitMessage = Extract<PlayOutbound, { type: 'estella:play:init' }>;
@@ -385,6 +520,10 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
});
setEditorMode(false);
setPlayMode(true);
+ // The editor's tree is the scene document's; this realm's is the running
+ // world's. Without the mapping between them the two can only be shown side by
+ // side, never as one thing.
+ enableSceneOrigins(app);
// The editor's play realm has no ad host, but "watch an ad to revive" is a
// flow a game has to be able to REHEARSE here — the mock keeps the real
@@ -907,6 +1046,9 @@ window.addEventListener('message', (e: MessageEvent) => {
if (data.kind === 'snapshot') {
const reply = app ? liveSnapshot(app.world, data.selectedId ?? null, data.withTree !== false) : null;
post({ type: 'estella:play:reply', reqId: data.reqId, data: reply });
+ } else if (data.kind === 'pick') {
+ const entityId = app && data.x != null && data.y != null ? pickAt(app.world, data.x, data.y) : null;
+ post({ type: 'estella:play:reply', reqId: data.reqId, data: { entityId } });
} else if (data.kind === 'stats') {
// Per-phase + per-system timing + render counters — the running game's
// engine segment for the editor profiler (PerfMonitor, realm 'play').
@@ -962,6 +1104,9 @@ window.addEventListener('message', (e: MessageEvent) => {
setEntityVisible(app.world, data.entityId as never, data.visible);
}
break;
+ case 'estella:play:dragTo':
+ if (app && data.entityId != null) dragTo(app.world, data.entityId, data.x, data.y, data.axis);
+ break;
}
});
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 6ca6e3c6a..ee3945c3d 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -397,7 +397,6 @@ class ProjectStoreImpl {
const es = useEditorStore.getState();
if (es.isPlaying || es.isPaused) {
PlayInspect.stop();
- es.setInspectWorld('editor');
es.stop();
}
// A new project supersedes any in-flight revalidation of the old one (its
diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.ts
index bd4cbc373..3fa8b616f 100644
--- a/desktop/src/store/editorStore.ts
+++ b/desktop/src/store/editorStore.ts
@@ -32,11 +32,6 @@ interface EditorState {
// (tweaking entities in the Outliner/Details) keeps its panels. Persisted.
maximizeOnPlay: boolean;
setMaximizeOnPlay: (v: boolean) => void;
- // Which world the Outliner/Details inspect: the edit scene or the live game
- // (UE5 world picker). Auto-flips to 'game' on Play, 'editor' on Stop.
- inspectWorld: 'editor' | 'game';
- setInspectWorld: (w: 'editor' | 'game') => void;
-
// Launcher (project browser) vs editor shell. The editor opens on the
// launcher until a project is opened/created; `enterEditor` dismisses it.
showLauncher: boolean;
@@ -183,9 +178,6 @@ export const useEditorStore = create<EditorState>((set) => ({
if (typeof localStorage !== 'undefined') localStorage.setItem('estella.maximizeOnPlay', maximizeOnPlay ? '1' : '0');
set({ maximizeOnPlay });
},
- inspectWorld: 'editor',
- setInspectWorld: (inspectWorld) => set({ inspectWorld }),
-
showLauncher: true,
enterEditor: () => set({ showLauncher: false, isPlaying: false, isPaused: false }),
openLauncher: () => set({ showLauncher: true, isPlaying: false, isPaused: false }),
diff --git a/desktop/src/store/selectionStore.ts b/desktop/src/store/selectionStore.ts
index c66227eef..e321b0590 100644
--- a/desktop/src/store/selectionStore.ts
+++ b/desktop/src/store/selectionStore.ts
@@ -3,13 +3,16 @@
import { create } from 'zustand';
import { SceneModel, SceneModelImpl } from '@/engine/SceneModel';
import { PerfMonitor } from '@/engine/PerfMonitor';
+import { authoredRef, type EntityRef } from '@/engine/entityRef';
import type { EntityId, InspectSource } from '@/types';
/**
* Entity selection — model-anchored.
*
- * Selection holds stable **source ids** (they survive undo/redo recreates, where
- * the runtime World id changes). A selected entity can still be removed out from
+ * Selection holds a stable **ref** — a source id for anything the document
+ * declares (surviving undo/redo recreates, where the runtime World id changes),
+ * a realm handle for an entity only the running game has.
+ * A selected entity can still be removed out from
* under us (delete, undo-of-create, scene reload). Instead of scattering
* defensive `select(null)` after every such op, this store listens for the
* model's `entityRemoved` event and drops the dead id — selection self-heals, and
@@ -24,6 +27,14 @@ import type { EntityId, InspectSource } from '@/types';
* single inspector surface, no duplicate "details" column in the content browser.
*/
interface SelectionState {
+ /**
+ * What is selected, in whichever world owns it. The document's own entities
+ * carry their source id here too, so a selection made in the editor is still
+ * the same selection once the game is running.
+ */
+ selectedRef: EntityRef | null;
+ /** The primary selection's SOURCE id — null when the running game spawned it
+ * and the document has no such entity. */
selectedId: EntityId | null;
selectedIds: Set<EntityId>;
/** The PRIMARY selected asset (project-relative path), mutually exclusive with
@@ -34,6 +45,9 @@ interface SelectionState {
selectedAssets: Set<string>;
/** Replace the selection with a single entity (or clear it with null). */
select: (id: EntityId | null) => void;
+ /** Replace the selection with a ref — the door for rows the document doesn't
+ * have (entities the running game spawned). */
+ selectRef: (ref: EntityRef | null) => void;
/** Ctrl/Cmd-click: add/remove one entity from the selection. */
toggleSelect: (id: EntityId) => void;
/** Shift-click / box: replace the selection with a set, with a primary. */
@@ -54,6 +68,8 @@ interface SelectionState {
setInspectSource: (src: InspectSource | null) => void;
/** Remove one id from the selection (despawn self-healing). */
dropId: (id: EntityId) => void;
+ /** Clear a selection only the running realm could resolve (called on Stop). */
+ dropSpawnedSelection: () => void;
}
export type SelectionStore = ReturnType<typeof createSelectionStore>;
@@ -66,7 +82,20 @@ export type SelectionStore = ReturnType<typeof createSelectionStore>;
* restart with the incoming scene. One per EditorSession.
*/
export function createSelectionStore(model: SceneModelImpl) {
+ // The one place ref and id are decided together — they are two readings of a
+ // single fact, and a setter that updated only one would show the Inspector an
+ // entity the Outliner is not highlighting.
+ const entityPick = (ids: Set<EntityId>, primary: EntityId | null) => ({
+ selectedIds: ids,
+ selectedId: primary,
+ selectedRef: primary != null ? authoredRef(primary) : null,
+ selectedAsset: null,
+ selectedAssets: new Set<string>(),
+ });
+ const noEntity = { selectedId: null, selectedRef: null, selectedIds: new Set<EntityId>() };
+
const useStore = create<SelectionState>((set) => ({
+ selectedRef: null,
selectedId: null,
selectedIds: new Set<EntityId>(),
selectedAsset: null,
@@ -77,13 +106,25 @@ export function createSelectionStore(model: SceneModelImpl) {
// 'select' zone captures the synchronous subscriber work a selection triggers.
select: (selectedId) =>
PerfMonitor.measure('select', () =>
+ set(entityPick(selectedId != null ? new Set([selectedId]) : new Set(), selectedId)),
+ ),
+
+ selectRef: (ref) =>
+ PerfMonitor.measure('select', () => {
+ if (ref == null || ref.world === 'authored') {
+ set(entityPick(ref == null ? new Set() : new Set([ref.src]), ref?.src ?? null));
+ return;
+ }
+ // A running-game entity has no document id, so it cannot join the
+ // multi-selection the edit commands act on.
set({
- selectedId,
- selectedIds: selectedId != null ? new Set([selectedId]) : new Set(),
+ selectedRef: ref,
+ selectedId: null,
+ selectedIds: new Set(),
selectedAsset: null,
selectedAssets: new Set(),
- }),
- ),
+ });
+ }),
toggleSelect: (id) =>
PerfMonitor.measure('select', () =>
@@ -93,20 +134,20 @@ export function createSelectionStore(model: SceneModelImpl) {
next.delete(id);
const primary =
s.selectedId === id ? (next.size ? [...next][next.size - 1] : null) : s.selectedId;
- return { selectedIds: next, selectedId: primary, selectedAsset: null, selectedAssets: new Set() };
+ return entityPick(next, primary);
}
next.add(id);
- return { selectedIds: next, selectedId: id, selectedAsset: null, selectedAssets: new Set() };
+ return entityPick(next, id);
}),
),
selectMany: (ids, primary) =>
- PerfMonitor.measure('select', () => set({ selectedIds: new Set(ids), selectedId: primary, selectedAsset: null, selectedAssets: new Set() })),
+ PerfMonitor.measure('select', () => set(entityPick(new Set(ids), primary))),
// Selecting an asset clears any entity selection (mutually exclusive).
selectAsset: (selectedAsset) =>
PerfMonitor.measure('select', () =>
- set({ selectedAsset, selectedAssets: selectedAsset ? new Set([selectedAsset]) : new Set(), selectedId: null, selectedIds: new Set() })),
+ set({ selectedAsset, selectedAssets: selectedAsset ? new Set([selectedAsset]) : new Set(), ...noEntity })),
toggleAsset: (path) =>
PerfMonitor.measure('select', () =>
@@ -116,15 +157,15 @@ export function createSelectionStore(model: SceneModelImpl) {
next.delete(path);
const primary =
s.selectedAsset === path ? (next.size ? [...next][next.size - 1] : null) : s.selectedAsset;
- return { selectedAssets: next, selectedAsset: primary, selectedId: null, selectedIds: new Set() };
+ return { selectedAssets: next, selectedAsset: primary, ...noEntity };
}
next.add(path);
- return { selectedAssets: next, selectedAsset: path, selectedId: null, selectedIds: new Set() };
+ return { selectedAssets: next, selectedAsset: path, ...noEntity };
}),
),
selectAssets: (paths, primary) =>
- PerfMonitor.measure('select', () => set({ selectedAssets: new Set(paths), selectedAsset: primary, selectedId: null, selectedIds: new Set() })),
+ PerfMonitor.measure('select', () => set({ selectedAssets: new Set(paths), selectedAsset: primary, ...noEntity })),
dropId: (id) =>
set((s) => {
@@ -133,8 +174,11 @@ export function createSelectionStore(model: SceneModelImpl) {
next.delete(id);
const primary =
s.selectedId === id ? (next.size ? [...next][next.size - 1] : null) : s.selectedId;
- return { selectedIds: next, selectedId: primary };
+ return { selectedIds: next, selectedId: primary, selectedRef: primary != null ? authoredRef(primary) : null };
}),
+
+ dropSpawnedSelection: () =>
+ set((s) => (s.selectedRef?.world === 'spawned' ? { selectedRef: null } : s)),
}));
model.subscribe((ev) => {
diff --git a/desktop/src/theme/outliner.css b/desktop/src/theme/outliner.css
index 4f8327420..fac294b24 100644
--- a/desktop/src/theme/outliner.css
+++ b/desktop/src/theme/outliner.css
@@ -118,6 +118,10 @@
.row.folder .rname { color: var(--text); }
.row.sel.folder .rname { color: var(--on-accent); } /* selected folder reads white on the blue fill */
-/* World picker (UE5): switch the Outliner/Details between edit + live game —
- a full-width shared Segmented; only the row placement is outliner-specific. */
-.world-pick { padding: 6px 8px; border-bottom: 1px solid var(--border); flex-shrink: 0; }
+/* The banner that says the tree is the running game's, and that what you change
+ in it ends at Stop. */
+.out-live { padding: 5px 10px; font-size: var(--fs-xs); font-weight: 500; color: var(--run-hi); background: rgba(70, 160, 74, 0.12); border-bottom: 1px solid var(--border); flex-shrink: 0; }
+
+/* A row the game made: nothing in the document answers to it, so it reads as a
+ guest — dimmer name, no drag affordance. */
+.row.spawned .rname { color: var(--text-dim); font-style: italic; }
diff --git a/desktop/src/theme/viewport.css b/desktop/src/theme/viewport.css
index a7b8679ab..28fab7e29 100644
--- a/desktop/src/theme/viewport.css
+++ b/desktop/src/theme/viewport.css
@@ -290,8 +290,42 @@
warm re-Play) but is invisible, non-interactive, and behind the editor stage.
visibility (not display:none) keeps the iframe's GL context alive. */
.viewport__play--parked { visibility: hidden; pointer-events: none; z-index: -1; }
-.viewport__play-host { width: 100%; height: 100%; }
+.viewport__play-host { width: 100%; height: 100%; position: relative; }
.viewport__play-host iframe { width: 100%; height: 100%; border: 0; display: block; }
+
+/* Editor gizmos over the running game. The pointer belongs to the GAME unless
+ the user hands it here — a game that cannot be clicked is not running. */
+.play-ov { position: absolute; inset: 0; z-index: 1; pointer-events: none; }
+.play-ov.interactive { pointer-events: auto; cursor: default; }
+.play-ov__svg { position: absolute; inset: 0; overflow: visible; }
+.play-ov__box { fill: none; stroke: var(--star); stroke-width: 1.5; }
+.play-ov__origin { fill: var(--star); stroke: rgba(0, 0, 0, 0.6); stroke-width: 1; }
+/* Same two axis colors the edit gizmo uses — one gizmo language, two worlds. */
+.play-ov__axis { stroke-width: 2.5; }
+.play-ov__axis.x { stroke: var(--error); }
+.play-ov__axis.y { stroke: var(--run); }
+.play-ov__grab { fill: transparent; cursor: move; }
+.play-ov.interactive .play-ov__grab.x { fill: var(--error); }
+.play-ov.interactive .play-ov__grab.y { fill: var(--run); }
+
+/* The toggle that takes the pointer. Sits clear of the status overlay. */
+.viewport__inspect {
+ position: absolute;
+ top: 8px;
+ left: 8px;
+ z-index: 8;
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 3px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--srf-2);
+ color: var(--text-dim);
+ font-size: var(--fs-xs);
+ cursor: pointer;
+}
+.viewport__inspect.on { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
.viewport__play-status {
position: absolute;
inset: 0;
@@ -377,7 +411,21 @@
selection letterboxes by SHAPING the host, so the realm's canvas is the
device's shape and its ScreenScaling adapts exactly as on real hardware. */
.game-panel__stage { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; }
-.game-panel__host { width: 100%; height: 100%; }
+.game-panel__host { width: 100%; height: 100%; position: relative; }
+.game-panel__inspect {
+ margin-left: auto;
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 2px 7px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: transparent;
+ color: var(--text-dim);
+ font-size: var(--fs-xs);
+ cursor: pointer;
+}
+.game-panel__inspect.on { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
/* Play-in-viewport gets the same letterbox: one target screen, both views. */
.viewport__play-stage { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; }
.game-panel__overlay {
diff --git a/desktop/tests/entity-ops.test.ts b/desktop/tests/entity-ops.test.ts
new file mode 100644
index 000000000..ec9792c5d
--- /dev/null
+++ b/desktop/tests/entity-ops.test.ts
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file One write, whichever world is showing.
+ *
+ * The point of the op layer is that a caller cannot accidentally write to the
+ * wrong world, and cannot silently write to none. Both halves are claims here:
+ * where each op landed, and that a ref the running world has no entity for is
+ * refused rather than quietly dropped into the document.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+vi.mock('@/engine/SceneCommands', () => ({
+ SceneCommands: {
+ setField: vi.fn(),
+ setEntityVisible: vi.fn(),
+ setEntityXY: vi.fn(),
+ },
+ toModelValue: (_cur: unknown, _type: unknown, _key: string, value: unknown) => value,
+}));
+vi.mock('@/engine/PlayRealm', () => ({
+ PlayRealm: { setField: vi.fn(), setVisible: vi.fn(), dragTo: vi.fn(), snapshot: vi.fn() },
+}));
+
+import { EntityOps } from '@/engine/entityOps';
+import { SceneCommands } from '@/engine/SceneCommands';
+import { PlayRealm } from '@/engine/PlayRealm';
+import { PlayInspect } from '@/engine/PlayInspect';
+import { useEditorStore } from '@/store/editorStore';
+import { authoredRef, spawnedRef } from '@/engine/entityRef';
+
+/** Play, with the realm holding runtime 900 for document row 3 and nothing else. */
+function playingWith(pairs: Array<{ live: number; src?: number }>) {
+ useEditorStore.setState({ isPlaying: true });
+ vi.spyOn(PlayInspect, 'liveIdOf').mockImplementation((ref) => {
+ if (ref == null) return null;
+ if (ref.world === 'spawned') return pairs.some((p) => p.live === ref.live) ? ref.live : null;
+ return pairs.find((p) => p.src === ref.src)?.live ?? null;
+ });
+ vi.spyOn(PlayInspect, 'componentData').mockReturnValue({});
+}
+
+beforeEach(() => {
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ useEditorStore.setState({ isPlaying: false });
+});
+
+describe('while editing', () => {
+ it('sends a field write to the document, by source id', () => {
+ expect(EntityOps.setField(authoredRef(3), 'Transform', 'position', 'vec3', [1, 2, 0])).toBe('document');
+ expect(SceneCommands.setField).toHaveBeenCalledWith(3, 'Transform', 'position', 'vec3', [1, 2, 0]);
+ expect(PlayRealm.setField).not.toHaveBeenCalled();
+ });
+
+ it('moves through the document command, in world units', () => {
+ expect(EntityOps.moveToPoint(authoredRef(3), { world: { x: 10, y: 20 } })).toBe('document');
+ expect(SceneCommands.setEntityXY).toHaveBeenCalledWith(3, 10, 20);
+ });
+
+ it('refuses a ref the document has no entity for', () => {
+ // A spawned ref outside play has nothing behind it in either world; writing
+ // its realm id into the document would edit whatever row shares the number.
+ expect(EntityOps.setField(spawnedRef(900), 'Transform', 'position', 'vec3', [1, 2, 0])).toBeNull();
+ expect(SceneCommands.setField).not.toHaveBeenCalled();
+ });
+});
+
+describe('while playing', () => {
+ it('sends the same field write to the realm, by runtime id', () => {
+ playingWith([{ live: 900, src: 3 }]);
+ expect(EntityOps.setField(authoredRef(3), 'Sprite', 'color', 'color', [1, 0, 0, 1])).toBe('live');
+ expect(PlayRealm.setField).toHaveBeenCalledWith(900, 'Sprite', 'color', [1, 0, 0, 1]);
+ expect(SceneCommands.setField).not.toHaveBeenCalled();
+ });
+
+ it('never reaches the document — that is what makes a play edit temporary', () => {
+ playingWith([{ live: 900, src: 3 }]);
+ EntityOps.setVisible(authoredRef(3), false);
+ EntityOps.moveToPoint(authoredRef(3), { canvas: { x: 0.5, y: 0.25 } }, 'x');
+ expect(PlayRealm.setVisible).toHaveBeenCalledWith(900, false);
+ expect(PlayRealm.dragTo).toHaveBeenCalledWith(900, 0.5, 0.25, 'x');
+ expect(SceneCommands.setEntityVisible).not.toHaveBeenCalled();
+ expect(SceneCommands.setEntityXY).not.toHaveBeenCalled();
+ });
+
+ it('refuses a write to something the running world destroyed', () => {
+ playingWith([]); // row 3 was never spawned, or is already gone
+ expect(EntityOps.setField(authoredRef(3), 'Sprite', 'color', 'color', [1, 0, 0, 1])).toBeNull();
+ expect(PlayRealm.setField).not.toHaveBeenCalled();
+ expect(SceneCommands.setField).not.toHaveBeenCalled();
+ });
+
+ it('writes to a spawned entity the document knows nothing about', () => {
+ playingWith([{ live: 901 }]);
+ expect(EntityOps.setVisible(spawnedRef(901), false)).toBe('live');
+ expect(PlayRealm.setVisible).toHaveBeenCalledWith(901, false);
+ });
+
+ it('reports the world a write would land in without performing one', () => {
+ playingWith([{ live: 900, src: 3 }]);
+ expect(EntityOps.worldFor(authoredRef(3))).toBe('live');
+ expect(EntityOps.worldFor(authoredRef(4))).toBeNull();
+ expect(EntityOps.worldFor(null)).toBeNull();
+ expect(PlayRealm.setField).not.toHaveBeenCalled();
+ });
+});
diff --git a/desktop/tests/live-tree-identity.test.ts b/desktop/tests/live-tree-identity.test.ts
new file mode 100644
index 000000000..5fa4caaff
--- /dev/null
+++ b/desktop/tests/live-tree-identity.test.ts
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file One tree across the play boundary: what makes a row "the same row".
+ *
+ * The Outliner showed two trees because a document id and a realm handle are
+ * different numbers for the same entity. These are the claims that let one tree
+ * span both: an authored row keeps its key while the game runs, a spawned row
+ * gets one that cannot collide with a document id, and a selection made in the
+ * editor still points at the same thing after Play.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import type { SceneData } from 'esengine';
+import { authoredRef, spawnedRef, refKey, refOfLive, sameRef, srcIdOf } from '@/engine/entityRef';
+import { buildOutlinerItems, entityKey } from '@/outliner/OutlinerModel';
+import { useSelection } from '@/store/selectionStore';
+
+/** A live tree as the realm reports it: realm handles, `src` only where the
+ * entity came from the open document. */
+const liveTree = (rows: Array<{ id: number; src?: number; parent?: number | null }>): SceneData =>
+ ({
+ version: '1.0',
+ name: 'live',
+ entities: rows.map((r) => ({
+ id: r.id,
+ name: `E${r.id}`,
+ parent: r.parent ?? null,
+ children: [],
+ components: [{ type: 'Transform', data: {} }],
+ ...(r.src === undefined ? {} : { src: r.src }),
+ })),
+ }) as unknown as SceneData;
+
+const srcOfLive = (tree: SceneData) => {
+ const map = new Map<number, number>();
+ for (const e of tree.entities as Array<{ id: number; src?: number }>) {
+ if (e.src !== undefined) map.set(e.id, e.src);
+ }
+ return (id: number) => refOfLive(id, map.get(id));
+};
+
+describe('entity refs', () => {
+ it('keys an authored row exactly as the plain scene tree does', () => {
+ // A saved expansion set is a set of these strings. If the key changed on
+ // Play, every open row would close and reopen somewhere else.
+ expect(refKey(authoredRef(7))).toBe(entityKey(7));
+ });
+
+ it('cannot confuse a realm handle with a document id', () => {
+ // Realm handles are small integers too — the collision is certain, not
+ // theoretical, so the two spaces must not share a key format.
+ expect(refKey(spawnedRef(7))).not.toBe(refKey(authoredRef(7)));
+ expect(sameRef(spawnedRef(7), authoredRef(7))).toBe(false);
+ });
+
+ it('reads a document id only from something the document has', () => {
+ expect(srcIdOf(authoredRef(7))).toBe(7);
+ expect(srcIdOf(spawnedRef(7))).toBeNull();
+ expect(srcIdOf(null)).toBeNull();
+ });
+});
+
+describe('the tree of a running world', () => {
+ it('gives an authored entity the row key it had before Play', () => {
+ // Realm handle 900, loaded from document row 3.
+ const tree = liveTree([{ id: 900, src: 3 }]);
+ const items = buildOutlinerItems(tree, { expanded: new Set(), refOf: srcOfLive(tree) });
+ expect(items).toHaveLength(1);
+ expect(items[0].key).toBe(entityKey(3));
+ // The row still ACTS on the running world: live ops need the handle.
+ expect(items[0].kind === 'entity' && items[0].id).toBe(900);
+ });
+
+ it('marks an entity the game spawned as belonging to no document row', () => {
+ const tree = liveTree([{ id: 901 }]);
+ const items = buildOutlinerItems(tree, { expanded: new Set(), refOf: srcOfLive(tree) });
+ expect(items[0].kind === 'entity' && items[0].ref.world).toBe('spawned');
+ expect(items[0].key).toBe(refKey(spawnedRef(901)));
+ });
+
+ it('separates a spawned row from the document row that shares its number', () => {
+ // Handle 3 is a bullet; document row 3 is a platform loaded as handle 900.
+ const tree = liveTree([{ id: 900, src: 3 }, { id: 3 }]);
+ const items = buildOutlinerItems(tree, { expanded: new Set(), refOf: srcOfLive(tree) });
+ expect(new Set(items.map((i) => i.key)).size).toBe(2);
+ });
+
+ it('keeps a parent row expanded under the key its child nests below', () => {
+ const tree = liveTree([{ id: 900, src: 3 }, { id: 901, src: 4, parent: 900 }]);
+ const refOf = srcOfLive(tree);
+ const collapsed = buildOutlinerItems(tree, { expanded: new Set(), refOf });
+ expect(collapsed).toHaveLength(1); // the child is folded away
+
+ const opened = buildOutlinerItems(tree, { expanded: new Set([entityKey(3)]), refOf });
+ expect(opened.map((i) => i.key)).toEqual([entityKey(3), entityKey(4)]);
+ expect(opened[1].parentKey).toBe(entityKey(3));
+ });
+});
+
+describe('one selection', () => {
+ beforeEach(() => useSelection.getState().select(null));
+
+ it('survives Play as the same ref it was made with', () => {
+ useSelection.getState().select(3);
+ const before = useSelection.getState().selectedRef;
+ // Play changes nothing about the selection: the running world is looked up
+ // through the ref, not stored in it.
+ expect(sameRef(before, authoredRef(3))).toBe(true);
+ expect(useSelection.getState().selectedId).toBe(3);
+ });
+
+ it('holds a spawned entity without claiming the document has one', () => {
+ useSelection.getState().selectRef(spawnedRef(901));
+ const s = useSelection.getState();
+ expect(s.selectedRef).toEqual(spawnedRef(901));
+ // Every edit command reads selectedId/selectedIds; a bullet must not reach
+ // one and be looked up as a document row.
+ expect(s.selectedId).toBeNull();
+ expect(s.selectedIds.size).toBe(0);
+ });
+
+ it('drops a spawned selection on Stop and keeps an authored one', () => {
+ useSelection.getState().selectRef(spawnedRef(901));
+ useSelection.getState().dropSpawnedSelection();
+ expect(useSelection.getState().selectedRef).toBeNull();
+
+ useSelection.getState().select(3);
+ useSelection.getState().dropSpawnedSelection();
+ expect(sameRef(useSelection.getState().selectedRef, authoredRef(3))).toBe(true);
+ });
+
+ it('never lets the ref and the id disagree', () => {
+ useSelection.getState().selectMany([3, 4], 4);
+ expect(useSelection.getState().selectedId).toBe(4);
+ expect(sameRef(useSelection.getState().selectedRef, authoredRef(4))).toBe(true);
+
+ useSelection.getState().toggleSelect(4); // drops the primary
+ const s = useSelection.getState();
+ expect(srcIdOf(s.selectedRef)).toBe(s.selectedId);
+
+ useSelection.getState().selectAsset('a/b.png');
+ expect(useSelection.getState().selectedRef).toBeNull();
+ expect(useSelection.getState().selectedId).toBeNull();
+ });
+});
diff --git a/desktop/tests/outliner-controller.test.ts b/desktop/tests/outliner-controller.test.ts
index 1108d3d8c..261691e33 100644
--- a/desktop/tests/outliner-controller.test.ts
+++ b/desktop/tests/outliner-controller.test.ts
@@ -10,6 +10,9 @@ import type { SceneData } from 'esengine';
import { EditorSession } from '@/engine/EditorSession';
import { createSceneOutlinerStore } from '@/outliner/OutlinerController';
import { entityKey, folderKey } from '@/outliner/OutlinerModel';
+import { refKey, spawnedRef } from '@/engine/entityRef';
+
+const liveKey = (id: number) => refKey(spawnedRef(id));
const ent = (id: number, parent: number | null, children: number[]) => ({ id, name: `E${id}`, parent, children, components: [] as unknown[] });
// 1 ─ 2 ─ 3 (a chain); root 1 lives in folder "A/B".
@@ -83,24 +86,27 @@ describe('OutlinerController', () => {
expect(store.getState().selectedFolder).toBeNull();
});
- // The snapshot-source self-heal. A running world announces nothing when an
- // entity dies, and its ids are RECYCLED — so a key kept past its entity would
- // open a row belonging to something else entirely.
- it('retainIds drops expansion + cursor for entities the source no longer has', () => {
- store.getState().setExpanded([entityKey(1), entityKey(2), folderKey('A')]);
- store.getState().setCursor(entityKey(2));
- store.getState().retainIds(new Set([1]));
+ // The live self-heal. A running world announces nothing when an entity dies,
+ // and its ids are RECYCLED — so a key kept past its entity would open a row
+ // belonging to something else entirely.
+ it('retainLiveIds drops expansion + cursor for spawned rows the world no longer has', () => {
+ store.getState().setExpanded([liveKey(1), liveKey(2), entityKey(2), folderKey('A')]);
+ store.getState().setCursor(liveKey(2));
+ store.getState().retainLiveIds(new Set([1]));
const exp = store.getState().expanded;
- expect(exp.has(entityKey(1))).toBe(true);
- expect(exp.has(entityKey(2))).toBe(false);
- expect(exp.has(folderKey('A'))).toBe(true); // folder keys are not entity keys
+ expect(exp.has(liveKey(1))).toBe(true);
+ expect(exp.has(liveKey(2))).toBe(false);
+ // A document row answers to the model, not to a realm snapshot: an entity
+ // the running game never spawned still has its row in the scene.
+ expect(exp.has(entityKey(2))).toBe(true);
+ expect(exp.has(folderKey('A'))).toBe(true);
expect(store.getState().cursor).toBeNull();
});
- it('retainIds keeps the same expansion object when nothing went away', () => {
- store.getState().setExpanded([entityKey(1)]);
+ it('retainLiveIds keeps the same expansion object when nothing went away', () => {
+ store.getState().setExpanded([liveKey(1)]);
const before = store.getState().expanded;
- store.getState().retainIds(new Set([1, 2, 3]));
+ store.getState().retainLiveIds(new Set([1, 2, 3]));
expect(store.getState().expanded).toBe(before); // no re-render on a steady frame
});
diff --git a/desktop/tests/play-inspect-gating.test.ts b/desktop/tests/play-inspect-gating.test.ts
index 03004334d..922c8ce78 100644
--- a/desktop/tests/play-inspect-gating.test.ts
+++ b/desktop/tests/play-inspect-gating.test.ts
@@ -19,6 +19,8 @@ vi.mock('@/engine/PlayRealm', () => ({
import { PlayInspect } from '@/engine/PlayInspect';
import { PlayRealm } from '@/engine/PlayRealm';
+import { useSelection } from '@/store/selectionStore';
+import { spawnedRef } from '@/engine/entityRef';
const snapshotMock = vi.mocked(PlayRealm.snapshot);
@@ -32,6 +34,7 @@ const tree = (ids: number[]): SceneData =>
let now = 0;
beforeEach(() => {
+ useSelection.getState().select(null);
vi.useFakeTimers();
now = 0;
vi.spyOn(performance, 'now').mockImplementation(() => now);
@@ -39,6 +42,7 @@ beforeEach(() => {
Promise.resolve({
tree: opts?.tree === false ? null : tree([1, 2]),
selected: sel != null ? (tree([sel as number]).entities[0] ?? null) : null,
+ overlay: null,
}),
);
});
@@ -81,7 +85,7 @@ describe('PlayInspect gating', () => {
expect(snapshotMock).toHaveBeenCalledTimes(1);
expect(snapshotMock.mock.calls[0][1]).toEqual({ tree: true }); // first sample seeds the tree
- PlayInspect.select(7); // detail polling engages
+ useSelection.getState().selectRef(spawnedRef(1)); // detail polling engages
await advance(500);
const withTree = snapshotMock.mock.calls.filter((c) => c[1]?.tree !== false).length;
const detailOnly = snapshotMock.mock.calls.filter((c) => c[1]?.tree === false).length;
@@ -117,7 +121,7 @@ describe('PlayInspect gating', () => {
await advance(200);
const first = PlayInspect.getTree();
snapshotMock.mockImplementation((_sel, opts) =>
- Promise.resolve({ tree: opts?.tree === false ? null : tree([1, 2, 3]), selected: null }),
+ Promise.resolve({ tree: opts?.tree === false ? null : tree([1, 2, 3]), selected: null, overlay: null }),
);
await advance(300);
expect(PlayInspect.getTree()).not.toBe(first);
@@ -129,10 +133,12 @@ describe('PlayInspect gating', () => {
PlayInspect.start();
const unsub = PlayInspect.subscribe(() => {});
await advance(200);
+ useSelection.getState().selectRef(spawnedRef(1));
expect(PlayInspect.getTree()).not.toBeNull();
PlayInspect.stop();
expect(PlayInspect.getTree()).toBeNull();
- expect(PlayInspect.getSelection()).toBeNull();
+ // A ref only the realm could resolve does not outlive it.
+ expect(useSelection.getState().selectedRef).toBeNull();
unsub();
});
});
diff --git a/docs/astro/src/content/docs/editor/play.mdx b/docs/astro/src/content/docs/editor/play.mdx
index 9a8c2c6ed..6f47b44a3 100644
--- a/docs/astro/src/content/docs/editor/play.mdx
+++ b/docs/astro/src/content/docs/editor/play.mdx
@@ -18,6 +18,29 @@ The **Play** controls in the toolbar run your game:
Because play uses an isolated realm — the same runtime that ships your game — what you
see in play is what a player gets.
+## The Outliner while playing
+
+There is one hierarchy, not two. While the game runs the Outliner shows the **running
+world**, and a row that came from your scene keeps the identity it had before Play — so
+what you had expanded stays expanded, what you had selected stays selected, and the
+Inspector tracks that entity's live values. Entities the game spawned appear under a
+**Runtime** group; they are gone on Stop, as are any values you tweak while playing.
+
+Authoring is the document's, so it waits for Stop: while playing you can select, search,
+fold and hide rows, but not rename, reparent, create or delete.
+
+## Moving things while the game runs
+
+The selected entity is outlined on the running frame. Turn on **Inspect** (above the
+game) and the pointer belongs to the editor instead of the game: click to select what is
+under it, drag the entity to move it, or drag an axis handle to move it along one. It is
+off by default, because a game you cannot click is not a game.
+
+The running world is what answers all of this — where the entity is drawn, what is under
+the pointer, where a drag lands — so it is the game's own camera doing the projection,
+and a moved entity ends up where the game will draw it. As with any play-time edit, it
+lasts until Stop.
+
## Autosave & recovery
The editor periodically snapshots your **unsaved** documents — only when there are
diff --git a/docs/astro/src/content/docs/zh-cn/editor/play.mdx b/docs/astro/src/content/docs/zh-cn/editor/play.mdx
index 1a4ee69bd..43fc9c33f 100644
--- a/docs/astro/src/content/docs/zh-cn/editor/play.mdx
+++ b/docs/astro/src/content/docs/zh-cn/editor/play.mdx
@@ -12,6 +12,23 @@ description: "在隔离 realm 里于编辑器内运行游戏、运行模式选
因为运行用的是隔离 realm——正是发布你游戏的那套运行时——你在运行里看到的,就是玩家会得到的。
+## 运行时的大纲
+
+层级只有一个,不是两个。游戏运行时大纲显示的是**运行中的世界**,而来自你场景的行会保留它在
+运行前的身份——所以你展开的仍然展开、你选中的仍然选中,检视器跟着显示那个实体的实时值。
+游戏自己创建的实体归到 **Runtime** 分组;它们和你运行期间调的值一样,停止时一并消失。
+
+创作属于文档,所以它等到停止:运行中你可以选择、搜索、折叠、隐藏,但不能重命名、改父子、
+新建或删除。
+
+## 运行中移动实体
+
+选中的实体会在运行画面上被描边。打开画面上方的**检视**,指针就归编辑器而不是游戏:点击选中
+指针下的东西,拖拽移动它,或拖某根轴手柄让它只沿那根轴走。默认关闭——点不动的游戏不算游戏。
+
+这些问题全部由运行中的世界回答——实体画在哪、指针下是谁、拖拽落到哪——用的是游戏自己的
+相机做投影,所以移动后的位置就是游戏接下来会画的位置。和任何运行期修改一样,它到停止为止。
+
## 自动保存与恢复
编辑器会定期快照你**未保存**的文档——仅在存在未保存改动且没有 Play 会话运行时——所以崩溃或