A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(editor): a delete you take back lands where it was, and the gizmo owns its centre
esengine544cb294500b
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex e18ca1f91..360cc7952 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -4,7 +4,7 @@ import type { SceneData, PrefabData, ControllerState, UIControllerData, GearBindimport { TilemapAPI, TilemapLiveSync, UIPositionType, DimensionUnit, AnchorAxis, writeFieldPath, type AnchorPreset } from 'esengine';import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types';import { EditorHistory, EditorHistoryImpl } from './EditorHistory';-import { SceneModel, SceneModelImpl, type PrefabInstanceTag } from './SceneModel';+import { SceneModel, SceneModelImpl, type PrefabInstanceTag, type RemovedEntity } from './SceneModel';import { SceneStore } from './SceneStore';import { usePrefabConflicts } from '@/store/prefabConflicts';import { ViewportController } from './ViewportController';@@ -739,12 +739,12 @@ export class SceneCommandsImpl {const sourceId = this.model.addEntity('Entity', [{ type: 'Transform', data: structuredClone(DEFAULT_TRANSFORM) } as SceneComponent,], parent);- let record: SceneEntity | undefined;+ let record: RemovedEntity | undefined;this.history.describe({ kind: 'add', entity: sourceId, name: this.nameOf(sourceId) });this.history.record('Add Entity',() => {- if (record) this.model.restoreEntity(record);+ if (record) this.model.restoreEntities([record]);},() => {record = this.model.removeEntityBySource(sourceId);@@ -756,23 +756,23 @@ export class SceneCommandsImpl {/*** Delete an entity AND its descendants (the World despawns children with their* parent, so the model removes the whole subtree to stay consistent). Undo- * re-creates the subtree losslessly, parent-before-child. Records are kept- * parent-first so restore re-links each child to its (already-restored) parent.+ * re-creates the subtree losslessly, each entity back at the index it left —+ * see SceneModel.restoreEntities for why the position is not decoration.*/deleteEntity(sourceId: EntityId): void {const entity = this.model.entityBySource(sourceId);if (!entity) return;const name = entity.name || 'Entity';- const remove = (): SceneEntity[] =>+ const remove = (): RemovedEntity[] =>this.model.collectSubtree(sourceId).map((id) => this.model.removeEntityBySource(id))- .filter((r): r is SceneEntity => r !== undefined);+ .filter((r): r is RemovedEntity => r !== undefined);let records = remove();if (records.length === 0) return;this.history.describe(...records.map((r) => ({- kind: 'remove' as const, entity: r.id, name: r.name || `Entity ${r.id}`,+ kind: 'remove' as const, entity: r.entity.id, name: r.entity.name || `Entity ${r.entity.id}`,})));this.history.record(`Delete ${name}`,@@ -780,7 +780,7 @@ export class SceneCommandsImpl {records = remove(); // redo},() => {- for (const r of records) this.model.restoreEntity(r); // parent-first+ this.model.restoreEntities(records);},);}diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.tsindex b2ee066ae..b47a2c91d 100644--- a/desktop/src/engine/SceneModel.ts+++ b/desktop/src/engine/SceneModel.ts@@ -37,6 +37,15 @@ export type ModelEvent =type Listener = (ev: ModelEvent) => void;+/** A removed entity plus where it sat — everything an exact restore needs. */+export interface RemovedEntity {+ entity: SceneEntity;+ /** Index in `data.entities`, which is painter order. */+ index: number;+ /** Index within the parent's `children[]`; -1 when it had no parent. */+ childIndex: number;+}+/*** Marks a model entity as part of a prefab instance. The* editor expands a prefab instance into ordinary entities; these tags record@@ -228,35 +237,47 @@ export class SceneModelImpl {* hierarchy stays consistent. The source↔runtime map is left to the Reconciler* to unbind on the emitted `entityRemoved`.*/- removeEntityBySource(sourceId: number): SceneEntity | undefined {+ removeEntityBySource(sourceId: number): RemovedEntity | undefined {if (!this.data) return undefined;- const idx = this.data.entities.findIndex((e) => e.id === sourceId);- if (idx < 0) return undefined;- const [removed] = this.data.entities.splice(idx, 1);+ const index = this.data.entities.findIndex((e) => e.id === sourceId);+ if (index < 0) return undefined;+ const [entity] = this.data.entities.splice(index, 1);this.entityIndex_.delete(sourceId);- if (removed.parent != null) {- const p = this.entityBySource(removed.parent);- if (p) p.children = p.children.filter((c) => c !== sourceId);+ let childIndex = -1;+ if (entity.parent != null) {+ const p = this.entityBySource(entity.parent);+ if (p) {+ childIndex = p.children.indexOf(sourceId);+ if (childIndex >= 0) p.children.splice(childIndex, 1);+ }}this.prefabTags.delete(sourceId);this.emit({ kind: 'entityRemoved', sourceId });- return removed;+ return { entity, index, childIndex };}/**- * Re-insert a previously-removed source entity (undo of delete). Restores its- * link in the parent's `children[]`. The Reconciler respawns + binds a fresh- * runtime entity on the emitted `entityAdded`.+ * Re-insert removed entities at the indices they left; the Reconciler respawns+ * each on the emitted `entityAdded`. Index matters — `data.entities` order is+ * painter order. Batched: the inverse of a run of splices is that run replayed+ * backwards, while links and events stay parent-first.*/- restoreEntity(entity: SceneEntity): void {+ restoreEntities(records: readonly RemovedEntity[]): void {if (!this.data) return;- this.data.entities.push(entity);- this.entityIndex_.set(entity.id, entity);- if (entity.parent != null) {- const p = this.entityBySource(entity.parent);- if (p && !p.children.includes(entity.id)) p.children.push(entity.id);+ for (let i = records.length - 1; i >= 0; i--) {+ const { entity, index } = records[i];+ this.data.entities.splice(Math.min(index, this.data.entities.length), 0, entity);+ this.entityIndex_.set(entity.id, entity);+ }+ for (const { entity, childIndex } of records) {+ if (entity.parent != null) {+ const p = this.entityBySource(entity.parent);+ if (p && !p.children.includes(entity.id)) {+ p.children.splice(childIndex < 0 ? p.children.length : Math.min(childIndex, p.children.length), 0, entity.id);+ }+ }+ this.emit({ kind: 'entityAdded', sourceId: entity.id });}- this.emit({ kind: 'entityAdded', sourceId: entity.id });}/**diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex 0745cf469..6f57a53da 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -48,7 +48,7 @@ import { usePanelWindow, eventWindow } from '@/components/PanelWindow';import type { ToolMode, EntityId } from '@/types';import { resolveActiveTool, type EditorTool, type ToolContext, type PointerInput } from '@/tools';import { cursorTile } from '@/tools/tileTools';-import { GIZMO, type GizmoAxis } from '@/tools/gizmo';+import { GIZMO, colliderHandleClass, type GizmoAxis } from '@/tools/gizmo';import { selectionPivot, gizmoScreenAngleRad } from '@/tools/transformTools';import { Marquee } from '@/tools/marquee';import { TilePaintPreview } from '@/tools/tilePreview';@@ -2321,7 +2321,10 @@ export function Viewport() {if (el) colliderRefs.current.set(id, el);else colliderRefs.current.delete(id);}}- className="viewport__collider-gizmo"+ className={+ 'viewport__collider-gizmo'+ + colliderHandleClass(selectedIds.has(SceneModel.sourceFor(id) ?? -1), tool)+ }data-src={SceneModel.sourceFor(id)}aria-hidden="true">diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.cssindex d500a3790..943c13dd3 100644--- a/desktop/src/theme/app.css+++ b/desktop/src/theme/app.css@@ -506,15 +506,22 @@ body.thumb-capture .viewport > :not(.viewport__stage):not(.viewport__play) {stroke-dasharray: 4 3;opacity: 0.85;}-/* Draggable handles — circle radius / box corner size (meters), written on canvas. */+/* Draggable handles — circle radius / box corner size (meters), written on canvas.+ Grabbable only on the selected entity (`.is-live`): the overlay is drawn for every+ collider in the scene, and a handle on each would take the pointer from the entity+ under it. */.viewport__collider-gizmo .cl-handle,.viewport__collider-gizmo .cl-size-handle {fill: var(--gizmo-collider);stroke: var(--srf-2);stroke-width: 1.5;- pointer-events: auto;cursor: ew-resize;}+.viewport__collider-gizmo.is-live .cl-handle,+.viewport__collider-gizmo.is-live .cl-size-handle,+.viewport__collider-gizmo.is-live .cl-vert {+ pointer-events: auto;+}.viewport__collider-gizmo .cl-size-handle {cursor: nwse-resize;}@@ -524,9 +531,14 @@ body.thumb-capture .viewport > :not(.viewport__stage):not(.viewport__play) {fill: var(--gizmo-collider);stroke: var(--srf-2);stroke-width: 1.25;- pointer-events: auto;cursor: move;}+/* The offset handle sits exactly where Move/Scale put their centre grab. The+ transform gizmo wins there; the offset stays draggable under Select, and typed+ in the Inspector either way. */+.viewport__collider-gizmo.gizmo-owns-centre .cl-offset {+ pointer-events: none;+}.viewport__collider-gizmo .cl-vert:hover {fill: color-mix(in srgb, var(--gizmo-collider) 70%, white);}diff --git a/desktop/src/tools/gizmo.ts b/desktop/src/tools/gizmo.tsindex 253921939..680c3b124 100644--- a/desktop/src/tools/gizmo.ts+++ b/desktop/src/tools/gizmo.ts@@ -142,3 +142,14 @@ export function rotateAround(p: Pt, c: Pt, angle: number): Pt {export function scaleAround(p: Pt, c: Pt, fx: number, fy: number): Pt {return { x: c.x + (p.x - c.x) * fx, y: c.y + (p.y - c.y) * fy };}++/**+ * Which collider-overlay handles may take the pointer.+ *+ * The overlay is drawn for EVERY collider in the scene, and the offset handle+ * sits where Move and Scale keep their centre grab. So handles answer only for+ * the selected entity, and the offset yields to any transform gizmo.+ */+export function colliderHandleClass(selected: boolean, mode: GizmoMode | 'select'): string {+ return (selected ? ' is-live' : '') + (mode === 'select' ? '' : ' gizmo-owns-centre');+}diff --git a/desktop/tests/gizmo.test.ts b/desktop/tests/gizmo.test.tsindex 2daf936db..f92a7ac91 100644--- a/desktop/tests/gizmo.test.ts+++ b/desktop/tests/gizmo.test.ts@@ -7,6 +7,7 @@import { describe, it, expect } from 'vitest';import {GIZMO,+ colliderHandleClass,hitTestGizmo,constrainWorldDelta,groupPivot,@@ -86,3 +87,33 @@ describe('distToSegment', () => {expect(distToSegment({ x: 13, y: 0 }, { x: 0, y: 0 }, { x: 10, y: 0 })).toBeCloseTo(3, 6);});});++/**+ * Collider overlays are drawn for every collider in the scene, and the offset+ * handle sits exactly where Move/Scale keep their centre grab. Ungated, dragging+ * the middle of a platform to move it writes BoxCollider.offset instead.+ */+describe('colliderHandleClass', () => {+ it('leaves an unselected entity\'s handles inert under every tool', () => {+ for (const mode of ['select', 'move', 'rotate', 'scale'] as const) {+ expect(colliderHandleClass(false, mode)).not.toContain('is-live');+ }+ });++ it('arms the selected entity\'s handles', () => {+ expect(colliderHandleClass(true, 'select')).toContain('is-live');+ });++ it('yields the centre to every transform gizmo, and only to those', () => {+ expect(colliderHandleClass(true, 'move')).toContain('gizmo-owns-centre');+ expect(colliderHandleClass(true, 'scale')).toContain('gizmo-owns-centre');+ expect(colliderHandleClass(true, 'rotate')).toContain('gizmo-owns-centre');+ expect(colliderHandleClass(true, 'select')).not.toContain('gizmo-owns-centre');+ });++ it('keeps the collider offset reachable: selected + Select tool arms it outright', () => {+ const cls = colliderHandleClass(true, 'select');+ expect(cls).toContain('is-live');+ expect(cls).not.toContain('gizmo-owns-centre');+ });+});diff --git a/desktop/tests/scene-model-restore-order.test.ts b/desktop/tests/scene-model-restore-order.test.tsnew file mode 100644index 000000000..6099e7def--- /dev/null+++ b/desktop/tests/scene-model-restore-order.test.ts@@ -0,0 +1,90 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Undoing a delete puts the entity back WHERE it was.+ *+ * `data.entities` order is painter order (SceneModel's own note on sibling+ * order), so a restore that appends moves the entity in front of whatever+ * it sat behind, and re-saves the file with a reordered list.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import type { SceneData } from 'esengine';+import { SceneModel } from '@/engine/SceneModel';++/** Four roots plus a parent with three children — enough for "middle" to exist. */+function fixture(): SceneData {+ return {+ version: '1.0',+ name: 'order',+ entities: [+ { id: 1, name: 'A', parent: null, children: [], components: [] },+ { id: 2, name: 'B', parent: null, children: [], components: [] },+ { id: 3, name: 'Group', parent: null, children: [4, 5, 6], components: [] },+ { id: 4, name: 'C1', parent: 3, children: [], components: [] },+ { id: 5, name: 'C2', parent: 3, children: [], components: [] },+ { id: 6, name: 'C3', parent: 3, children: [], components: [] },+ { id: 7, name: 'D', parent: null, children: [], components: [] },+ ],+ } as unknown as SceneData;+}++const order = () => SceneModel.current!.entities.map((e) => e.id);+const childrenOf = (id: number) => SceneModel.entityBySource(id)!.children.slice();++describe('restoring a removed entity', () => {+ beforeEach(() => SceneModel.adopt(fixture(), new Map()));++ it('puts a root back at its own index, not at the end', () => {+ const before = order();+ const rec = SceneModel.removeEntityBySource(2)!;+ expect(order()).toEqual([1, 3, 4, 5, 6, 7]);+ SceneModel.restoreEntities([rec]);+ expect(order()).toEqual(before);+ });++ it('puts a child back at its own slot among its siblings', () => {+ const rec = SceneModel.removeEntityBySource(5)!;+ expect(childrenOf(3)).toEqual([4, 6]);+ SceneModel.restoreEntities([rec]);+ expect(childrenOf(3)).toEqual([4, 5, 6]);+ expect(order()).toEqual([1, 2, 3, 4, 5, 6, 7]);+ });++ it('restores a whole subtree, parent and children, exactly where it was', () => {+ const before = order();+ const beforeChildren = childrenOf(3);+ // The delete path removes parent-first, over the shrinking array.+ const records = [3, 4, 5, 6].map((id) => SceneModel.removeEntityBySource(id)!);+ expect(order()).toEqual([1, 2, 7]);+ SceneModel.restoreEntities(records);+ expect(order()).toEqual(before);+ expect(childrenOf(3)).toEqual(beforeChildren);+ });++ it('restores several separate removals to their original places', () => {+ const before = order();+ const records = [1, 5, 7].map((id) => SceneModel.removeEntityBySource(id)!);+ SceneModel.restoreEntities(records);+ expect(order()).toEqual(before);+ expect(childrenOf(3)).toEqual([4, 5, 6]);+ });++ it('announces a restored parent before its children', () => {+ const records = [3, 4].map((id) => SceneModel.removeEntityBySource(id)!);+ const added: number[] = [];+ const off = SceneModel.subscribe((e) => {+ if (e.kind === 'entityAdded') added.push(e.sourceId);+ });+ SceneModel.restoreEntities(records);+ off();+ expect(added).toEqual([3, 4]);+ });++ it('appends when the recorded slot no longer exists', () => {+ const rec = SceneModel.removeEntityBySource(7)!; // last root+ SceneModel.removeEntityBySource(1);+ SceneModel.removeEntityBySource(2);+ expect(() => SceneModel.restoreEntities([rec])).not.toThrow();+ expect(order()).toContain(7);+ });+});diff --git a/desktop/tests/scene-model.test.ts b/desktop/tests/scene-model.test.tsindex 6120b4212..296553f28 100644--- a/desktop/tests/scene-model.test.ts+++ b/desktop/tests/scene-model.test.ts@@ -95,7 +95,7 @@ describe('SceneModel (JSON-first source of truth)', () => {expect(SceneModel.entityBySource(1)).toBeUndefined();expect(agrees()).toBe(true);- SceneModel.restoreEntity(removed!);+ SceneModel.restoreEntities([removed!]);expect(SceneModel.entityBySource(1)).toBe(scan(1));expect(agrees()).toBe(true);