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
feat(editor): multi-selection align + distribute tools
esenginee4f9b9a8c5ff
diff --git a/desktop/src/i18n/messages/viewport.ts b/desktop/src/i18n/messages/viewport.tsindex c5019204e..0230e29f1 100644--- a/desktop/src/i18n/messages/viewport.ts+++ b/desktop/src/i18n/messages/viewport.ts@@ -73,6 +73,16 @@ export const viewportMessages = defineMessages({'vp.flag.previewFx': { en: 'Preview FX', zh: '预览特效' },'vp.flag.perf': { en: 'Perf', zh: '性能' },+ // — Align + distribute (multi-selection) —+ 'vp.align.left': { en: 'Align left edges', zh: '左对齐' },+ 'vp.align.hcenter': { en: 'Align horizontal centers', zh: '水平居中对齐' },+ 'vp.align.right': { en: 'Align right edges', zh: '右对齐' },+ 'vp.align.top': { en: 'Align top edges', zh: '顶对齐' },+ 'vp.align.vmiddle': { en: 'Align vertical centers', zh: '垂直居中对齐' },+ 'vp.align.bottom': { en: 'Align bottom edges', zh: '底对齐' },+ 'vp.align.distributeH': { en: 'Distribute horizontal spacing', zh: '水平等距分布' },+ 'vp.align.distributeV': { en: 'Distribute vertical spacing', zh: '垂直等距分布' },+// — View controls —'vp.frameSelected': { en: 'Frame Selected', zh: '聚焦所选' },'vp.minimap': { en: 'Minimap · click or drag to navigate', zh: '小地图 · 点击或拖动以导航' },diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex babbe4f1b..6c4122f15 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -5,6 +5,9 @@ import type { PointerEvent as ReactPointerEvent, DragEvent as ReactDragEvent, Reimport {MousePointer2, Move, RotateCw, Scale3d, Grid3x3, Frame,Camera, Check, ChevronDown, Loader2, TriangleAlert, Lightbulb, Sparkles, Globe, Crosshair, Smartphone, Monitor, Magnet, Axis3d, Hexagon, type LucideIcon,+ AlignStartVertical, AlignCenterVertical, AlignEndVertical,+ AlignStartHorizontal, AlignCenterHorizontal, AlignEndHorizontal,+ AlignHorizontalDistributeCenter, AlignVerticalDistributeCenter,} from 'lucide-react';import { t } from '@/i18n';import { useEditorStore } from '@/store/editorStore';@@ -15,6 +18,7 @@ import { activeMode, activeModeOverlays } from '@/mode/activeMode';import { useEditorMode } from '@/store/editorModeStore';import { RESOLUTION_PRESETS, RESOLUTION_PRESET_BY_ID, DESIGN_RESOLUTION_PRESETS, deviceDims } from '@/mode/resolutionPresets';import { buildStampGhost } from '@/tools/tileStampGhost';+import { alignSelection, distributeSelection } from '@/tools/alignTools';import { TilemapAPI, tileIdOf, isNonOrthogonal, UINode, DimensionUnit, computeEffectiveOrthoSize, type TileCollisionPiece, type TilesetModel } from 'esengine';import { commands } from '@/commands';import { MOD_LABEL } from '@/commands/keybinding';@@ -2088,6 +2092,27 @@ export function Viewport() {</OvDropdown></div>+ {/* Align + distribute — contextual, appears once 2+ entities are selected.+ Every button lands through SceneCommands.setEntityXY (one undo step). */}+ {selCount >= 2 && (+ <div className="viewport__tb-group">+ <OvTool icon={AlignStartVertical} label={t('vp.align.left')} onClick={() => alignSelection('left')} />+ <OvTool icon={AlignCenterVertical} label={t('vp.align.hcenter')} onClick={() => alignSelection('hcenter')} />+ <OvTool icon={AlignEndVertical} label={t('vp.align.right')} onClick={() => alignSelection('right')} />+ <span className="ov-divider" />+ <OvTool icon={AlignStartHorizontal} label={t('vp.align.top')} onClick={() => alignSelection('top')} />+ <OvTool icon={AlignCenterHorizontal} label={t('vp.align.vmiddle')} onClick={() => alignSelection('vmiddle')} />+ <OvTool icon={AlignEndHorizontal} label={t('vp.align.bottom')} onClick={() => alignSelection('bottom')} />+ {selCount >= 3 && (+ <>+ <span className="ov-divider" />+ <OvTool icon={AlignHorizontalDistributeCenter} label={t('vp.align.distributeH')} onClick={() => distributeSelection('h')} />+ <OvTool icon={AlignVerticalDistributeCenter} label={t('vp.align.distributeV')} onClick={() => distributeSelection('v')} />+ </>+ )}+ </div>+ )}+<div className="viewport__tb-group viewport__tb-group--right"><span className="vp-mode-chip">2D</span><div className="ov-seg">diff --git a/desktop/src/tools/alignMath.ts b/desktop/src/tools/alignMath.tsnew file mode 100644index 000000000..42546ae6e--- /dev/null+++ b/desktop/src/tools/alignMath.ts@@ -0,0 +1,76 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file alignMath.ts+ * @brief Pure world-space (y-up) geometry for multi-selection align + distribute —+ * no engine / DOM coupling, so it unit-tests in isolation. The imperative+ * shell (alignTools) reads the live selection's boxes and applies these+ * targets through SceneCommands.+ */++export type AlignOp = 'left' | 'hcenter' | 'right' | 'top' | 'vmiddle' | 'bottom';+export type DistributeAxis = 'h' | 'v';++/** A selected entity's world AABB — edges, and the transform origin the move writes. */+export interface AlignBox {+ minX: number;+ maxX: number;+ minY: number;+ maxY: number;+ /** Transform origin (NOT the AABB center — a rotated/offset box's origin differs). */+ cx: number;+ cy: number;+}++/** Target transform origin per box for an align op (world y-up: top = maxY). */+export function alignTargets(boxes: AlignBox[], op: AlignOp): Array<{ cx: number; cy: number }> {+ const minX = Math.min(...boxes.map((b) => b.minX));+ const maxX = Math.max(...boxes.map((b) => b.maxX));+ const minY = Math.min(...boxes.map((b) => b.minY));+ const maxY = Math.max(...boxes.map((b) => b.maxY));+ const unionCx = (minX + maxX) / 2;+ const unionCy = (minY + maxY) / 2;+ return boxes.map((b) => {+ switch (op) {+ case 'left': return { cx: b.cx + (minX - b.minX), cy: b.cy };+ case 'right': return { cx: b.cx + (maxX - b.maxX), cy: b.cy };+ case 'hcenter': return { cx: unionCx, cy: b.cy };+ case 'top': return { cx: b.cx, cy: b.cy + (maxY - b.maxY) };+ case 'bottom': return { cx: b.cx, cy: b.cy + (minY - b.minY) };+ case 'vmiddle': return { cx: b.cx, cy: unionCy };+ }+ });+}++/** Target transform origin per box for equal edge-gap distribution. The two extreme+ * boxes stay put and define the span; the interior boxes are spread so the gaps+ * between adjacent edges are equal (Figma "distribute spacing"). Returned in input+ * order (< 3 boxes is a no-op → each box keeps its own origin). */+export function distributeTargets(boxes: AlignBox[], axis: DistributeAxis): Array<{ cx: number; cy: number }> {+ const targets = boxes.map((b) => ({ cx: b.cx, cy: b.cy }));+ const n = boxes.length;+ if (n < 3) return targets;+ const order = boxes.map((_, i) => i);+ if (axis === 'h') {+ order.sort((a, b) => boxes[a].minX - boxes[b].minX);+ const span = boxes[order[n - 1]].maxX - boxes[order[0]].minX;+ const sumW = boxes.reduce((s, b) => s + (b.maxX - b.minX), 0);+ const gap = (span - sumW) / (n - 1);+ let cursor = boxes[order[0]].minX;+ for (const i of order) {+ targets[i] = { cx: boxes[i].cx + (cursor - boxes[i].minX), cy: boxes[i].cy };+ cursor += (boxes[i].maxX - boxes[i].minX) + gap;+ }+ } else {+ order.sort((a, b) => boxes[a].minY - boxes[b].minY);+ const span = boxes[order[n - 1]].maxY - boxes[order[0]].minY;+ const sumH = boxes.reduce((s, b) => s + (b.maxY - b.minY), 0);+ const gap = (span - sumH) / (n - 1);+ let cursor = boxes[order[0]].minY;+ for (const i of order) {+ targets[i] = { cx: boxes[i].cx, cy: boxes[i].cy + (cursor - boxes[i].minY) };+ cursor += (boxes[i].maxY - boxes[i].minY) + gap;+ }+ }+ return targets;+}diff --git a/desktop/src/tools/alignTools.ts b/desktop/src/tools/alignTools.tsnew file mode 100644index 000000000..f5e06867a--- /dev/null+++ b/desktop/src/tools/alignTools.ts@@ -0,0 +1,67 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file alignTools.ts+ * @brief Multi-selection align + distribute — the Figma/UMG layout-precision tools+ * the viewport was missing. Every move lands through the ONE unified position+ * door, `SceneCommands.setEntityXY`, which routes a world point to a UINode+ * inset (Absolute), a Transform position (world entity), or a no-op (a+ * flex-flow node the layout owns) — so align is correct for every entity kind+ * without special-casing here. One gesture = one undo step. Geometry is in the+ * pure `alignMath` module.+ */+import { ViewportController } from '@/engine/ViewportController';+import { SceneCommands } from '@/engine/SceneCommands';+import { SceneModel } from '@/engine/SceneModel';+import { useSelection } from '@/store/selectionStore';+import { obbCorners } from '@/engine/viewportMath';+import { pruneDescendants, isFlowUINode, isOrphanUINode } from './transformTools';+import { alignTargets, distributeTargets, type AlignBox, type AlignOp, type DistributeAxis } from './alignMath';+import type { EntityId } from '@/types';++/** Positionable selection → each entity's world AABB. Excludes flex-flow / orphan+ * UI nodes (setEntityXY can't move them) and descendants of a selected ancestor+ * (already carried by their parent's move). */+function collectBoxes(): Array<{ sid: EntityId; box: AlignBox }> {+ const ids = pruneDescendants([...useSelection.getState().selectedIds]).filter(+ (sid) => !isFlowUINode(sid) && !isOrphanUINode(sid),+ );+ const out: Array<{ sid: EntityId; box: AlignBox }> = [];+ for (const sid of ids) {+ const rt = SceneModel.runtimeFor(sid);+ if (rt == null) continue;+ const obb = ViewportController.entityBounds(rt) ?? ViewportController.uiEntityWorldOBB(rt);+ if (!obb) continue;+ const corners = obbCorners(obb);+ const xs = corners.map((c) => c[0]);+ const ys = corners.map((c) => c[1]);+ out.push({+ sid,+ box: { minX: Math.min(...xs), maxX: Math.max(...xs), minY: Math.min(...ys), maxY: Math.max(...ys), cx: obb.cx, cy: obb.cy },+ });+ }+ return out;+}++function apply(boxes: Array<{ sid: EntityId; box: AlignBox }>, targets: Array<{ cx: number; cy: number }>, label: string): void {+ SceneCommands.beginGesture(label);+ try {+ boxes.forEach((b, i) => SceneCommands.setEntityXY(b.sid, targets[i].cx, targets[i].cy));+ } finally {+ SceneCommands.endGesture();+ }+}++/** Align the current multi-selection. No-op below two positionable entities. */+export function alignSelection(op: AlignOp): void {+ const boxes = collectBoxes();+ if (boxes.length < 2) return;+ apply(boxes, alignTargets(boxes.map((b) => b.box), op), `Align ${op}`);+}++/** Distribute the current multi-selection. No-op below three positionable entities. */+export function distributeSelection(axis: DistributeAxis): void {+ const boxes = collectBoxes();+ if (boxes.length < 3) return;+ apply(boxes, distributeTargets(boxes.map((b) => b.box), axis), `Distribute ${axis}`);+}diff --git a/desktop/src/tools/transformTools.ts b/desktop/src/tools/transformTools.tsindex ed8acd5db..37134b961 100644--- a/desktop/src/tools/transformTools.ts+++ b/desktop/src/tools/transformTools.ts@@ -92,7 +92,7 @@ function readTarget(sourceId: EntityId): Target | null {* carries its subtree, so transforming the descendant too would apply the* gesture twice (once directly, once through the parent).*/-function pruneDescendants(ids: readonly EntityId[]): EntityId[] {+export function pruneDescendants(ids: readonly EntityId[]): EntityId[] {const set = new Set(ids);return ids.filter((id) => {for (let p = SceneModel.entityBySource(id)?.parent; p != null; p = SceneModel.entityBySource(p)?.parent) {@@ -106,14 +106,14 @@ function pruneDescendants(ids: readonly EntityId[]): EntityId[] {* gesture has nothing to write (Absolute nodes move via inset edits instead —* see SceneCommands.setEntityXY). Rotation/scale are NOT layout-owned, so this* only gates `move`. */-function isFlowUINode(sourceId: EntityId): boolean {+export function isFlowUINode(sourceId: EntityId): boolean {const pos = SceneQuery.getFieldValue(sourceId, 'UINode', 'position');return pos != null && Number(pos) === 0;}/** A UINode with no Canvas ancestor (the UI layout root) — it has no layout box, so* it can't be positioned at all until it's placed under a Canvas. */-function isOrphanUINode(sourceId: EntityId): boolean {+export function isOrphanUINode(sourceId: EntityId): boolean {const e = SceneModel.entityBySource(sourceId);if (!e || !e.components.some((c) => c.type === 'UINode')) return false;for (let p = e.parent; p != null; p = SceneModel.entityBySource(p)?.parent ?? null) {diff --git a/desktop/tests/align-math.test.ts b/desktop/tests/align-math.test.tsnew file mode 100644index 000000000..6338ec3a4--- /dev/null+++ b/desktop/tests/align-math.test.ts@@ -0,0 +1,73 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { alignTargets, distributeTargets, type AlignBox } from '../src/tools/alignMath';++// Three boxes on one row (y-up, all at cy=5, height 10):+// A left 0..10 (w10, cx 5)+// B left 20..40 (w20, cx 30)+// C left 100..110 (w10, cx 105)+const row = (): AlignBox[] => [+ { minX: 0, maxX: 10, minY: 0, maxY: 10, cx: 5, cy: 5 },+ { minX: 20, maxX: 40, minY: 0, maxY: 10, cx: 30, cy: 5 },+ { minX: 100, maxX: 110, minY: 0, maxY: 10, cx: 105, cy: 5 },+];++describe('alignTargets', () => {+ it('left aligns every left edge to the minimum, preserving y', () => {+ const t = alignTargets(row(), 'left');+ // left edge → 0, so cx = 0 + halfWidth+ expect(t.map((p) => p.cx)).toEqual([5, 10, 5]);+ expect(t.every((p) => p.cy === 5)).toBe(true);+ });++ it('right aligns every right edge to the maximum', () => {+ const t = alignTargets(row(), 'right');+ // right edge → 110, so cx = 110 - halfWidth+ expect(t.map((p) => p.cx)).toEqual([105, 100, 105]);+ });++ it('hcenter puts every center on the union-bbox center', () => {+ const t = alignTargets(row(), 'hcenter');+ expect(t.map((p) => p.cx)).toEqual([55, 55, 55]); // (0+110)/2+ });++ it('top/bottom/vmiddle move on y only (y-up: top = maxY)', () => {+ const boxes: AlignBox[] = [+ { minX: 0, maxX: 10, minY: 0, maxY: 10, cx: 5, cy: 5 },+ { minX: 0, maxX: 10, minY: 40, maxY: 60, cx: 5, cy: 50 },+ ];+ expect(alignTargets(boxes, 'top').map((p) => p.cy)).toEqual([55, 50]); // top → 60+ expect(alignTargets(boxes, 'bottom').map((p) => p.cy)).toEqual([5, 10]); // bottom → 0 (B: 50+(0-40))+ expect(alignTargets(boxes, 'vmiddle').map((p) => p.cy)).toEqual([30, 30]); // (0+60)/2+ expect(alignTargets(boxes, 'top').every((p) => p.cx === 5)).toBe(true);+ });+});++describe('distributeTargets', () => {+ it('spreads interior boxes to equal edge gaps, extremes fixed', () => {+ const t = distributeTargets(row(), 'h');+ // span 110, widths 40, gap = 70/2 = 35: A stays, B.left→45 (cx 55), C stays.+ expect(t.map((p) => p.cx)).toEqual([5, 55, 105]);+ // gaps A→B and B→C are equal (35 each)+ const boxesAfter = row().map((b, i) => ({ ...b, minX: t[i].cx - (b.maxX - b.minX) / 2, maxX: t[i].cx + (b.maxX - b.minX) / 2 }));+ boxesAfter.sort((a, b) => a.minX - b.minX);+ expect(boxesAfter[1].minX - boxesAfter[0].maxX).toBeCloseTo(boxesAfter[2].minX - boxesAfter[1].maxX, 6);+ });++ it('is a no-op below three boxes', () => {+ const two = row().slice(0, 2);+ expect(distributeTargets(two, 'h')).toEqual(two.map((b) => ({ cx: b.cx, cy: b.cy })));+ });++ it('distributes vertically on y', () => {+ const col: AlignBox[] = [+ { minX: 0, maxX: 10, minY: 0, maxY: 10, cx: 5, cy: 5 },+ { minX: 0, maxX: 10, minY: 30, maxY: 50, cx: 5, cy: 40 },+ { minX: 0, maxX: 10, minY: 100, maxY: 110, cx: 5, cy: 105 },+ ];+ const t = distributeTargets(col, 'v');+ // span 110, heights 40, gap 35: bottom stays (cy5), mid.bottom→45 (cy55), top stays.+ expect(t.map((p) => p.cy)).toEqual([5, 55, 105]);+ });+});