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): the running game's gizmos snap to the grid

yhh4dddfcc107b6
diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.ts
index bda8044ad..99924d301 100644
--- a/desktop/src/engine/PlayRealm.ts
+++ b/desktop/src/engine/PlayRealm.ts
@@ -389,8 +389,8 @@ export class PlayRealmInstance {
/** 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 } : {}) });
+ dragTo(entityId: number, x: number, y: number, axis?: 'x' | 'y', snap?: number): void {
+ this.post({ type: 'estella:play:dragTo', entityId, x, y, ...(axis ? { axis } : {}), ...(snap ? { snap } : {}) });
}
/** Turn / resize a running entity by a relative amount (reverts on Stop). */
diff --git a/desktop/src/engine/entityOps.ts b/desktop/src/engine/entityOps.ts
index 861c8caae..4b6eecedf 100644
--- a/desktop/src/engine/entityOps.ts
+++ b/desktop/src/engine/entityOps.ts
@@ -77,13 +77,19 @@ export const EntityOps = {
*
* 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.
+ * on its canvas. Neither reimplements the other's projection. `snap` travels
+ * with a canvas point for the same reason the axis lock does: both resolve in
+ * world units, which only the side holding the camera has.
*/
- moveToPoint(ref: EntityRef, point: { world?: { x: number; y: number }; canvas?: { x: number; y: number } }, axis?: 'x' | 'y'): OpWorld {
+ moveToPoint(
+ ref: EntityRef,
+ point: { world?: { x: number; y: number }; canvas?: { x: number; y: number }; snap?: 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);
+ PlayRealm.dragTo(live, point.canvas.x, point.canvas.y, axis, point.snap);
PlayEdits.record(ref, 'Transform', 'position');
return 'live';
}
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index b1ba138b3..a0e1c9d72 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 = 6;
+export const PLAY_PROTOCOL_VERSION = 7;
/**
* The handshake check: `null` if the realm's reported protocol version is compatible
@@ -225,9 +225,10 @@ export type PlayOutbound =
*
* 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.
+ * where the camera is. The axis lock resolves after it, in world space — and
+ * so does `snap`, a grid in world units the resolved point lands on.
*/
- | { type: 'estella:play:dragTo'; entityId: number; x: number; y: number; axis?: 'x' | 'y' }
+ | { type: 'estella:play:dragTo'; entityId: number; x: number; y: number; axis?: 'x' | 'y'; snap?: number }
/**
* Turn or resize a running entity by a RELATIVE amount.
*
diff --git a/desktop/src/panels/PlayOverlay.tsx b/desktop/src/panels/PlayOverlay.tsx
index c9cd776a4..e44220786 100644
--- a/desktop/src/panels/PlayOverlay.tsx
+++ b/desktop/src/panels/PlayOverlay.tsx
@@ -24,6 +24,7 @@ import { PlayRealm } from '@/engine/PlayRealm';
import { EntityOps } from '@/engine/entityOps';
import { useSelection } from '@/store/selectionStore';
import { useEditorStore } from '@/store/editorStore';
+import { snapTo, quatAngleZ2D } from '@/engine/viewportMath';
import type { CanvasPoint, PlayOverlayBox } from '@/engine/playProtocol';
/** Half-size of the origin handle, in CSS px. */
@@ -75,8 +76,13 @@ export function PlayOverlay({ interactive }: Props) {
/** Pointer angle / distance about the origin when the gesture began (px). */
startAngle: number;
startDist: number;
- lastAngle: number;
- lastDist: number;
+ /** The live rotation / scale the gesture started from — what a snap grid is
+ * measured from, since the grid is the RESULT's, not the gesture's. */
+ startRot: number;
+ startScale: number;
+ /** Turn / factor already sent, so each message carries only the step left. */
+ sentTurn: number;
+ sentScale: number;
} | null>(null);
useEffect(() => {
@@ -118,6 +124,8 @@ export function PlayOverlay({ interactive }: Props) {
const anchor = overlay?.origin;
const onIt = anchor != null && (data?.grab != null || axis != null || grabbed(overlay!, anchor, p, size));
const polar = polarOf(p);
+ const live = PlayInspect.liveIdOf(selectedRef);
+ const t = live == null ? {} : PlayInspect.componentData(live, 'Transform');
drag.current = {
dx: anchor ? anchor.x - p.x : 0,
dy: anchor ? anchor.y - p.y : 0,
@@ -127,8 +135,10 @@ export function PlayOverlay({ interactive }: Props) {
from: { x: e.clientX, y: e.clientY },
startAngle: polar.angle,
startDist: polar.dist,
- lastAngle: polar.angle,
- lastDist: polar.dist,
+ startRot: quatAngleZ2D(t.rotation as { z?: number; w?: number } | undefined),
+ startScale: (t.scale as { x?: number } | undefined)?.x ?? 1,
+ sentTurn: 0,
+ sentScale: 1,
};
};
@@ -140,21 +150,34 @@ export function PlayOverlay({ interactive }: Props) {
d.moved = true;
}
const p = pointOf(e);
+ const ed = useEditorStore.getState();
if (tool === 'rotate' || tool === 'scale') {
- // Sent as the step since the last event, so the realm composes rather than
- // needing a gesture-start value it was never told.
+ // Measured from the gesture start and sent as the step still owed, so the
+ // realm goes on composing while the total lands where the grid says. A
+ // per-event step could not: each one would be snapped away to nothing.
const { angle, dist } = polarOf(p);
if (tool === 'rotate') {
- EntityOps.turnBy(selectedRef, angle - d.lastAngle);
- } else if (d.lastDist > 1) {
- const k = Math.max(0.05, dist / d.lastDist);
- EntityOps.resizeBy(selectedRef, { x: k, y: k });
+ const turned = angle - d.startAngle;
+ const want = ed.snapping
+ ? snapTo(d.startRot + turned, (ed.snapAngle * Math.PI) / 180) - d.startRot
+ : turned;
+ EntityOps.turnBy(selectedRef, want - d.sentTurn);
+ d.sentTurn = want;
+ } else if (d.startDist > 1) {
+ const f = dist / d.startDist;
+ const want = Math.max(0.01, ed.snapping && d.startScale
+ ? snapTo(d.startScale * f, ed.snapScale) / d.startScale
+ : f);
+ EntityOps.resizeBy(selectedRef, { x: want / d.sentScale, y: want / d.sentScale });
+ d.sentScale = want;
}
- d.lastAngle = angle;
- d.lastDist = dist;
return;
}
- EntityOps.moveToPoint(selectedRef, { canvas: { x: p.x + d.dx, y: p.y + d.dy } }, d.axis);
+ EntityOps.moveToPoint(
+ selectedRef,
+ { canvas: { x: p.x + d.dx, y: p.y + d.dy }, snap: ed.snapping ? ed.snapStep : 0 },
+ d.axis,
+ );
};
const onPointerUp = (e: React.PointerEvent) => {
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index a86e15945..6b470327c 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -2234,6 +2234,20 @@ export function Viewport() {
/>
))}
</div>
+ {/* The grid switch, where the docked toolbar's snap menu cannot reach: the
+ gizmos work on the running game, so what they snap to has to be sayable
+ there. The increments stay in that menu. */}
+ {playInViewport && inspectPlay && (
+ <div className="ov-cluster ov-cluster--v">
+ <OvTool
+ icon={Magnet}
+ toggle
+ label={`${t('vp.gridSnap')} (${snapping ? snapStep : t('vp.snapOff')})`}
+ active={snapping}
+ onClick={() => useEditorStore.setState({ snapping: !snapping })}
+ />
+ </div>
+ )}
</div>
{/* The engine canvas mounts here; pointer events drive pick + transform + pan. */}
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index 1e986370e..8f2e63d4d 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -20,7 +20,7 @@ import type { ESEngineModule } from 'esengine/wasm';
import { PLAY_PROTOCOL_VERSION } from './engine/playProtocol';
import type { PlayOutbound, PlayInbound, LiveVisibility, CanvasPoint, PlayOverlayBox } from './engine/playProtocol';
import { translateAssetHandles, projectRelative } from './engine/liveAssetRefs';
-import { pointInOBB, rankPickCandidates, worldToLocal2D, turnQuat2D, scaleVecBy, type PickCandidate } from '@/engine/viewportMath';
+import { pointInOBB, rankPickCandidates, worldToLocal2D, turnQuat2D, scaleVecBy, snapTo, type PickCandidate } from '@/engine/viewportMath';
import {
inspectEntity, findEntities, readResources, readSystems,
type Realm, type EntityFilter,
@@ -300,7 +300,7 @@ function transformBy(world: App['world'], entity: number, rotateBy?: number, sca
* 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 {
+function dragTo(world: App['world'], entity: number, nx: number, ny: number, axis?: 'x' | 'y', snap?: number): void {
const view = app?.getResource(CameraView);
const transformDef = getComponent('Transform');
const parentDef = getComponent('Parent');
@@ -312,10 +312,10 @@ function dragTo(world: App['world'], entity: number, nx: number, ny: number, axi
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;
+ // The lock and the grid resolve HERE, in world space, so a rotated camera
+ // cannot turn "along X" into a diagonal, nor a zoom change what a grid step is.
+ const wantX = axis === 'y' ? t.worldPosition.x : snapTo(target.x, snap ?? 0);
+ const wantY = axis === 'x' ? t.worldPosition.y : snapTo(target.y, snap ?? 0);
// `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
@@ -1145,7 +1145,7 @@ window.addEventListener('message', (e: MessageEvent) => {
}
break;
case 'estella:play:dragTo':
- if (app && data.entityId != null) dragTo(app.world, data.entityId, data.x, data.y, data.axis);
+ if (app && data.entityId != null) dragTo(app.world, data.entityId, data.x, data.y, data.axis, data.snap);
break;
case 'estella:play:transformBy':
if (app && data.entityId != null) transformBy(app.world, data.entityId, data.rotateBy, data.scaleBy);
diff --git a/desktop/tests/entity-ops.test.ts b/desktop/tests/entity-ops.test.ts
index 3fcddb991..370bab328 100644
--- a/desktop/tests/entity-ops.test.ts
+++ b/desktop/tests/entity-ops.test.ts
@@ -81,11 +81,19 @@ describe('while playing', () => {
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(PlayRealm.dragTo).toHaveBeenCalledWith(900, 0.5, 0.25, 'x', undefined);
expect(SceneCommands.setEntityVisible).not.toHaveBeenCalled();
expect(SceneCommands.setEntityXY).not.toHaveBeenCalled();
});
+ it('hands the grid to the side that can resolve it', () => {
+ // A grid step is world units; the canvas point is not. Snapping in the editor
+ // would need the game's camera, which is exactly what it does not have.
+ playingWith([{ live: 900, src: 3 }]);
+ EntityOps.moveToPoint(authoredRef(3), { canvas: { x: 0.5, y: 0.25 }, snap: 32 });
+ expect(PlayRealm.dragTo).toHaveBeenCalledWith(900, 0.5, 0.25, undefined, 32);
+ });
+
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();