The VS Code of video editing, built for agents.
TypeScript
Enhance editing and movement capabilities in the editor
konstantin-paulus6f26053a9f9e
diff --git a/apps/desktop/src/edit.ts b/apps/desktop/src/edit.tsindex 03143858..090a3002 100644--- a/apps/desktop/src/edit.ts+++ b/apps/desktop/src/edit.ts@@ -2,19 +2,6 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-// The write direction of a project's JSX: `applyEdits` puts a value the editor-// arrived at back into the attribute that produced it, and `stampProject`-// gives elements the durable names that survive edits made to the file in-// between.-//-// Elements are addressed the way `./source` stamps them: by position in-// document order until they have an `id`. Both directions walk every JSX-// element a file has, so the nth tag here is the nth stamp there — one order,-// two parsers.-//-// ts-morph owns the parsing and the printing. It edits the syntax tree and-// re-prints only what changed, so a write touches the attribute it was asked-// to and leaves the rest of the file byte for byte as its author wrote it.import { readdir, readFile, writeFile } from "node:fs/promises";import { join } from "node:path";@@ -61,7 +48,22 @@ export interface SourceInsert {text?: string;}-export type SourceEdit = SourceSet | SourceInsert;+/**+ * Moves the element named by `source` under the one named by `parent`, in+ * front of the child named by `before` or last. The element travels as it was+ * written — its own text, re-indented for where it lands — so a move is the+ * one edit that does not touch what an element says, only where it says it.+ * Both ends must be in one file: an element cannot move into another module's+ * JSX any more than a project could have put it there.+ */+export interface SourceMove {+ kind: "move";+ source: string;+ parent: string;+ before?: string;+}++export type SourceEdit = SourceSet | SourceInsert | SourceMove;export interface WriteResult {/** Sources that could not be written, as `id` or `id (prop)`. */@@ -277,6 +279,42 @@ function insertChild(sourceFile: SourceFile, parent: JsxTag, child: string, befoelse sourceFile.insertText(closing.getStart(), `\n${childIndent}${child}\n${indent}`);}+/**+ * Takes an element out of the tree, and the line it stood on when it had one+ * to itself, so what is left reads as if it had never been there.+ */+function cutElement(sourceFile: SourceFile, element: JsxElement | JsxSelfClosingElement): void {+ let start = element.getStart();+ let end = element.getEnd();++ if (element.isFirstNodeOnLine()) {+ const rest = sourceFile.getFullText().slice(end);+ const breakAt = rest.indexOf("\n");+ const trailing = breakAt === -1 ? rest : rest.slice(0, breakAt + 1);++ if (!trailing.trim()) {+ start = element.getStartLinePos();+ end += trailing.length;+ }+ }++ sourceFile.removeText(start, end);+}++/**+ * An element's text at a new indentation level. Every line after the first+ * moves by the same amount, so the block keeps the shape its author gave it;+ * a line indented less than the element itself is left where it is.+ */+function reindent(text: string, from: string, to: string): string {+ if (from === to) return text;++ return text+ .split("\n")+ .map((line, index) => (index === 0 || !line.startsWith(from) ? line : `${to}${line.slice(from.length)}`))+ .join("\n");+}+/** Whether an expression is a value rather than a way of computing one. */function isLiteral(node: Node): boolean {if (@@ -561,6 +599,11 @@ class SourceWriter {continue;}+ if (edit.kind === "move") {+ if (!this.moveElement(file, sourceFile, edit, ids, nextId)) skipped.push(edit.source);+ continue;+ }+const locator = locate(edit.source, ids)?.locator;if (locator === undefined) {skipped.push(edit.source);@@ -645,6 +688,75 @@ class SourceWriter {ids[edit.source] = formatSource(file, id);return true;}++ /**+ * Moves one element to another parent: its text is cut from where it stands+ * and put back under the new one. False when either end is not an element of+ * this file, or when the move is one no tree can hold (an element into+ * itself or into its own subtree).+ *+ * Everything is addressed by id first, since cutting the text renumbers the+ * positions the sources of an unnamed element would otherwise rely on.+ */+ private moveElement(+ file: string,+ sourceFile: SourceFile,+ edit: SourceMove,+ ids: Record<string, string>,+ nextId: () => string,+ ): boolean {+ const named = (source: string): string | undefined => {+ const address = locate(source, ids);+ // Ids are allocated per file, so one from elsewhere could name an+ // element here that has nothing to do with it.+ const locator = address?.file === file ? address.locator : undefined;+ const tag = locator === undefined ? undefined : findTag(sourceFile, locator);+ if (!tag) return undefined;+ const id = idOf(tag);+ if (id) return id;++ const minted = nextId();+ tag.addAttribute({ name: ID_ATTR, initializer: `"${minted}"` });+ // The write answers with it: the canvas addresses this element by+ // position until it hears otherwise, and the move invalidates that.+ ids[source] = formatSource(file, minted);+ return minted;+ };++ // Named before anything is cut, and each stamp re-parses, so the tags are+ // re-found from the ids afterwards rather than held across the edits.+ const id = named(edit.source);+ const parentId = named(edit.parent);+ if (!id || !parentId || id === parentId) return false;+ const beforeId = edit.before === undefined ? undefined : named(edit.before);+ if (edit.before !== undefined && !beforeId) return false;++ const element = elementOf(findTag(sourceFile, id)!);+ const parentElement = elementOf(findTag(sourceFile, parentId)!);+ if (parentElement.getAncestors().includes(element)) return false;++ if (beforeId !== undefined) {+ const anchor = elementOf(findTag(sourceFile, beforeId)!);+ if (anchor.getParent() !== parentElement) return false;+ }++ // Before any indentation is measured: ts-morph counts it in units of a+ // setting it does not learn from the file on its own.+ matchIndentation(sourceFile);+ const text = element.getText();+ const indent = element.getIndentationText();+ cutElement(sourceFile, element);++ const parent = findTag(sourceFile, parentId);+ const before = beforeId === undefined ? undefined : findTag(sourceFile, beforeId);+ // Neither can have gone with the cut (a destination inside what is being+ // moved was refused above), and the element is out of the tree by now, so+ // this is the file dropping out of the write rather than a skipped edit.+ if (!parent || (beforeId !== undefined && !before)) throw new Error("the element's new parent is gone");++ insertChild(sourceFile, parent, reindent(text, indent, elementOf(parent).getChildIndentationText()), before);+ return true;+ }}/** Stamps every source file of the project. Writes nothing to a fully named project. */diff --git a/apps/web/src/engine/camera-controller.tsx b/apps/web/src/engine/camera-controller.tsxindex 5ac2eaa6..5be7ba4a 100644--- a/apps/web/src/engine/camera-controller.tsx+++ b/apps/web/src/engine/camera-controller.tsx@@ -6,6 +6,7 @@ import { createMemo, onCleanup, onMount } from 'solid-js';import { useTrait, useWorld } from '@diffusionstudio/koota-solid';import { panCamera, setCamera, zoomCameraAt, getCamera, RenderSurface, getCameraMatrix, Root } from '@diffusionstudio/runtime';import { useEditor } from './hooks/use-editor';+import { updateCursor } from './input/cursor';import type { JSX } from 'solid-js';@@ -44,13 +45,7 @@ export function CameraController(): JSX.Element {let startE = 0;let startF = 0;- const updateCursor = (): void => {- const target = canvas();- if (target) {- target.style.cursor = panning ? 'grabbing' : (spaceHeld ? 'grab' : '');- }- };/** Pointer position in canvas CSS pixels. */const localPoint = (event: { clientX: number; clientY: number }): [x: number, y: number] => {@@ -68,7 +63,7 @@ export function CameraController(): JSX.Element {}panPointerId = null;- updateCursor();+ updateCursor(world, spaceHeld ? 'grab' : 'default');};const handleWheel = (event: WheelEvent): void => {@@ -104,7 +99,7 @@ export function CameraController(): JSX.Element {const camera = getCamera(world);startE = camera.e;startF = camera.f;- updateCursor();+ updateCursor(world, 'grabbing');};const handlePointerMove = (event: PointerEvent): void => {@@ -125,23 +120,21 @@ export function CameraController(): JSX.Element {const handleKeyDown = (event: KeyboardEvent): void => {if (event.code !== 'Space' || event.repeat || isEditable(event.target)) return;spaceHeld = true;- updateCursor();+ updateCursor(world, 'grab');};const handleKeyUp = (event: KeyboardEvent): void => {if (event.code !== 'Space') return;spaceHeld = false;- // Releasing space mid-drag ends the pan even though the pointer is- // still down, matching how the pan was armed.endPan();- updateCursor();+ updateCursor(world, 'default');};const handleBlur = (): void => {// Key-up never arrives when focus leaves mid-hold (⌘-tab, devtools).spaceHeld = false;endPan();- updateCursor();+ updateCursor(world, 'default');};onMount(() => {diff --git a/apps/web/src/engine/canvas.tsx b/apps/web/src/engine/canvas.tsxindex 632f4431..443580fc 100644--- a/apps/web/src/engine/canvas.tsx+++ b/apps/web/src/engine/canvas.tsx@@ -3,8 +3,6 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { onMount, type JSX } from 'solid-js';-import { createResizeObserver } from '@solid-primitives/resize-observer';-import { useEngineContext } from './context';/**@@ -17,11 +15,6 @@ export function EngineCanvas(): JSX.Element {let canvasRef!: HTMLCanvasElement;let containerRef!: HTMLDivElement;- createResizeObserver(- () => containerRef,- ({ width, height }) => engine.resize(width, height, window.devicePixelRatio)- );-onMount(() => {engine.mount(canvasRef);engine.start();diff --git a/apps/web/src/engine/create-engine.ts b/apps/web/src/engine/create-engine.tsindex 428d746b..378ace5b 100644--- a/apps/web/src/engine/create-engine.ts+++ b/apps/web/src/engine/create-engine.ts@@ -2,9 +2,14 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-import { renderSystem, transformSystem, playbackSystem, motionSystem, AudioEngine, createRuntimeWorld, RenderSurface, Time } from '@diffusionstudio/runtime';+import { renderSystem, transformSystem, playbackSystem, motionSystem, AudioEngine, createRuntimeWorld, RenderSurface, Time, ToolType, Tool, ChildOf, syncInteractiveState } from '@diffusionstudio/runtime';+import { hudSystem } from './hud';+import { createSignal, type Accessor, type Setter } from 'solid-js';+import { Hud, Keys, Pointer, PointerEvents, SnapLines } from './traits';+import { inputSystem } from './input/input-system';import type { RuntimeWorld } from '@diffusionstudio/runtime';+import type { CanvasPointerEvent, PointerEventType } from '@diffusionstudio/runtime';export interface EngineOptions {/**@@ -14,97 +19,150 @@ export interface EngineOptions {audioContext?: AudioContext;}-/**- * Browser-realtime engine shell: owns the koota runtime world, the canvas- * render surface, the AudioContext, and the requestAnimationFrame tick loop.- * Input, HUD, and DOM-sync systems are app-side concerns layered on top by- * the host, not part of this shell.- */class Engine {readonly world: RuntimeWorld;private canvas: HTMLCanvasElement | null = null;- private _running = false;private rafId: number | null = null;private lastTimestamp: number | null = null;+ private resizeObserver = new ResizeObserver(this.resize.bind(this));private readonly audioContext: AudioContext;private readonly ownsAudioContext: boolean;- private readonly runningListeners = new Set<(running: boolean) => void>();- private readonly boundLoop = (timestamp: number): void => this.loop(timestamp);++ private unsubscribe: (() => void)[] = [];+ private interactiveDirty = true;++ public running: Accessor<boolean>;+ private setRunning: Setter<boolean>;public constructor(projectId: string, options: EngineOptions = {}) {this.world = createRuntimeWorld(projectId);+ this.world.add(Pointer, Keys, SnapLines, Hud, PointerEvents);++ this.unsubscribe.push(+ this.world.onAdd(ChildOf('*'), () => (this.interactiveDirty = true)),+ this.world.onRemove(ChildOf('*'), () => (this.interactiveDirty = true)),+ );++ [this.running, this.setRunning] = createSignal(false);this.ownsAudioContext = options.audioContext === undefined;this.audioContext = options.audioContext ?? new AudioContext({ latencyHint: 'playback' });this.world.set(AudioEngine, { context: this.audioContext });}- public get running(): boolean {- return this._running;+ private readonly onClick = (event: MouseEvent) => {+ this.addEvent('click', event);}- /**- * Subscribe to start()/stop() transitions.- */- public onRunningChange(listener: (running: boolean) => void): () => void {- this.runningListeners.add(listener);- return () => this.runningListeners.delete(listener);+ private readonly onDoubleClick = (event: MouseEvent) => {+ this.addEvent('dblclick', event)}- private setRunning(running: boolean): void {- this._running = running;- for (const listener of this.runningListeners) listener(running);+ private readonly onPointerDown = (event: PointerEvent) => {+ this.addEvent('pointerdown', event)}- public mount(canvas: HTMLCanvasElement): void {- this.canvas = canvas;- this.world.set(RenderSurface, { canvas, ctx: canvas.getContext('2d') });+ private readonly onPointerMove = (event: PointerEvent) => {+ this.addEvent('pointermove', event)}- public resize(width: number, height: number, dpr = 1): void {- const pixelWidth = Math.round(width * dpr);- const pixelHeight = Math.round(height * dpr);+ private readonly onPointerUp = (event: PointerEvent) => {+ this.addEvent('pointerup', event)+ }- if (this.canvas) {- if (this.canvas.width !== pixelWidth || this.canvas.height !== pixelHeight) {- this.canvas.width = pixelWidth;- this.canvas.height = pixelHeight;- }- this.canvas.style.width = `${width}px`;- this.canvas.style.height = `${height}px`;- }+ private readonly onBlur = () => {+ this.world.get(Keys)!.clear();+ }- this.world.set(RenderSurface, { resolution: dpr });+ private readonly onKeyDown = (event: KeyboardEvent) => {+ if (+ this.world.get(Tool)?.value === ToolType.HAND+ || this.world.get(Keys)?.has(' ')+ ) return;++ const keys = this.world.get(Keys)!;+ keys.add(event.key.toLowerCase());++ if (event.key === 'Meta' || event.key === 'Control') {+ keys.add('mod');+ }}- /**- * Advance one frame at `timestamp` (ms, rAF clock). Public so a future- * host can drive the tick from its own rAF loop instead of this engine's- * internal one, to interleave app-side input/HUD systems around it.- */- public step(timestamp: number): void {+ private readonly onKeyUp = (event: KeyboardEvent) => {+ const keys = this.world.get(Keys)!;+ keys.delete(event.key.toLowerCase());++ if (event.key === 'Meta' || event.key === 'Control') {+ keys.delete('mod');+ }+ };++ private readonly loop = (timestamp: number): void => {const delta = this.lastTimestamp === null ? 0 : timestamp - this.lastTimestamp;this.lastTimestamp = timestamp;this.world.set(Time, { now: timestamp, delta });+ if (this.interactiveDirty) {+ syncInteractiveState(this.world);+ this.interactiveDirty = false;+ }++ this.runSystems();++ this.rafId = requestAnimationFrame(this.loop);+ }++ private resize(): void {+ const parent = this.canvas?.parentElement;+ if (!parent || !this.canvas) return;++ const { width, height } = parent.getBoundingClientRect();+ const dpr = window.devicePixelRatio;++ const pixelWidth = Math.round(width * dpr);+ const pixelHeight = Math.round(height * dpr);++ if (this.canvas.width !== pixelWidth || this.canvas.height !== pixelHeight) {+ this.canvas.width = pixelWidth;+ this.canvas.height = pixelHeight;+ }+ this.canvas.style.width = `${width}px`;+ this.canvas.style.height = `${height}px`;++ this.world.set(RenderSurface, { resolution: dpr });++ this.runSystems();+ }++ private addEvent(type: PointerEventType, event: PointerEvent | MouseEvent): void {+ if (!this.canvas) return;+ const rect = this.canvas.getBoundingClientRect();+ const resolution = this.world.get(RenderSurface)?.resolution ?? 1;++ this.world.get(PointerEvents)?.queue.push({+ type,+ clientX: (event.clientX - rect.left) * resolution,+ clientY: (event.clientY - rect.top) * resolution,+ button: event.button,+ } as CanvasPointerEvent);+ };++ private runSystems(): void {+ inputSystem(this.world);playbackSystem(this.world);motionSystem(this.world);transformSystem(this.world);renderSystem(this.world);- }-- private loop(timestamp: number): void {- this.step(timestamp);- this.rafId = requestAnimationFrame(this.boundLoop);+ hudSystem(this.world);}public start(): void {- if (this._running) return;+ if (this.running()) return;this.setRunning(true);this.lastTimestamp = null;- this.rafId = requestAnimationFrame(this.boundLoop);+ this.rafId = requestAnimationFrame(this.loop);}public stop(): void {@@ -115,12 +173,49 @@ class Engine {}}+ public mount(canvas: HTMLCanvasElement): void {+ this.unsubscribeEventListeners();++ this.canvas = canvas;+ this.world.set(RenderSurface, { canvas, ctx: canvas.getContext('2d') });++ canvas.addEventListener('click', this.onClick);+ canvas.addEventListener('dblclick', this.onDoubleClick);+ canvas.addEventListener('pointerdown', this.onPointerDown);+ canvas.addEventListener('pointermove', this.onPointerMove);+ window.addEventListener('pointerup', this.onPointerUp);+ window.addEventListener('pointercancel', this.onPointerUp);+ window.addEventListener('keydown', this.onKeyDown);+ window.addEventListener('keyup', this.onKeyUp);+ window.addEventListener('blur', this.onBlur);++ this.resizeObserver.observe(canvas.parentElement!);+ }+public dispose(): void {this.stop();if (this.ownsAudioContext) {this.audioContext.close();}this.world.destroy();+ this.unsubscribeEventListeners();+ this.world.get(PointerEvents)!.queue.length = 0;++ this.unsubscribe.forEach(unsubscribe => unsubscribe());+ this.unsubscribe.length = 0;+ }++ private unsubscribeEventListeners(): void {+ this.canvas?.removeEventListener('click', this.onClick);+ this.canvas?.removeEventListener('dblclick', this.onDoubleClick);+ this.canvas?.removeEventListener('pointerdown', this.onPointerDown);+ this.canvas?.removeEventListener('pointermove', this.onPointerMove);+ window.removeEventListener('pointerup', this.onPointerUp);+ window.removeEventListener('pointercancel', this.onPointerUp);+ window.removeEventListener('keydown', this.onKeyDown);+ window.removeEventListener('keyup', this.onKeyUp);+ window.removeEventListener('blur', this.onBlur);+ this.resizeObserver.disconnect();}}diff --git a/apps/web/src/engine/editor.ts b/apps/web/src/engine/editor.tsindex 8639377d..ce227549 100644--- a/apps/web/src/engine/editor.ts+++ b/apps/web/src/engine/editor.ts@@ -10,7 +10,7 @@* where the commands live.*/-import { Chars, getActiveEntity, getEntityChildren, getParentEntity, isText, Selected, setActive, Source, Stage } from '@diffusionstudio/runtime';+import { Active, Chars, getActiveEntity, getEntityChildren, getEntityTree, getParentEntity, isText, Selected, setActive, Source, Stage } from '@diffusionstudio/runtime';import { SOURCE_ATTR } from '@diffusionstudio/jsx';import { createRoot } from 'solid-js';@@ -53,7 +53,21 @@ export interface InsertEdit {text?: string;}-export type EntityEdit = PropEdit | InsertEdit;+/**+ * An element the editor moved to another parent: `parent` is the element it+ * belongs to now and `before`, when present, the sibling it was placed in+ * front of; without it, last. The entity is already there when this is+ * reported. Nesting is the one thing a prop cannot say, so this is its own+ * edit: dragging a clip into a scene has to move the element itself.+ */+export interface MoveEdit {+ kind: 'move';+ source: string;+ parent: string;+ before?: string;+}++export type EntityEdit = PropEdit | InsertEdit | MoveEdit;/*** Sources of elements the editor created that no write has named yet. Shaped@@ -244,6 +258,51 @@ export class DocumentEditor {return [...created.keys()].filter((entity) => !created.has(getParentEntity(entity)!));}+ /**+ * Moves `entity` under `parent`, in front of `anchor` or last, and reports+ * it so the element moves in the file too. The move goes through the+ * document, so the canvas ends up exactly where a project nesting it that+ * way would have put it (ordering included).+ */+ public reparent(entity: Entity, parent: Entity, anchor?: Entity): boolean {+ const source = entity.get(Source)?.value;+ const parentSource = parent.get(Source)?.value;+ if (!source || !parentSource) return false;+ if (getParentEntity(entity) === parent && anchor === undefined) return false;+ // Checked here rather than left to the document: a move into itself is+ // a no-op there (nothing to report), and one into its own subtree is+ // caught only after the node has already left the parent it had.+ if (entity === parent || getEntityTree(this.world, entity).includes(parent)) return false;++ const wasActive = entity.has(Active);++ try {+ this.document.insertNode({ entity: parent }, { entity }, anchor ? { entity: anchor } : undefined);+ } catch {+ return false;+ }++ // An anchor the file does not name cannot be pointed at; appending is+ // the honest answer, and where the document put it either way.+ const before = anchor?.get(Source)?.value;++ this.sink?.({+ kind: 'move',+ source,+ parent: parentSource,+ ...(before ? { before } : {}),+ });++ // Only a root holds the active tag (see world/observers), so a node+ // that just stopped being one has lost it; the file hears that here+ // rather than keeping an `active` its own rules would strip on reload.+ if (wasActive && !entity.has(Active)) {+ this.reportEdit(entity, 'active', false);+ }++ return true;+ }+/*** Re-stamps entities whose element earned a name, as `old source -> new`.* Queried rather than remembered: the entities that survived are the onesdiff --git a/apps/web/src/engine/hooks/index.ts b/apps/web/src/engine/hooks/index.tsindex b3dabbcf..e2b0f41e 100644--- a/apps/web/src/engine/hooks/index.ts+++ b/apps/web/src/engine/hooks/index.ts@@ -4,6 +4,5 @@export * from './use-active-scene';export * from './use-camera';-export * from './use-running';export * from './use-editor';export * from './use-tool';diff --git a/apps/web/src/engine/hooks/use-running.ts b/apps/web/src/engine/hooks/use-running.tsdeleted file mode 100644index 57e22fd9..00000000--- a/apps/web/src/engine/hooks/use-running.ts+++ /dev/null@@ -1,17 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { createSignal, onCleanup, type Accessor } from 'solid-js';--import { useEngineContext } from '../context';--/** Reactive read of whether the engine's tick loop is running. */-export function useRunning(): Accessor<boolean> {- const engine = useEngineContext();- const [running, setRunning] = createSignal(engine.running);-- onCleanup(engine.onRunningChange(setRunning));-- return running;-}diff --git a/apps/web/src/engine/hud/hud-system.ts b/apps/web/src/engine/hud/hud-system.tsnew file mode 100644index 00000000..4fd14b42--- /dev/null+++ b/apps/web/src/engine/hud/hud-system.ts@@ -0,0 +1,500 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++/**+ * Everything drawn over the document rather than in it: snap guides, hover+ * outlines, scene headers, the selection mask with its handles, and the+ * marquee. Runs after the render system, on the same canvas and in device+ * pixels (the transform is reset per piece, so nothing here inherits the+ * camera).+ *+ * Drawing is also where the HUD's hit regions come from: a control is pushed+ * with the handler it answers to right after it is painted, so the regions+ * come out in paint order, on top of the entity regions the render system+ * left, and the input system can test them back to front next frame.+ */++import { Not, Or } from 'koota';+import {+ Active, Computed, Culled, FrameRate, Generating, Geometry, Group, Hidden,+ HitRegions, Hovering, Name, Playback, RenderSurface, Root, Selected,+ Sequential, ChildOf,+ entityQuad, entityWorldMat, getMaskSelection, getSelectionMask, invert2D,+ multiply2D, rectToQuad, rotate2D, scale2D, store, transformPoint,+ translate2D,+} from '@diffusionstudio/runtime';++import { Hud, Keys, SnapLines } from '../traits';+import {+ handleLabelInteraction, handleMaskInteraction, handlePlayInteraction,+ handleResizeInteraction, handleRotateInteraction,+} from '../input/interactions';+import { getMarqueeQuad } from '../input/snapping';+import { getMountedNameInput } from './name-input';++import type { Entity, World } from 'koota';+import type { Mat2D } from '@diffusionstudio/runtime';++const ACCENT = '#008CFF';+const SNAP_COLOR = '#F43535';+const HEADER_FONT = '350 11px Inter, sans-serif';+const HEADER_HEIGHT = 22;+const ACTIVE_BADGE_WIDTH = 60;++type Ctx2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;++export function hudSystem(world: World): void {+ const ctx = world.get(RenderSurface)?.ctx;+ if (!ctx) return;++ const resolution = world.get(RenderSurface)?.resolution ?? 1;++ drawSnapLines(world, ctx, resolution);+ drawHoverOutlines(world, ctx, resolution);++ for (const entity of world.query(Or(Name, Generating), ChildOf(world.get(Root)!), Not(Culled), Not(Hidden))) {+ drawHeader(world, ctx, entity, resolution);+ }++ // The mask is in the way of the thing it is around while that thing is+ // being moved, so it steps aside for the gesture.+ const mask = world.get(Hud)?.mode === 'moving' ? null : getSelectionMask(world);++ if (mask) {+ drawSelectionMask(world, ctx, mask, resolution);+ drawDimensions(world, ctx, mask, resolution);+ }++ drawMarquee(world, ctx, resolution);+}++function drawSnapLines(world: World, ctx: Ctx2D, resolution: number): void {+ const lines = world.get(SnapLines)?.list ?? [];+ // Mod suspends snapping, so the guides go with it.+ if (lines.length === 0 || world.get(Keys)?.has('mod')) return;++ const cross = Math.round(3 * resolution);++ ctx.resetTransform();+ ctx.beginPath();++ for (const line of lines) {+ ctx.moveTo(line.from.x, line.from.y);+ ctx.lineTo(line.to.x, line.to.y);+ }++ ctx.closePath();+ ctx.strokeStyle = SNAP_COLOR;+ ctx.lineWidth = Math.round(resolution);+ ctx.stroke();++ ctx.beginPath();++ for (const line of lines) {+ for (const point of [line.from, line.to]) {+ ctx.moveTo(point.x - cross, point.y - cross);+ ctx.lineTo(point.x + cross, point.y + cross);+ ctx.moveTo(point.x - cross, point.y + cross);+ ctx.lineTo(point.x + cross, point.y - cross);+ }+ }++ ctx.stroke();+}++function drawHoverOutlines(world: World, ctx: Ctx2D, resolution: number): void {+ for (const entity of world.query(Hovering, Or(Geometry, Group), Not(Sequential), Not(Culled))) {+ ctx.resetTransform();+ traceQuad(ctx, entityQuad(world, entity));+ ctx.strokeStyle = ACCENT;+ ctx.lineWidth = Math.round(2 * resolution);+ ctx.stroke();+ }+}++/**+ * The bar above a top-level node: play button, name, active badge, duration.+ * It sits in the node's own rotation, one line above its top edge.+ */+function drawHeader(world: World, ctx: Ctx2D, entity: Entity, resolution: number): void {+ const generating = entity.has(Generating);+ const label = generating ? 'Generating...' : entity.get(Name)?.value;+ if (!label) return;++ const header = getHeaderLayout(world, entity, resolution);+ const playback = entity.get(Playback);+ const selected = entity.has(Selected);+ const active = entity.has(Active);+ const foreground = selected ? '#cce8ff' : 'rgba(242, 242, 242, 0.64)';+ const regions = world.get(HitRegions)!.list;++ ctx.setTransform(header.mat.a, header.mat.b, header.mat.c, header.mat.d, header.mat.e, header.mat.f);++ let labelStart = 0;++ if (playback) {+ ctx.save();+ ctx.fillStyle = foreground;+ if (playback.playing) {+ ctx.translate(4, 3);+ ctx.fill(PAUSE_PATH);+ } else {+ ctx.translate(2, 3);+ ctx.fill(PLAY_PATH);+ }+ ctx.restore();+ labelStart = 18;++ regions.push({+ target: { kind: 'hud', id: 'play', entity, quad: rectToQuad(header.mat, 16, HEADER_HEIGHT) },+ callback: handlePlayInteraction,+ });+ }++ const labelMat = multiply2D(header.mat, translate2D(labelStart, 3));+ ctx.setTransform(labelMat.a, labelMat.b, labelMat.c, labelMat.d, labelMat.e, labelMat.f);+ ctx.textAlign = 'left';+ ctx.textBaseline = 'top';+ ctx.font = HEADER_FONT;++ const badgeWidth = active ? ACTIVE_BADGE_WIDTH : 0;+ const fitted = fitTextToWidth(ctx, label, header.width - labelStart - badgeWidth);++ if (fitted) {+ ctx.fillStyle = foreground;+ ctx.fillText(fitted.value, 0, 0);++ regions.push({+ target: {+ kind: 'hud',+ id: 'label',+ entity,+ quad: rectToQuad(multiply2D(header.mat, translate2D(labelStart, 0)), fitted.width + 4, HEADER_HEIGHT),+ },+ callback: handleLabelInteraction,+ });+ }++ // The rename field is a DOM element over the canvas, so it is placed in CSS+ // pixels and turned to match the header it stands in for.+ const renaming = getMountedNameInput();+ if (renaming && renaming.entity === entity) {+ const inputMat = multiply2D(header.mat, translate2D(labelStart - 3, 0));+ renaming.input.style.left = `${inputMat.e / resolution}px`;+ renaming.input.style.top = `${inputMat.f / resolution}px`;+ renaming.input.style.transform = `rotate(${header.rotation}deg)`;+ renaming.input.style.width = `${(fitted?.width ?? 40) + 4}px`;+ }++ if (active && header.width > badgeWidth) {+ ctx.setTransform(header.mat.a, header.mat.b, header.mat.c, header.mat.d, header.mat.e, header.mat.f);+ ctx.translate((fitted?.width ?? 0) + labelStart + 4, 0);+ ctx.beginPath();+ ctx.roundRect(0, 0, 40, 16, 2);+ ctx.closePath();+ ctx.fillStyle = selected ? '#013e70' : '#292929';+ ctx.fill();++ ctx.translate(4, 3);+ ctx.textAlign = 'left';+ ctx.textBaseline = 'top';+ ctx.font = HEADER_FONT;+ ctx.fillStyle = foreground;+ ctx.fillText('Active', 0, 0);+ }++ if (playback && (fitted?.width ?? 0) + badgeWidth + 60 < header.width) {+ ctx.setTransform(header.mat.a, header.mat.b, header.mat.c, header.mat.d, header.mat.e, header.mat.f);+ ctx.translate(header.width, 3);+ ctx.textAlign = 'right';+ ctx.textBaseline = 'top';+ ctx.font = '400 11px JetBrains Mono';++ const seconds = (store(world, Computed).duration[entity.id()] ?? 0) / (world.get(FrameRate)?.value ?? 30);+ const minutes = Math.floor(seconds / 60).toString().padStart(2, '0');+ const rest = Math.floor(seconds % 60).toString().padStart(2, '0');++ if (selected) {+ ctx.globalAlpha = 0.7;+ ctx.fillStyle = '#cce8ff';+ } else {+ ctx.fillStyle = 'rgba(121, 121, 121, 1)';+ }++ ctx.fillText(`${minutes}:${rest}`, 0, 0);+ ctx.globalAlpha = 1;+ }+}++/**+ * The box around the selection, its resize/rotate regions, and the handles+ * that show where they are. Rotation regions sit outside the corners, resize+ * regions straddle the edges, and both are pushed whether or not a handle is+ * painted there.+ */+function drawSelectionMask(world: World, ctx: Ctx2D, mask: { width: number; height: number; mat: Mat2D }, resolution: number): void {+ const { width, height, mat } = mask;+ const selection = getMaskSelection(world);+ const regions = world.get(HitRegions)!.list;++ ctx.resetTransform();+ ctx.beginPath();++ // Each node's own outline, then the box around them all.+ for (const entity of selection) {+ const quad = entityQuad(world, entity);+ ctx.moveTo(quad[0].x, quad[0].y);+ ctx.lineTo(quad[1].x, quad[1].y);+ ctx.lineTo(quad[2].x, quad[2].y);+ ctx.lineTo(quad[3].x, quad[3].y);+ ctx.lineTo(quad[0].x, quad[0].y);+ }++ ctx.setTransform(mat.a, mat.b, mat.c, mat.d, mat.e, mat.f);+ ctx.rect(0, 0, width, height);+ ctx.closePath();+ ctx.strokeStyle = ACCENT;+ ctx.lineWidth = Math.round(selection.length === 1 ? 2 : 1 * resolution);+ ctx.stroke();++ regions.push({+ target: { kind: 'hud', id: 'selection', quad: rectToQuad(mat, width, height) },+ callback: handleMaskInteraction,+ });++ const rotate = Math.round(16 * resolution);+ const rotateRegions: Record<string, [x: number, y: number]> = {+ rtl: [-rotate, -rotate],+ rtr: [width, -rotate],+ rbr: [width, height],+ rbl: [-rotate, height],+ };++ for (const [id, [x, y]] of Object.entries(rotateRegions)) {+ regions.push({+ target: { kind: 'hud', id, quad: rectToQuad(multiply2D(mat, translate2D(x, y)), rotate, rotate) },+ callback: handleRotateInteraction,+ });+ }++ const edge = Math.round(6 * resolution);+ const edgeOffset = Math.round(edge / 2);+ const edgeRegions: Record<string, [x: number, y: number, width: number, height: number]> = {+ l: [-edgeOffset, 0, edge, height],+ t: [0, -edgeOffset, width, edge],+ r: [width - edgeOffset, 0, edge, height],+ b: [0, height - edgeOffset, width, edge],+ };++ for (const [id, [x, y, regionWidth, regionHeight]] of Object.entries(edgeRegions)) {+ regions.push({+ target: { kind: 'hud', id, quad: rectToQuad(multiply2D(mat, translate2D(x, y)), regionWidth, regionHeight) },+ callback: handleResizeInteraction,+ });+ }++ ctx.beginPath();++ const handle = Math.round(8 * resolution);+ const handleOffset = Math.round(handle / 2);+ const corners: Record<string, [x: number, y: number]> = {+ tl: [-handleOffset, -handleOffset],+ tr: [width - handleOffset, -handleOffset],+ br: [width - handleOffset, height - handleOffset],+ bl: [-handleOffset, height - handleOffset],+ };++ for (const [id, [x, y]] of Object.entries(corners)) {+ const corner = multiply2D(mat, translate2D(x, y));+ ctx.setTransform(corner.a, corner.b, corner.c, corner.d, corner.e, corner.f);+ ctx.rect(0, 0, handle, handle);++ regions.push({+ target: { kind: 'hud', id, quad: rectToQuad(corner, handle, handle) },+ callback: handleResizeInteraction,+ });+ }++ ctx.closePath();+ ctx.fillStyle = '#FFFFFF';+ ctx.fill();+ ctx.strokeStyle = ACCENT;+ ctx.lineWidth = Math.round(resolution);+ ctx.stroke();+}++/** The size readout under the selection, in document units rather than pixels. */+function drawDimensions(world: World, ctx: Ctx2D, mask: { width: number; height: number; mat: Mat2D }, resolution: number): void {+ const selection = getMaskSelection(world);++ let rotation = 0;+ let center = 0;+ let x = 0;+ let y = 0;+ let width = 0;+ let height = 0;++ if (selection.length === 1) {+ const entity = selection[0]!;+ const computed = store(world, Computed);+ const eid = entity.id();++ // The bottom edge, left to right: the readout follows it.+ const bottom = [...entityQuad(world, entity)]+ .sort((a, b) => b.y - a.y)+ .slice(0, 2)+ .sort((a, b) => a.x - b.x);++ rotation = Math.atan2(bottom[1]!.y - bottom[0]!.y, bottom[1]!.x - bottom[0]!.x) * 180 / Math.PI;+ center = Math.hypot(bottom[0]!.x - bottom[1]!.x, bottom[0]!.y - bottom[1]!.y) / 2;+ width = (computed.width[eid] ?? 0) * Math.abs(computed.scaleX[eid] ?? 1);+ height = (computed.height[eid] ?? 0) * Math.abs(computed.scaleY[eid] ?? 1);+ x = bottom[0]!.x;+ y = bottom[0]!.y;+ } else {+ // Undo the view transform as a direction, not a point, so the readout+ // is the selection's size in the document rather than on screen.+ const inverse = invert2D(entityWorldMat(world, null));+ inverse.e = 0;+ inverse.f = 0;+ const size = transformPoint(inverse, mask.width, mask.height);++ width = size.x;+ height = size.y;+ x = mask.mat.e;+ y = mask.mat.f + mask.height;+ center = mask.width / 2;+ }++ ctx.save();++ let mat = translate2D(x, y);+ mat = multiply2D(mat, rotate2D(rotation));+ mat = multiply2D(mat, scale2D(resolution, resolution));+ mat = multiply2D(mat, translate2D(center / resolution, 16));+ ctx.setTransform(mat.a, mat.b, mat.c, mat.d, mat.e, mat.f);++ const text = `${Math.round(width * 100) / 100}x${Math.round(height * 100) / 100}`;+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';+ ctx.font = '11px Inter, sans-serif';++ const boxWidth = ctx.measureText(text).width + 8;++ ctx.beginPath();+ ctx.roundRect(-boxWidth / 2, -9, boxWidth, 16, 3);+ ctx.closePath();+ ctx.fillStyle = ACCENT;+ ctx.fill();++ ctx.fillStyle = '#FFFFFF';+ ctx.fillText(text, 0, 0);+ ctx.restore();+}++function drawMarquee(world: World, ctx: Ctx2D, resolution: number): void {+ const marquee = getMarqueeQuad(world);+ if (!marquee) return;++ ctx.resetTransform();+ ctx.beginPath();+ ctx.rect(+ marquee[0].x,+ marquee[0].y,+ marquee[1].x - marquee[0].x,+ marquee[3].y - marquee[0].y,+ );+ ctx.closePath();++ ctx.fillStyle = ACCENT;+ ctx.globalAlpha = 0.15;+ ctx.fill();+ ctx.globalAlpha = 1;+ ctx.strokeStyle = ACCENT;+ ctx.lineWidth = Math.round(resolution);+ ctx.stroke();+}++function traceQuad(ctx: Ctx2D, quad: ReturnType<typeof entityQuad>): void {+ ctx.beginPath();+ ctx.moveTo(quad[0].x, quad[0].y);+ ctx.lineTo(quad[1].x, quad[1].y);+ ctx.lineTo(quad[2].x, quad[2].y);+ ctx.lineTo(quad[3].x, quad[3].y);+ ctx.closePath();+}++/**+ * Where a node's header goes: along its top edge, one bar above it, in the+ * node's rotation but not its scale (the header is chrome, it keeps its size+ * whatever the zoom).+ */+function getHeaderLayout(world: World, entity: Entity, resolution: number): { rotation: number; width: number; mat: Mat2D } {+ const top = [...entityQuad(world, entity)]+ .sort((a, b) => a.y - b.y)+ .slice(0, 2)+ .sort((a, b) => a.x - b.x);++ const rotation = Math.atan2(top[1]!.y - top[0]!.y, top[1]!.x - top[0]!.x) * 180 / Math.PI;+ const width = Math.hypot(top[0]!.x - top[1]!.x, top[0]!.y - top[1]!.y) / resolution;+ const radians = rotation * Math.PI / 180;+ const cos = Math.cos(radians);+ const sin = Math.sin(radians);++ return {+ rotation,+ width,+ mat: {+ a: cos * resolution,+ b: sin * resolution,+ c: -sin * resolution,+ d: cos * resolution,+ e: top[0]!.x - HEADER_HEIGHT * (-sin * resolution),+ f: top[0]!.y - HEADER_HEIGHT * (cos * resolution),+ },+ };+}++const PLAY_PATH = new Path2D("M0.24182 0.0683919C0.3919 -0.017789 0.5784 -0.022846 0.73338 0.0550586L9.7334 4.57886C9.8974 4.66129 10 4.82339 10 4.99999C10 5.17659 9.8974 5.3387 9.7334 5.42113L0.73338 9.94494C0.5784 10.0228 0.3919 10.0178 0.24182 9.93161C0.0917501 9.84541 0 9.69065 0 9.5238V0.476191C0 0.309296 0.0917501 0.154573 0.24182 0.0683919ZM1 1.26595V8.73399L8.4288 4.99999L1 1.26595Z");+const PAUSE_PATH = new Path2D("M1.08197 0.518868C1.08197 0.232311 0.839803 0 0.540984 0C0.242203 0 0 0.232311 0 0.518868V9.48113C0 9.76764 0.242203 10 0.540984 10C0.839803 10 1.08197 9.76764 1.08197 9.48113V0.518868ZM6 0.518868C6 0.232311 5.75784 0 5.45902 0C5.1602 0 4.91803 0.232311 4.91803 0.518868V9.48113C4.91803 9.76764 5.1602 10 5.45902 10C5.75784 10 6 9.76764 6 9.48113V0.518868Z");++const TEXT_WIDTHS = new Map<string, number>();++/** `text`, elided with an ellipsis if it does not fit, or null if nothing does. */+function fitTextToWidth(ctx: Ctx2D, text: string, maxWidth: number): { value: string; width: number } | null {+ const widthOf = (value: string): number => {+ let width = TEXT_WIDTHS.get(value);+ if (width === undefined) {+ width = ctx.measureText(value).width;+ TEXT_WIDTHS.set(value, width);+ }+ return width;+ };++ const width = widthOf(text);+ if (width <= maxWidth) return { value: text, width };++ const available = maxWidth - widthOf('...');+ if (available <= 0) return null;++ let start = 0;+ let end = text.length;+ let best = 0;++ while (start <= end) {+ const mid = Math.floor((start + end) / 2);++ if (widthOf(text.slice(0, mid)) <= available) {+ best = mid;+ start = mid + 1;+ } else {+ end = mid - 1;+ }+ }++ if (best === 0) return null;++ const value = `${text.slice(0, best)}...`;+ return { value, width: widthOf(value) };+}diff --git a/apps/web/src/engine/hud/index.ts b/apps/web/src/engine/hud/index.tsnew file mode 100644index 00000000..ca873b0d--- /dev/null+++ b/apps/web/src/engine/hud/index.ts@@ -0,0 +1,6 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++export * from './hud-system';+export * from './name-input';diff --git a/apps/web/src/engine/hud/name-input.ts b/apps/web/src/engine/hud/name-input.tsnew file mode 100644index 00000000..a414fc40--- /dev/null+++ b/apps/web/src/engine/hud/name-input.ts@@ -0,0 +1,90 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++/**+ * Renaming a node from its header. The header itself is painted on the canvas,+ * which cannot take text input, so an <input> is placed over it for the+ * duration; the HUD moves it into place each frame while it is mounted.+ */++import { Name, RenderSurface } from '@diffusionstudio/runtime';++import { getDocumentEditor } from '../editor';++import type { Entity, World } from 'koota';++const INPUT_STYLE = {+ position: 'absolute',+ transformOrigin: 'left top',+ font: '350 11px Inter, sans-serif',+ color: 'var(--foreground)',+ background: 'var(--input)',+ border: '1px solid var(--primary)',+ borderRadius: '2px',+ outline: 'none',+ padding: '0 0 0 2px',+ margin: '0',+ boxSizing: 'content-box',+ zIndex: '1000',+};++let mounted: { input: HTMLInputElement; entity: Entity } | null = null;++/** The input being edited, for the HUD to position. */+export function getMountedNameInput(): { input: HTMLInputElement; entity: Entity } | null {+ return mounted;+}++/** Opens the rename field over `entity`'s header. */+export function mountNameInput(world: World, entity: Entity): void {+ const canvas = world.get(RenderSurface)?.canvas;+ const container = canvas instanceof HTMLCanvasElement ? canvas.parentElement : null;+ if (!container) return;++ const editor = getDocumentEditor(world);+ const original = entity.get(Name)?.value ?? '';++ const input = document.createElement('input');+ input.type = 'text';+ input.value = original;+ Object.assign(input.style, INPUT_STYLE);++ input.addEventListener('input', () => {+ editor.editProperty(entity, 'name', input.value);+ });++ input.addEventListener('blur', () => {+ input.remove();+ // A name is what the node is called; an empty one is not an edit.+ if (!input.value.trim()) editor.editProperty(entity, 'name', original);+ if (mounted?.input === input) mounted = null;+ });++ input.addEventListener('keydown', (event) => {+ // The canvas shortcuts are listening on the window; typing here is not+ // for them.+ event.stopPropagation();++ if (event.key === 'Escape') {+ editor.editProperty(entity, 'name', original);+ input.blur();+ }++ if (event.key === 'Enter') {+ input.blur();+ }+ });++ container.appendChild(input);+ input.focus();+ input.select();++ mounted = { input, entity };+}++/** Closes the rename field, if one is open. */+export function unmountNameInput(): void {+ mounted?.input.blur();+ mounted = null;+}diff --git a/apps/web/src/engine/index.ts b/apps/web/src/engine/index.tsindex 5e91e211..a1cdfe0c 100644--- a/apps/web/src/engine/index.ts+++ b/apps/web/src/engine/index.ts@@ -8,3 +8,6 @@ export * from './canvas';export * from './camera-controller';export * from './hooks';export * from './editor';+export * from './traits';+export * from './input';+export * from './hud';diff --git a/apps/web/src/engine/input/cursor.ts b/apps/web/src/engine/input/cursor.tsnew file mode 100644index 00000000..c279773e--- /dev/null+++ b/apps/web/src/engine/input/cursor.ts@@ -0,0 +1,69 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++/**+ * The stage cursor. Resize and rotate handles point along the selection's+ * rotation, which no CSS keyword can express, so those are drawn as inline+ * SVG and handed to `cursor:` as a data URL. Everything that touches the+ * cursor goes through here (the camera controller included), so the last+ * writer always wins and no one has to know who wrote it before.+ *+ * The timeline keeps its own copy in `components/engine/utils/cursor.ts`+ * (trim cursors, the old world's canvas); this one is the stage's.+ */++import { RenderSurface } from '@diffusionstudio/runtime';++import type { World } from 'koota';++const CORNER_SVG = `<path d='m19.7432 17.0869-4.072 4.068 2.829 2.828-8.473-.013-.013-8.47 2.841 2.842 4.075-4.068 1.414-1.415-2.844-2.842h8.486v8.484l-2.83-2.827z' fill='%23fff'/><path d='m18.6826 16.7334-4.427 4.424 1.828 1.828-5.056-.016-.014-5.054 1.842 1.841 4.428-4.422 2.474-2.475-1.844-1.843h5.073v5.071l-1.83-1.828z' fill='%23000'/>`;+const EDGE_SVG = `<path d='m9 17.9907v.005l5.997 5.996.001-3.999h1.999 2.02v4l5.98-6.001-5.98-5.999.001 4.019-2.021.002h-2l.001-4.022zm1.411.003 3.587-3.588-.001 2.587h3.5 2.521v-2.585l3.565 3.586-3.564 3.585-.001-2.585h-2.521l-3.499-.001-.001 2.586z' fill='%23fff'/><path d='m17.4971 18.9932h2.521v2.586l3.565-3.586-3.565-3.585v2.605h-2.521-3.5v-2.607l-3.586 3.587 3.586 3.586v-2.587z' fill='%23000'/>`;+const ROTATE_SVG = `<path d="M22.4789 9.45728L25.9935 12.9942L22.4789 16.5283V14.1032C18.126 14.1502 14.6071 17.6737 14.5675 22.0283H17.05L13.513 25.543L9.97889 22.0283H12.5674C12.6071 16.5691 17.0214 12.1503 22.4789 12.1031L22.4789 9.45728Z" fill="black"/><path fill-rule="evenodd" clip-rule="evenodd" d="M21.4789 7.03223L27.4035 12.9945L21.4789 18.9521V15.1868C18.4798 15.6549 16.1113 18.0273 15.649 21.0284H19.475L13.5128 26.953L7.55519 21.0284H11.6189C12.1243 15.8155 16.2679 11.6677 21.4789 11.1559L21.4789 7.03223ZM22.4789 12.1031C17.0214 12.1503 12.6071 16.5691 12.5674 22.0284H9.97889L13.513 25.543L17.05 22.0284H14.5675C14.5705 21.6896 14.5947 21.3558 14.6386 21.0284C15.1157 17.4741 17.9266 14.6592 21.4789 14.1761C21.8063 14.1316 22.1401 14.1069 22.4789 14.1032V16.5284L25.9935 12.9942L22.4789 9.45729L22.4789 12.1031Z" fill="white"/>`;++const STATIC_CURSORS = new Set(['default', 'pointer', 'cross', 'move', 'grab', 'grabbing', 'text', 'zoom-in', 'zoom-out']);++function getCursorCss(svg: string, rotation: number, turn: number, color: string, hx = 16, hy = 16): string {+ // Keep the drop shadow pointing the same way whatever the cursor's own+ // rotation is, so a rotated handle still reads as lit from one side.+ const angle = (-turn - rotation) * (Math.PI / 180);+ const dx = Math.cos(angle) - Math.sin(angle);+ const dy = Math.sin(angle) + Math.cos(angle);++ return `url("data:image/svg+xml,<svg height='32' width='32' viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' style='color: ${color};'><defs><filter id='shadow' y='-40%' x='-40%' width='180px' height='180%' color-interpolation-filters='sRGB'><feDropShadow dx='${dx}' dy='${dy}' stdDeviation='1.2' flood-opacity='.5'/></filter></defs><g fill='none' transform='rotate(${rotation + turn} 16 16)' filter='url(%23shadow)'>${svg.replaceAll(`"`, `'`)}</g></svg>") ${hx} ${hy}, pointer`;+}++const CURSORS: Record<string, (rotation: number, color: string) => string> = {+ 'ew-resize': (rotation, color) => getCursorCss(EDGE_SVG, rotation, 0, color),+ 'ns-resize': (rotation, color) => getCursorCss(EDGE_SVG, rotation, 90, color),+ 'nesw-resize': (rotation, color) => getCursorCss(CORNER_SVG, rotation, 0, color),+ 'nwse-resize': (rotation, color) => getCursorCss(CORNER_SVG, rotation, 90, color),+ 'nwse-rotate': (rotation, color) => getCursorCss(ROTATE_SVG, rotation, 0, color),+ 'nesw-rotate': (rotation, color) => getCursorCss(ROTATE_SVG, rotation, 90, color),+ 'senw-rotate': (rotation, color) => getCursorCss(ROTATE_SVG, rotation, 180, color),+ 'swne-rotate': (rotation, color) => getCursorCss(ROTATE_SVG, rotation, 270, color),+};++export type CursorType =+ | 'default' | 'pointer' | 'cross' | 'grab' | 'grabbing' | 'move' | 'text'+ | 'zoom-in' | 'zoom-out'+ | 'ew-resize' | 'ns-resize' | 'nesw-resize' | 'nwse-resize'+ | 'nesw-rotate' | 'nwse-rotate' | 'swne-rotate' | 'senw-rotate';++// What each canvas is showing, so an unchanged cursor is not rebuilt (the SVG+// data URL is rebuilt from scratch on every write otherwise).+const current = new WeakMap<HTMLCanvasElement, string>();++/** Points the stage cursor at `type`, turned by `rotation` radians. */+export function updateCursor(world: World, type: CursorType, rotation = 0, color = 'black'): void {+ const canvas = world.get(RenderSurface)?.canvas;+ if (!(canvas instanceof HTMLCanvasElement)) return;++ const hash = `${type}-${rotation}-${color}`;+ if (current.get(canvas) === hash) return;+ current.set(canvas, hash);++ canvas.style.cursor = STATIC_CURSORS.has(type)+ ? type+ : CURSORS[type]?.(rotation * 180 / Math.PI, color) ?? 'default';+}diff --git a/apps/web/src/engine/input/index.ts b/apps/web/src/engine/input/index.tsnew file mode 100644index 00000000..243de954--- /dev/null+++ b/apps/web/src/engine/input/index.ts@@ -0,0 +1,8 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++export * from './cursor';+export * from './input-system';+export * from './interactions';+export * from './snapping';diff --git a/apps/web/src/engine/input/input-system.ts b/apps/web/src/engine/input/input-system.tsnew file mode 100644index 00000000..0b041a7a--- /dev/null+++ b/apps/web/src/engine/input/input-system.ts@@ -0,0 +1,153 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { HitRegions, Tool, ToolType, Dragging, Hovering, isPointerInEntity, pointInQuad } from '@diffusionstudio/runtime';++import { Keys, Pointer, PointerEvents } from '../traits';+import { updateCursor } from './cursor';+import { handleCanvasInteraction, handleGeometryInteraction } from './interactions';++import type { World } from 'koota';+import type { CanvasPointerEvent, DispatchedPointerEvent, HitRegion, PointerEventType } from '@diffusionstudio/runtime';++/**+ * A region's identity for enter/leave: two headers are two targets even+ * though both are called 'label'.+ */+function targetKey(region: HitRegion | null): string | null {+ if (region === null) return null;+ const { target } = region;+ return target.kind === 'entity' ? `entity:${target.id}` : `${target.id}:${target.entity ?? ''}`;+}++function hitTest(world: World, event: CanvasPointerEvent): HitRegion | null {+ const regions = world.get(HitRegions)?.list ?? [];++ for (let i = regions.length - 1; i >= 0; i--) {+ const region = regions[i]!;++ if (region.target.kind === 'entity') {+ if (region.target.id.isAlive() && isPointerInEntity(world, region.target.id, { x: event.clientX, y: event.clientY })) {+ return region;+ }+ } else if (pointInQuad(event.clientX, event.clientY, region.target.quad)) {+ return region;+ }+ }++ return null;+};++function dispatch(+ world: World,+ region: HitRegion,+ event: CanvasPointerEvent,+ type: PointerEventType = event.type+): void {+ let handler: (world: World, event: DispatchedPointerEvent) => void;++ if (region.callback) {+ handler = region.callback;+ } else if (region.target.kind === 'entity') {+ handler = handleGeometryInteraction;+ } else {+ handler = handleCanvasInteraction;+ }++ handler(world, { ...event, type, target: region.target });+};+++let hovered: HitRegion | null = null;+let dragged: HitRegion | null = null;++export function inputSystem(world: World) {+ const panning = world.get(Tool)?.value === ToolType.HAND || (world.get(Keys)?.has(' ') ?? false);+ const queue = world.get(PointerEvents)?.queue ?? [];+ const regions = world.get(HitRegions)?.list ?? [];++ for (const event of queue) {+ world.set(Pointer, {+ clientX: event.clientX,+ clientY: event.clientY,+ button: event.button,+ ...(event.type === 'pointerdown' && {+ phase: 'pressed' as const,+ dragStartX: event.clientX,+ dragStartY: event.clientY,+ }),+ ...(event.type === 'pointerup' && { phase: 'lifted' as const }),+ });++ if (panning) continue;++ // The other buttons belong to the camera (middle-drag pans) and to+ // the browser's own menu, so they never start a gesture here.+ if ((event.type === 'pointerdown' || event.type === 'pointerup') && event.button !== 0) continue;++ const region = hitTest(world, event);++ if (event.type === 'pointermove') {+ const left = targetKey(hovered);+ const entered = targetKey(region);++ if (left !== entered && hovered !== null) {+ // The region is a frame old, so what it points at may be gone.+ if (hovered.target.kind === 'entity' && hovered.target.id.isAlive()) {+ hovered.target.id.remove(Hovering);+ }+ dispatch(world, hovered, event, 'pointerleave');+ }++ if (left !== entered && region !== null) {+ if (region.target.kind === 'entity') region.target.id.add(Hovering);+ dispatch(world, region, event, 'pointerenter');+ }++ hovered = region;+ }++ // A press arms the drag on whatever it landed on, and every move+ // until the release goes to that same region, wherever the pointer+ // has traveled since.+ if (event.type === 'pointerdown') {+ if (region !== null) {+ if (region.target.kind === 'entity') region.target.id.add(Dragging);+ dispatch(world, region, event, 'dragstart');+ }+ dragged = region;+ }++ if (event.type === 'pointermove' && dragged !== null) {+ dispatch(world, dragged, event, 'drag');+ }++ if (event.type === 'pointerup' && dragged !== null) {+ if (dragged.target.kind === 'entity' && dragged.target.id.isAlive()) {+ dragged.target.id.remove(Dragging);+ }+ dispatch(world, dragged, event, 'dragend');+ dragged = null;+ }++ if (region !== null) {+ dispatch(world, region, event);+ }+ }++ if (panning) {+ updateCursor(world, world.get(Pointer)!.phase === 'pressed' ? 'grabbing' : 'grab');+ for (const entity of world.query(Hovering)) {+ entity.remove(Hovering);+ }+ for (const entity of world.query(Dragging)) {+ entity.remove(Dragging);+ }+ hovered = null;+ dragged = null;+ }++ queue.length = 0;+ regions.length = 0;+}diff --git a/apps/web/src/engine/input/interactions.ts b/apps/web/src/engine/input/interactions.tsnew file mode 100644index 00000000..877c8068--- /dev/null+++ b/apps/web/src/engine/input/interactions.ts@@ -0,0 +1,839 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++/**+ * What a pointer gesture does to the document: select, move, resize, rotate.+ * The input system dispatches to these through the hit regions the render and+ * HUD systems left behind, so a handler only ever sees the region it was+ * pushed for plus the pointer.+ *+ * Every change goes through `DocumentEditor`, because the source is the+ * document: dragging a node writes `x`/`y` back to the element it came from,+ * and dropping it into a scene moves the element under that scene's, the same+ * way the inspector or a hand edit would. One bitecs behavior did not come+ * along, for want of a way to say it: alt-drag duplication, which would have+ * to author a copy of a subtree the JSX may well be generating.+ */++import {+ AudioEngine, ChildOf, Computed, Culled, Geometry, Group, Hovering,+ Interactive, KeepAspectRatio, Playback, RenderSurface, Root, Scene,+ Selected, Skew, Time,+ computeGroupBounds, computeLocalMatrix, decompose2D, entityAnchor,+ entityOffset, entityQuad, entityWorldMat, enterEntity,+ findKeyframeTrackEntity, getParentEntity, getParentNode, getSceneAncestor,+ getSelection, getSelectionMask, identity2D, invert2D, isPointerInEntity,+ multiply2D, quadCenter, quadsIntersect, rectToQuad, rotate2D, scale2D,+ store, syncInteractiveState, transformPoint, translate2D,+} from '@diffusionstudio/runtime';+import { Not, Or } from 'koota';++import { getDocumentEditor } from '../editor';+import { Hud, Keys, Pointer, SnapLines } from '../traits';+import { updateCursor, type CursorType } from './cursor';+import { mountNameInput } from '../hud/name-input';+import {+ buildSnapCandidatesFromCorners, buildSnapCandidatesFromQuad, findSnapTarget,+ getMarqueeQuad, getSelectionMaskSnapshot, getSnapCandidatesSnapshot,+ getTransformSnapshot, snapshotSelectionMask, snapshotSelectionTransforms,+ snapshotSnapCandidates,+} from './snapping';++import type { Entity, World } from 'koota';+import type { DispatchedPointerEvent, Mat2D, Point, Quad } from '@diffusionstudio/runtime';++/** How close, in CSS pixels, a candidate has to be before a gesture snaps to it. */+const SNAP_DISTANCE = 6;++/** A pointer that traveled less than this between press and release is a click. */+const CLICK_DISTANCE = 4;++type Handle = 'tl' | 'tr' | 'bl' | 'br' | 't' | 'r' | 'b' | 'l';++/**+ * Which way each handle grows the mask, as a multiple of the pointer delta:+ * -1 pulls the near edge, 1 pushes the far one, 0 leaves the axis alone.+ */+const HANDLE_FACTOR: Record<Handle, Point> = {+ tl: { x: -1, y: -1 }, tr: { x: 1, y: -1 },+ bl: { x: -1, y: 1 }, br: { x: 1, y: 1 },+ t: { x: 0, y: -1 }, r: { x: 1, y: 0 },+ b: { x: 0, y: 1 }, l: { x: -1, y: 0 },+};++const HANDLE_CURSOR: Record<Handle, CursorType> = {+ tl: 'nwse-resize', tr: 'nesw-resize',+ bl: 'nesw-resize', br: 'nwse-resize',+ t: 'ns-resize', b: 'ns-resize',+ l: 'ew-resize', r: 'ew-resize',+};++const isHandle = (id: string): id is Handle => id in HANDLE_FACTOR;++const keys = (world: World): Set<string> => world.get(Keys) ?? new Set<string>();++const resolution = (world: World): number => world.get(RenderSurface)?.resolution ?? 1;++/** The pointer now, in the mask's local space. */+function pointerPoint(world: World, mat: Mat2D): Point {+ const pointer = world.get(Pointer)!;+ return transformPoint(invert2D(mat), pointer.clientX, pointer.clientY);+}++/** Where the pointer went down, in the mask's local space. */+function pointerOrigin(world: World, mat: Mat2D): Point {+ const pointer = world.get(Pointer)!;+ return transformPoint(invert2D(mat), pointer.dragStartX, pointer.dragStartY);+}++function clearHovering(world: World): void {+ for (const entity of world.query(Hovering)) {+ entity.remove(Hovering);+ }+}++/**+ * The default handler for the entity regions the render system pushes: a+ * press selects, and from there the node moves like any selection.+ */+export function handleGeometryInteraction(world: World, event: DispatchedPointerEvent): void {+ const editor = getDocumentEditor(world);++ if (event.type === 'dragstart' && event.target.kind === 'entity') {+ editor.select(event.target.id, { extend: keys(world).has('shift') });+ handleMaskInteraction(world, event);+ }++ if (event.type === 'drag' || event.type === 'dragend') {+ handleMaskInteraction(world, event);+ }++ // Double-click drills into a container: its children become the things the+ // canvas can hit, and the one under the pointer takes the selection.+ if (event.type === 'dblclick' && event.target.kind === 'entity') {+ const child = enterEntity(world, event.target.id, { x: event.clientX, y: event.clientY });+ if (child !== null) editor.select(child);+ }++ if (world.get(Pointer)!.phase === 'lifted') {+ updateCursor(world, 'default');+ }+}++/**+ * The default handler for the stage itself: dragging draws a marquee, a click+ * on nothing drops the selection and leaves whatever was drilled into.+ */+export function handleCanvasInteraction(world: World, event: DispatchedPointerEvent): void {+ const editor = getDocumentEditor(world);++ if (event.type === 'dragstart') {+ world.set(Hud, { mode: 'marquee' });+ }++ if (event.type === 'drag' && world.get(Hud)?.mode === 'marquee') {+ const marquee = getMarqueeQuad(world);++ if (marquee) {+ editor.select([...world.query(Interactive, Or(Geometry, Group), Not(Culled))]+ .filter((entity) => quadsIntersect(marquee, entityQuad(world, entity))));+ }++ updateCursor(world, 'default');+ }++ if (event.type === 'dragend') {+ world.set(Hud, { mode: 'idle' });+ }++ if (event.type === 'pointerup') {+ const pointer = world.get(Pointer)!;+ const dx = event.clientX - pointer.dragStartX;+ const dy = event.clientY - pointer.dragStartY;++ if (Math.hypot(dx, dy) < CLICK_DISTANCE * resolution(world)) {+ editor.clearSelection();+ syncInteractiveState(world);+ clearHovering(world);+ }+ }++ if (world.get(Pointer)!.phase === 'lifted') {+ updateCursor(world, 'default');+ }+}++/** The play/pause button on a scene header. */+export function handlePlayInteraction(world: World, event: DispatchedPointerEvent): void {+ if (event.type !== 'click' || event.target.kind !== 'hud') return;++ // The region is a frame old, so what it points at may be gone.+ const entity = event.target.entity;+ const playback = entity?.isAlive() ? entity.get(Playback) : undefined;+ if (!entity || !playback) return;++ entity.set(Playback, { playing: !playback.playing, speed: 1 });++ // Audio is gated until the context has seen a gesture; this is one.+ const context = world.get(AudioEngine)?.context;+ if (context instanceof AudioContext) void context.resume();+}++/** The name on a scene header: selects, renames on double-click, drags the node. */+export function handleLabelInteraction(world: World, event: DispatchedPointerEvent): void {+ if (event.target.kind !== 'hud') return;++ const entity = event.target.entity;+ if (!entity?.isAlive()) return;+ const editor = getDocumentEditor(world);++ if (event.type === 'pointerenter') {+ clearHovering(world);+ entity.add(Hovering);+ }++ if (event.type === 'pointerleave') {+ clearHovering(world);+ }++ if (event.type === 'dragstart') {+ editor.select(entity, { extend: keys(world).has('shift') });+ }++ if (event.type === 'dblclick') {+ mountNameInput(world, entity);+ }++ if (event.type === 'click' && entity.has(Scene)) {+ editor.activate(entity);+ }++ handleMaskInteraction(world, event);+}++/** A resize handle on the selection mask: an edge, or a corner. */+export function handleResizeInteraction(world: World, event: DispatchedPointerEvent): void {+ if (event.target.kind !== 'hud' || !isHandle(event.target.id)) return;++ const handle = event.target.id;+ const factor = HANDLE_FACTOR[handle];++ if (event.type === 'dragstart') {+ snapshotSelectionMask(world);+ snapshotSelectionTransforms(world);+ snapshotSnapCandidates(world);+ world.get(SnapLines)!.list.length = 0;+ }++ const snapshot = getSelectionMaskSnapshot();++ if (event.type === 'drag' && snapshot) {+ const oldTr = snapshot.mat;+ const selection = getSelection(world);+ const snapLines = world.get(SnapLines)!.list;+ snapLines.length = 0;++ const current = pointerPoint(world, oldTr);+ const origin = pointerOrigin(world, oldTr);++ // The pointer delta, in the mask's own space, as a size change.+ const deltaX = current.x - origin.x;+ const deltaY = current.y - origin.y;+ let deltaWidth = deltaX * factor.x;+ let deltaHeight = deltaY * factor.y;++ // Lock the ratio when shift is held or every selected node keeps one.+ // Both paths run the same math, so the pivot and position stay+ // consistent; when the stored ratio matches the mask's, the Size+ // observer's own enforcement is a no-op on top.+ const lockAspect = keys(world).has('shift')+ || (selection.length > 0 && selection.every((entity) => entity.has(KeepAspectRatio)));++ if (lockAspect && snapshot.width > 0 && snapshot.height > 0) {+ const w0 = snapshot.width;+ const h0 = snapshot.height;++ if (factor.x !== 0 && factor.y !== 0) {+ // Project the pointer delta onto the pivot-to-corner diagonal: the+ // dragged corner lands on the closest point of the ratio-locked+ // ray, so the cursor stays with it without ever leaping past.+ const t = (deltaX * factor.x * w0 + deltaY * factor.y * h0) / (w0 * w0 + h0 * h0);+ deltaWidth = w0 * t;+ deltaHeight = h0 * t;+ } else if (factor.y === 0) {+ deltaHeight = h0 * ((w0 + deltaWidth) / w0 - 1);+ } else {+ deltaWidth = w0 * ((h0 + deltaHeight) / h0 - 1);+ }+ }++ // The pivot is the handle's opposite: factor -1 -> 1 (far edge),+ // 0 -> 0.5 (center), 1 -> 0 (near edge).+ let pivotX = snapshot.width * (1 - factor.x) / 2;+ let pivotY = snapshot.height * (1 - factor.y) / 2;++ // Alt resizes about the center, so both edges move.+ const fromCenter = keys(world).has('alt');+ if (fromCenter) {+ pivotX = snapshot.width * 0.5;+ pivotY = snapshot.height * 0.5;+ deltaWidth *= 2;+ deltaHeight *= 2;+ }++ let newWidth = snapshot.width + deltaWidth;+ let newHeight = snapshot.height + deltaHeight;++ // Snap the vertices the handle is dragging to nearby candidates.+ {+ const scaled = scaleAbout(pivotX, pivotY, newWidth / snapshot.width, newHeight / snapshot.height);+ const proposed = rectToQuad(multiply2D(oldTr, scaled), snapshot.width, snapshot.height);+ const candidates = getSnapCandidatesSnapshot();+ const dragged = buildSnapCandidatesFromCorners(handleVertices(handle, proposed));+ const threshold = SNAP_DISTANCE * resolution(world);++ if (lockAspect) {+ // The dragged corner travels the ray from the pivot (s = 0) through+ // its proposed position (s = the proposed scale), so each snap line+ // crosses it at exactly one scale: (span + offset) / span on the+ // snapped axis. Take whichever ratio is closest to 1 and apply it+ // to both axes, which is what keeps the ratio.+ const base = transformPoint(oldTr, pivotX, pivotY);+ const ratioOf = (snap: { sourcePoint: Point; offset: number } | null, axis: 'x' | 'y'): number | null => {+ if (!snap) return null;+ const span = snap.sourcePoint[axis] - base[axis];+ return Math.abs(span) < 1e-9 ? null : (span + snap.offset) / span;+ };++ const xSnap = findSnapTarget(dragged.x, candidates.x, threshold, 'x');+ const ySnap = findSnapTarget(dragged.y, candidates.y, threshold, 'y');+ const ratioX = ratioOf(xSnap, 'x');+ const ratioY = ratioOf(ySnap, 'y');+ const takeX = ratioX !== null && (ratioY === null || Math.abs(ratioX - 1) <= Math.abs(ratioY - 1));+ const snap = takeX ? xSnap : (ratioY !== null ? ySnap : null);+ const ratio = takeX ? ratioX : ratioY;++ if (snap && ratio !== null) {+ newWidth *= ratio;+ newHeight *= ratio;+ snapLines.push({+ from: {+ x: base.x + (snap.sourcePoint.x - base.x) * ratio,+ y: base.y + (snap.sourcePoint.y - base.y) * ratio,+ },+ to: snap.targetPoint,+ });+ }+ } else {+ const xSnap = factor.x !== 0 ? findSnapTarget(dragged.x, candidates.x, threshold, 'x') : null;+ const ySnap = factor.y !== 0 ? findSnapTarget(dragged.y, candidates.y, threshold, 'y') : null;++ if (xSnap) snapLines.push({+ from: { x: xSnap.sourcePoint.x + xSnap.offset, y: xSnap.sourcePoint.y + (ySnap?.offset ?? 0) },+ to: xSnap.targetPoint,+ });++ if (ySnap) snapLines.push({+ from: { x: ySnap.sourcePoint.x + (xSnap?.offset ?? 0), y: ySnap.sourcePoint.y + ySnap.offset },+ to: ySnap.targetPoint,+ });++ if (xSnap || ySnap) {+ // The snap offset is in device pixels; turn it back into a size+ // change in the mask's space (direction only, hence no translation).+ const inverse = invert2D(oldTr);+ inverse.e = 0;+ inverse.f = 0;+ const correction = transformPoint(inverse, xSnap?.offset ?? 0, ySnap?.offset ?? 0);+ const both = fromCenter ? 2 : 1;++ if (factor.x !== 0) deltaWidth += correction.x * factor.x * both;+ if (factor.y !== 0) deltaHeight += correction.y * factor.y * both;++ newWidth = snapshot.width + deltaWidth;+ newHeight = snapshot.height + deltaHeight;+ }+ }+ }++ const localScale = scaleAbout(pivotX, pivotY, newWidth / snapshot.width, newHeight / snapshot.height);++ // Groups have no Size of their own, so a group resize transforms its+ // direct children instead; the group's own transform is left alone and+ // the transform system rebuilds its box from where the children ended up.+ const hasGroup = selection.some((entity) => entity.has(Group));+ // The single-node wobble guard does not apply to a group's children:+ // they are scaled in the group's space, not their own, so their+ // rotation and skew really can change.+ const writeAngles = selection.length > 1 || hasGroup;++ for (const selected of selection) {+ const targets = selected.has(Group)+ ? [...world.query(Or(Geometry, Group), ChildOf(selected))]+ : [selected];++ for (const entity of targets) {+ resizeNode(world, entity, oldTr, localScale, writeAngles);++ // The walk is parent-first, so a group's box is built from its+ // children's transforms as of the previous frame. Refresh this one+ // now, or a rotated group's box lags a frame behind and drifts.+ if (hasGroup) computeLocalMatrix(world, entity);+ }++ if (selected.has(Group)) {+ keepGroupPlaced(world, selected);+ }+ }++ updateResizeCursor(world, handle);+ }++ if (event.type === 'dragend') {+ world.get(SnapLines)!.list.length = 0;+ }++ if (world.get(Pointer)!.phase === 'lifted') {+ updateResizeCursor(world, handle);+ }+}++/**+ * Applies the mask's scale to one node: the delta is composed in world space,+ * mapped back through the node's parent, and decomposed into the size,+ * position and angles the source can spell.+ */+function resizeNode(world: World, entity: Entity, oldTr: Mat2D, localScale: Mat2D, writeAngles: boolean): void {+ const snapshot = getTransformSnapshot(entity);+ if (!snapshot) return;++ const editor = getDocumentEditor(world);+ const anchor = entityAnchor(world, entity);++ // Take the pivot out of the old local transform: the decomposition puts it+ // back from the new size.+ const oldLocal = multiply2D(+ snapshot.localTransform,+ translate2D(snapshot.width * anchor.x, snapshot.height * anchor.y),+ );++ const decomposed = decompose2D(inParentSpace(oldTr, localScale, snapshot.parentTransform, oldLocal));++ // Scale the authored size by how much the node's own scale changed, which+ // is what accounts for it sitting at an angle to the mask.+ const width = snapshot.width * (decomposed.scaleX / snapshot.scaleX);+ const height = snapshot.height * (decomposed.scaleY / snapshot.scaleY);+ const offset = entityOffset(world, entity);++ editor.editProperty(entity, 'width', Math.round(width));+ editor.editProperty(entity, 'height', Math.round(height));+ editor.editProperty(entity, 'x', Math.round(decomposed.x - width * anchor.x - offset.x));+ editor.editProperty(entity, 'y', Math.round(decomposed.y - height * anchor.y - offset.y));++ if (writeAngles) {+ editor.editProperty(entity, 'rotation', Math.round(decomposed.rotation * 100) / 100);+ // Skew has no JSX spelling, so it is written to the trait alone and+ // lasts until the project is rendered again.+ entity.add(Skew);+ entity.set(Skew, {+ x: Math.round(decomposed.skewX * 100) / 100,+ y: Math.round(decomposed.skewY * 100) / 100,+ });+ }+}++/**+ * Holds a resized group where the gesture found it. Its local matrix pivots+ * about anchor x box size, and resizing the children moves that pivot; with a+ * rotation, the (I - R)·pivot term then shifts the group's translation and+ * drags the whole group off the pointer. The children were computed against+ * the group's transform as of dragstart, so put it back.+ */+function keepGroupPlaced(world: World, group: Entity): void {+ const snapshot = getTransformSnapshot(group);+ if (!snapshot) return;++ // Rebuild the box from the children that just moved, so the new pivot is+ // the one the group will actually be drawn with.+ computeGroupBounds(world, group);++ const computed = store(world, Computed);+ const gid = group.id();+ const anchor = entityAnchor(world, group);+ const pivotX = anchor.x * (computed.width[gid] ?? 0);+ const pivotY = anchor.y * (computed.height[gid] ?? 0);++ // computeLocalMatrix builds L = T(position) · K, K = T(pivot)·linear·T(-pivot).+ // The resize leaves `linear` alone, so solve T(position) = L · K⁻¹ for the+ // new pivot and the rebuilt matrix comes out equal to the snapshot again.+ const desired = snapshot.localTransform;+ const linear: Mat2D = { a: desired.a, b: desired.b, c: desired.c, d: desired.d, e: 0, f: 0 };+ const position = multiply2D(desired, invert2D(scaleFree(pivotX, pivotY, linear)));+ const offset = entityOffset(world, group);+ const editor = getDocumentEditor(world);++ editor.editProperty(group, 'x', Math.round(position.e - offset.x));+ editor.editProperty(group, 'y', Math.round(position.f - offset.y));+ computeLocalMatrix(world, group);+}++/** A rotation handle, just outside a corner of the selection mask. */+export function handleRotateInteraction(world: World, event: DispatchedPointerEvent): void {+ if (event.type === 'dragstart') {+ snapshotSelectionTransforms(world);+ snapshotSelectionMask(world);+ }++ const snapshot = getSelectionMaskSnapshot();++ if (event.type === 'drag' && snapshot) {+ const oldTr = snapshot.mat;+ const editor = getDocumentEditor(world);+ const selection = getSelection(world);++ // One node turns about its own anchor, several about the center of the+ // box they share.+ const single = selection.length === 1 ? entityAnchor(world, selection[0]!) : null;+ const pivotX = snapshot.width * (single?.x ?? 0.5);+ const pivotY = snapshot.height * (single?.y ?? 0.5);++ const current = pointerPoint(world, oldTr);+ const origin = pointerOrigin(world, oldTr);+ const delta = Math.atan2(current.y - pivotY, current.x - pivotX)+ - Math.atan2(origin.y - pivotY, origin.x - pivotX);++ const localRotate = rotateAbout(pivotX, pivotY, delta * 180 / Math.PI);++ for (const entity of selection) {+ const state = getTransformSnapshot(entity);+ if (!state) continue;++ const anchor = entityAnchor(world, entity);+ const anchorX = state.width * anchor.x;+ const anchorY = state.height * anchor.y;+ const oldLocal = multiply2D(state.localTransform, translate2D(anchorX, anchorY));++ let newLocal = inParentSpace(oldTr, localRotate, state.parentTransform, oldLocal);+ let decomposed = decompose2D(newLocal);++ // Shift snaps to global 15 degree steps. The snap has to turn about+ // the pivot the gesture used, and the position has to be re-derived+ // from the snapped matrix: reusing the unsnapped one works for a+ // single node (its own matrix pivots about the same anchor, so its+ // position is rotation-invariant) but a group's matrix pivots about+ // its box center, which the mask's center is offset from, and the+ // mask jumps.+ if (keys(world).has('shift')) {+ const snapped = Math.round(decomposed.rotation / 15) * 15;++ if (snapped !== decomposed.rotation) {+ const pivot = transformPoint(oldTr, pivotX, pivotY);+ const correction = rotateAbout(pivot.x, pivot.y, snapped - decomposed.rotation);+ newLocal = multiply2D(inParent(state.parentTransform, correction), newLocal);+ decomposed = decompose2D(newLocal);+ }+ }++ const offset = entityOffset(world, entity);+ editor.editProperty(entity, 'x', Math.round(decomposed.x - anchorX - offset.x));+ editor.editProperty(entity, 'y', Math.round(decomposed.y - anchorY - offset.y));+ editor.editProperty(entity, 'rotation', Math.round(decomposed.rotation * 100) / 100);+ }++ updateRotationCursor(world);+ }++ if (world.get(Pointer)!.phase === 'lifted') {+ updateRotationCursor(world);+ }+}++/** The body of the selection mask: dragging it moves everything selected. */+export function handleMaskInteraction(world: World, event: DispatchedPointerEvent): void {+ const editor = getDocumentEditor(world);++ // Double-clicking a selected container drills into it, same as on the+ // entity itself; the mask covers the node, so this is where it lands.+ if (event.type === 'dblclick') {+ const selection = getSelection(world);+ if (selection.length !== 1) return;+ const child = enterEntity(world, selection[0]!, { x: event.clientX, y: event.clientY });+ if (child !== null) editor.select(child);+ return;+ }++ if (event.type === 'dragstart') {+ snapshotSelectionMask(world);+ snapshotSelectionTransforms(world);+ snapshotSnapCandidates(world);+ world.get(SnapLines)!.list.length = 0;+ reparentCorrections.clear();+ resetDwell(world, { x: event.clientX, y: event.clientY });+ world.set(Hud, { mode: 'moving' });+ }++ const snapshot = getSelectionMaskSnapshot();++ if (event.type === 'drag' && snapshot) {+ const oldTr = snapshot.mat;+ const snapLines = world.get(SnapLines)!.list;+ snapLines.length = 0;++ const current = pointerPoint(world, oldTr);+ const origin = pointerOrigin(world, oldTr);+ let deltaX = current.x - origin.x;+ let deltaY = current.y - origin.y;++ // Mod suspends snapping for the gesture.+ if (!keys(world).has('mod')) {+ const proposed = rectToQuad(multiply2D(oldTr, translate2D(deltaX, deltaY)), snapshot.width, snapshot.height);+ const candidates = getSnapCandidatesSnapshot();+ const moved = buildSnapCandidatesFromQuad(proposed);+ const threshold = SNAP_DISTANCE * resolution(world);+ const xSnap = findSnapTarget(moved.x, candidates.x, threshold, 'x');+ const ySnap = findSnapTarget(moved.y, candidates.y, threshold, 'y');++ if (xSnap) snapLines.push({+ from: { x: xSnap.sourcePoint.x + xSnap.offset, y: xSnap.sourcePoint.y + (ySnap?.offset ?? 0) },+ to: xSnap.targetPoint,+ });++ if (ySnap) snapLines.push({+ from: { x: ySnap.sourcePoint.x + (xSnap?.offset ?? 0), y: ySnap.sourcePoint.y + ySnap.offset },+ to: ySnap.targetPoint,+ });++ if (xSnap || ySnap) {+ const inverse = invert2D(oldTr);+ inverse.e = 0;+ inverse.f = 0;+ const correction = transformPoint(inverse, xSnap?.offset ?? 0, ySnap?.offset ?? 0);+ deltaX += correction.x;+ deltaY += correction.y;+ }+ }++ const localOffset = translate2D(deltaX, deltaY);+ // One drop target for the whole selection, decided once for the frame.+ const drop = settledDropTarget(world, { x: event.clientX, y: event.clientY });++ for (const entity of getSelection(world)) {+ const state = getTransformSnapshot(entity);+ if (!state) continue;++ if (drop !== undefined) reparentTo(world, entity, drop);++ const anchor = entityAnchor(world, entity);+ const anchorX = state.width * anchor.x;+ const anchorY = state.height * anchor.y;+ const oldLocal = multiply2D(state.localTransform, translate2D(anchorX, anchorY));+ // The snapshot is against the parent the drag started under, so a+ // node that changed parents mid-drag carries the correction that+ // undoes the difference between them.+ const correction = reparentCorrections.get(entity) ?? identity2D();+ const moved = multiply2D(correction, inParentSpace(oldTr, localOffset, state.parentTransform, oldLocal));+ const decomposed = decompose2D(moved);+ const offset = entityOffset(world, entity);++ editor.editProperty(entity, 'x', Math.round(decomposed.x - anchorX - offset.x));+ editor.editProperty(entity, 'y', Math.round(decomposed.y - anchorY - offset.y));+ }+ }++ if (event.type === 'dragend') {+ world.get(SnapLines)!.list.length = 0;+ world.set(Hud, { mode: 'idle' });+ }++ if (world.get(Pointer)!.phase === 'lifted') {+ updateCursor(world, 'default');+ }+}++/**+ * Per node, what its parent change during this drag did to its coordinates:+ * new parent⁻¹ · old parent, accumulated over however many times it changed.+ */+const reparentCorrections = new Map<Entity, Mat2D>();++/** How many scenes deep a node sits, the stage being 0. */+function sceneDepth(entity: Entity): number {+ let depth = 0;+ for (let scene = getSceneAncestor(entity); scene !== null; scene = getSceneAncestor(scene)) depth++;+ return depth;+}++/**+ * The scene under a device-pixel point that a dragged node could be dropped+ * into: the innermost one, since scenes nest and the one drawn over the others+ * is the one being pointed at. Nothing being dragged is a candidate, itself or+ * anything under it, so a drag cannot drop a node into its own subtree.+ */+function findSceneAtPointer(world: World, point: Point): Entity | null {+ let target: Entity | null = null;+ let deepest = -1;++ for (const scene of world.query(Scene, Not(Selected), Not(Culled))) {+ if (isDragged(scene) || !isPointerInEntity(world, scene, point)) continue;++ const depth = sceneDepth(scene);+ if (depth > deepest) {+ deepest = depth;+ target = scene;+ }+ }++ return target;+}++/** Whether the node is one of the dragged ones, or inside one. */+function isDragged(entity: Entity): boolean {+ for (let node: Entity | null = entity; node !== null; node = getParentNode(node)) {+ if (node.has(Selected)) return true;+ }++ return false;+}++/** Whether the node's position is animated, in which case a move would fight the keyframes. */+function hasPositionKeyframes(world: World, entity: Entity): boolean {+ return findKeyframeTrackEntity(world, entity, 'position.x') !== null+ || findKeyframeTrackEntity(world, entity, 'position.y') !== null;+}++/**+ * How long the pointer has to stay over the same thing before a dragged node+ * is moved into it. Dragging across a scene on the way somewhere else is not a+ * request to nest anything in it, and without a wait a quick pass would+ * re-home the node twice, once each way, writing both to the file.+ */+const DROP_DWELL_MS = 350;++/** What the pointer is over, and since when. */+const dwell = { target: null as Entity | null, since: 0 };++/**+ * Starts the clock for a new drag, on whatever the pointer is already over:+ * a node picked up inside a scene starts out settled there, so the wait+ * begins when it leaves rather than when it was grabbed. The stage counts as+ * a target like any scene, so a node dragged out of one has to be held+ * outside before it is handed back.+ */+function resetDwell(world: World, point: Point): void {+ dwell.target = findSceneAtPointer(world, point);+ dwell.since = world.get(Time)?.now ?? 0;+}++/**+ * The scene a drop would go into, or the stage as null, once the pointer has+ * stayed over it long enough to mean it. Undefined until then, which is the+ * answer for most of a drag: nothing moves.+ */+function settledDropTarget(world: World, point: Point): Entity | null | undefined {+ const target = findSceneAtPointer(world, point);+ const now = world.get(Time)?.now ?? 0;++ if (target !== dwell.target) {+ dwell.target = target;+ dwell.since = now;+ }++ return now - dwell.since >= DROP_DWELL_MS ? dwell.target : undefined;+}++/**+ * Moves a dragged node into `target` (a scene, or the stage as null) once the+ * pointer has settled on it. Scenes travel like anything else: they nest, so a+ * scene dropped into a scene becomes one of its children.+ *+ * Only top-level nodes are taken in and only direct children handed back, so a+ * drag rearranges the document one level at a time. "Top-level" is+ * `getParentNode`, not a missing parent: under the stage model every node has+ * one, and a root's is the stage.+ */+function reparentTo(world: World, entity: Entity, target: Entity | null): void {+ const editor = getDocumentEditor(world);+ const parent = getParentNode(entity);+ const before = entityWorldMat(world, getParentEntity(entity));+ let moved = false;++ if (target !== null && target !== entity && parent === null) {+ moved = editor.reparent(entity, target);+ // Dropping into a scene points the timeline at it, but only a root can+ // hold the active tag, so a nested one leaves it where it was.+ if (moved && getParentNode(target) === null) editor.activate(target);+ }++ if (target === null && parent !== null && getSceneAncestor(entity) !== null && !hasPositionKeyframes(world, entity)) {+ moved = editor.reparent(entity, world.get(Root)!);+ }++ if (!moved) return;++ const after = entityWorldMat(world, getParentEntity(entity));+ const correction = multiply2D(invert2D(after), before);+ reparentCorrections.set(entity, multiply2D(reparentCorrections.get(entity) ?? identity2D(), correction));+}++export function updateResizeCursor(world: World, handle: Handle): void {+ const mask = getSelectionMask(world);+ if (mask === null) return;++ updateCursor(world, HANDLE_CURSOR[handle], Math.atan2(mask.mat.b, mask.mat.a));+}++export function updateRotationCursor(world: World): void {+ const mask = getSelectionMask(world);+ if (mask === null) return;++ const quad = rectToQuad(mask.mat, mask.width, mask.height);+ const center = quadCenter(quad);+ const pointer = world.get(Pointer)!;+ const angle = Math.atan2(center.y - pointer.clientY, center.x - pointer.clientX);++ updateCursor(world, 'nwse-rotate', angle - Math.PI / 4);+}++/** Scale about a point, in the space the point is given in. */+function scaleAbout(x: number, y: number, scaleX: number, scaleY: number): Mat2D {+ let mat = translate2D(x, y);+ mat = multiply2D(mat, scale2D(scaleX, scaleY));+ return multiply2D(mat, translate2D(-x, -y));+}++/** Rotate about a point, in the space the point is given in. */+function rotateAbout(x: number, y: number, degrees: number): Mat2D {+ let mat = translate2D(x, y);+ mat = multiply2D(mat, rotate2D(degrees));+ return multiply2D(mat, translate2D(-x, -y));+}++/** The pivot part of `computeLocalMatrix`: T(pivot) · linear · T(-pivot). */+function scaleFree(pivotX: number, pivotY: number, linear: Mat2D): Mat2D {+ return multiply2D(multiply2D(translate2D(pivotX, pivotY), linear), translate2D(-pivotX, -pivotY));+}++/** A mask-space delta as the parent sees it: parent⁻¹ · mask · delta · mask⁻¹ · parent. */+function inParent(parentTransform: Mat2D, deltaWorld: Mat2D): Mat2D {+ return multiply2D(multiply2D(invert2D(parentTransform), deltaWorld), parentTransform);+}++/** The node's new local transform after `localDelta` is applied through the mask. */+function inParentSpace(maskTr: Mat2D, localDelta: Mat2D, parentTransform: Mat2D, oldLocal: Mat2D): Mat2D {+ const deltaWorld = multiply2D(multiply2D(maskTr, localDelta), invert2D(maskTr));+ return multiply2D(inParent(parentTransform, deltaWorld), oldLocal);+}++function handleVertices(handle: Handle, quad: Quad): Point[] {+ switch (handle) {+ case 'tl': return [quad[0]];+ case 'tr': return [quad[1]];+ case 'br': return [quad[2]];+ case 'bl': return [quad[3]];+ case 't': return [quad[0], quad[1]];+ case 'r': return [quad[1], quad[2]];+ case 'b': return [quad[2], quad[3]];+ case 'l': return [quad[3], quad[0]];+ }+}diff --git a/apps/web/src/engine/input/snapping.ts b/apps/web/src/engine/input/snapping.tsnew file mode 100644index 00000000..d473bf78--- /dev/null+++ b/apps/web/src/engine/input/snapping.ts@@ -0,0 +1,213 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++/**+ * What a transform gesture needs to remember. A drag is measured against the+ * world as it stood when the pointer went down, not against the frame before+ * it: the nodes move while it runs, so reading them again would compound. All+ * of it is snapshotted once at dragstart and read back per frame.+ *+ * There is one gesture at a time, so this state is module-level, as the+ * pointer's own is.+ */++import { Not, Or } from 'koota';+import {+ ChildOf, Computed, Culled, Geometry, Group, Hidden, Root, Scale,+ entityLocalMat, entityQuad, entityWorldMat, getParentEntity, getSelection,+ getSelectionMask, isStage, quadCenter, store,+} from '@diffusionstudio/runtime';++import { Hud, Pointer } from '../traits';++import type { Entity, World } from 'koota';+import type { Mat2D, Point, Quad, SelectionMask } from '@diffusionstudio/runtime';++export type NodeSnapshot = {+ localTransform: Mat2D;+ parentTransform: Mat2D;+ width: number;+ height: number;+ scaleX: number;+ scaleY: number;+};++const transforms = new Map<Entity, NodeSnapshot>();++/**+ * Records the local and parent transforms of everything the gesture will+ * move. Groups have no Size of their own, so their direct children come along:+ * those are the entities a group resize actually transforms.+ */+export function snapshotSelectionTransforms(world: World): void {+ transforms.clear();+ const computed = store(world, Computed);+ const scale = store(world, Scale);++ const snapshot = (entity: Entity): void => {+ if (transforms.has(entity)) return;+ const eid = entity.id();++ transforms.set(entity, {+ localTransform: entityLocalMat(world, entity),+ parentTransform: entityWorldMat(world, getParentEntity(entity)),+ width: computed.width[eid] ?? 0,+ height: computed.height[eid] ?? 0,+ scaleX: scale.x[eid] ?? 1,+ scaleY: scale.y[eid] ?? 1,+ });++ if (entity.has(Group)) {+ for (const child of world.query(Or(Geometry, Group), ChildOf(entity))) {+ snapshot(child);+ }+ }+ };++ for (const entity of getSelection(world)) {+ snapshot(entity);+ }+}++export function getTransformSnapshot(entity: Entity): NodeSnapshot | undefined {+ return transforms.get(entity);+}++let mask: SelectionMask | null = null;++export function snapshotSelectionMask(world: World): void {+ mask = getSelectionMask(world);+}++export function getSelectionMaskSnapshot(): SelectionMask | null {+ return mask;+}++export type SnapAxisCandidate = { value: number; point: Point };+export type SnapCandidates = { x: SnapAxisCandidate[]; y: SnapAxisCandidate[] };++const candidates: SnapCandidates = { x: [], y: [] };++/**+ * The edges and centers a gesture can snap to: the selection's siblings, plus+ * its parent. Taken once at dragstart, so a node cannot snap to where it has+ * just been dragged.+ */+export function snapshotSnapCandidates(world: World): void {+ candidates.x.length = 0;+ candidates.y.length = 0;++ const seen = new Set<string>();+ const selection = new Set(getSelection(world));+ const computed = store(world, Computed);++ const addNode = (entity: Entity): void => {+ if (computed.visibility[entity.id()] === 0) return;++ const quad = entityQuad(world, entity);+ const node = buildSnapCandidatesFromQuad(quad);+ const axes = [+ ...node.x.map((candidate) => ({ axis: 'x' as const, candidate })),+ ...node.y.map((candidate) => ({ axis: 'y' as const, candidate })),+ ];++ for (const { axis, candidate } of axes) {+ const round = (value: number): number => Math.round(value * 100) / 100;+ const key = axis === 'x'+ ? `x:${round(candidate.value)}:${round(candidate.point.y)}`+ : `y:${round(candidate.value)}:${round(candidate.point.x)}`;+ if (seen.has(key)) continue;+ seen.add(key);++ candidates[axis].push(candidate);+ }+ };++ // A single node snaps within its own frame; a multi-selection spans+ // frames, so the stage is the only frame they share.+ const only = selection.size === 1 ? [...selection][0]! : null;+ const parent = (only === null ? null : getParentEntity(only)) ?? world.get(Root)!;++ for (const sibling of world.query(Or(Geometry, Group), ChildOf(parent), Not(Culled), Not(Hidden))) {+ if (selection.has(sibling)) continue;+ addNode(sibling);+ }++ if (!isStage(parent) && !selection.has(parent)) {+ addNode(parent);+ }+}++export function getSnapCandidatesSnapshot(): SnapCandidates {+ return candidates;+}++export function buildSnapCandidatesFromQuad(quad: Quad): SnapCandidates {+ return buildSnapCandidatesFromCorners([...quad, quadCenter(quad)]);+}++export function buildSnapCandidatesFromCorners(points: Point[]): SnapCandidates {+ return {+ x: points.map((point) => ({ value: point.x, point })),+ y: points.map((point) => ({ value: point.y, point })),+ };+}++export type SnapTarget = {+ offset: number;+ distance: number;+ sourcePoint: Point;+ targetPoint: Point;+};++/**+ * The nearest candidate within `threshold` on one axis, ties broken by the+ * shorter guide: of two equally close snaps, the one whose line is shorter is+ * the one the user meant.+ */+export function findSnapTarget(+ source: SnapAxisCandidate[],+ targets: SnapAxisCandidate[],+ threshold: number,+ axis: 'x' | 'y',+): SnapTarget | null {+ const cross = (a: Point, b: Point): number => (axis === 'x' ? Math.abs(b.y - a.y) : Math.abs(b.x - a.x));+ let best: SnapTarget | null = null;++ for (const candidate of source) {+ for (const target of targets) {+ const offset = target.value - candidate.value;+ const distance = Math.abs(offset);+ if (distance > threshold) continue;++ if (+ !best+ || distance < best.distance+ || (distance === best.distance && cross(candidate.point, target.point) < cross(best.sourcePoint, best.targetPoint))+ ) {+ best = { offset, distance, sourcePoint: candidate.point, targetPoint: target.point };+ }+ }+ }++ return best;+}++/** The marquee rectangle in device pixels, or null when no marquee is running. */+export function getMarqueeQuad(world: World): Quad | null {+ if (world.get(Hud)?.mode !== 'marquee') return null;++ const pointer = world.get(Pointer)!;+ const minX = Math.min(pointer.dragStartX, pointer.clientX);+ const minY = Math.min(pointer.dragStartY, pointer.clientY);+ const maxX = Math.max(pointer.dragStartX, pointer.clientX);+ const maxY = Math.max(pointer.dragStartY, pointer.clientY);++ return [+ { x: minX, y: minY },+ { x: maxX, y: minY },+ { x: maxX, y: maxY },+ { x: minX, y: maxY },+ ];+}diff --git a/apps/web/src/engine/traits.ts b/apps/web/src/engine/traits.tsnew file mode 100644index 00000000..f28dfdfa--- /dev/null+++ b/apps/web/src/engine/traits.ts@@ -0,0 +1,56 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++/**+ * Editor state on the world, next to the runtime's own singletons: what the+ * pointer and keyboard are doing, and what the HUD is drawing because of it.+ * None of it belongs in `@diffusionstudio/runtime` (a headless world has no+ * pointer), and none of it is authored, so it never reaches the source.+ */++import { trait } from 'koota';++import type { CanvasPointerEvent, Point } from '@diffusionstudio/runtime';++export type PointerPhase = 'pressed' | 'lifted';++/**+ * The pointer in canvas device pixels, as of the last event the input system+ * drained. `dragStart*` is where the current press began, which is what a+ * gesture measures its delta from.+ */+export const Pointer = trait({+ phase: 'lifted' as PointerPhase,+ button: 0,+ clientX: 0,+ clientY: 0,+ dragStartX: 0,+ dragStartY: 0,+});++/**+ * Keys currently held, lowercased, with 'mod' standing in for meta/control so+ * a shortcut does not have to know which platform it is on. Mutated in place:+ * an AoS trait hands back the set itself.+ */+export const Keys = trait(() => new Set<string>());++export type SnapLine = { from: Point; to: Point };++/** Snap guides for the gesture in flight; the HUD draws and empties them. */+export const SnapLines = trait({ list: () => [] as SnapLine[] });++export type HudMode = 'idle' | 'moving' | 'marquee';++/**+ * What the HUD is in the middle of. 'moving' hides the selection mask (the+ * nodes are under the pointer, the box would only be in the way) and+ * 'marquee' turns the drag rectangle into a selection.+ */+export const Hud = trait({ mode: 'idle' as HudMode });++/**+ * Queue of pointer events to be processed by the input system.+ */+export const PointerEvents = trait({ queue: () => [] as CanvasPointerEvent[] });diff --git a/apps/web/src/projects/edits.ts b/apps/web/src/projects/edits.tsindex e23ca5ad..6663fb21 100644--- a/apps/web/src/projects/edits.ts+++ b/apps/web/src/projects/edits.ts@@ -8,7 +8,7 @@ import { toast } from 'somoto';import { writeProject } from './host';-import type { EntityEdit, InsertEdit } from '@/engine/editor';+import type { EntityEdit, InsertEdit, MoveEdit } from '@/engine/editor';import type { SourceEdit, WriteResult } from './host';import type { World } from 'koota';@@ -24,9 +24,11 @@ class EditWriter {private readonly world: World;// Inserts first, in the order they were made (a child's parent may be one- // of them), then per element, per prop: the last value for a prop is the- // only one worth writing, and an element written twice is written once.+ // of them), then the moves, then per element, per prop: the last value for+ // a prop is the only one worth writing, an element written twice is+ // written once, and only where an element ended up is worth moving it to.private inserts = new Map<string, InsertEdit>();+ private moves = new Map<string, MoveEdit>();private pending = new Map<string, InsertEdit['props']>();// Pending sources a write is out for: edits to them wait for the answer.private inflight = new Set<string>();@@ -44,6 +46,19 @@ class EditWriter {if (edit.kind === 'insert') {this.inserts.set(edit.source, edit);+ } else if (edit.kind === 'move') {+ // Where an element still waiting to be inserted goes is part of how+ // it is inserted, not a move of it.+ const insert = this.inserts.get(edit.source);++ if (insert) {+ const moved: InsertEdit = { ...insert, parent: edit.parent };+ if (edit.before === undefined) delete moved.before;+ else moved.before = edit.before;+ this.inserts.set(edit.source, moved);+ } else {+ this.moves.set(edit.source, edit);+ }} else {// A prop of an element still waiting to be inserted is part of how// it is inserted.@@ -71,12 +86,14 @@ class EditWriter {private flush(): void {this.timer = undefined;- if (!this.inserts.size && !this.pending.size) return;+ if (!this.inserts.size && !this.moves.size && !this.pending.size) return;// Anything addressed through an element whose insert is still out- // waits for its name: edits to it, and inserts under or beside it.+ // waits for its name: edits to it, and inserts or moves under or+ // beside it.const waits = (source: string | undefined): boolean => source !== undefined && this.inflight.has(source);const heldInserts = new Map([...this.inserts].filter(([, insert]) => waits(insert.parent) || waits(insert.before)));+ const heldMoves = new Map([...this.moves].filter(([source, move]) => waits(source) || waits(move.parent) || waits(move.before)));const held = new Map([...this.pending].filter(([source]) => waits(source)));const edits: SourceEdit[] = [...[...this.inserts.values()]@@ -90,6 +107,16 @@ class EditWriter {...(before === undefined ? {} : { before }),...(text === undefined ? {} : { text }),})),+ // After the inserts: a move may be into an element this same write+ // is adding. Before the props, which then land on it where it is.+ ...[...this.moves.values()]+ .filter((move) => !heldMoves.has(move.source))+ .map(({ kind, source, parent, before }): SourceEdit => ({+ kind,+ source,+ parent,+ ...(before === undefined ? {} : { before }),+ })),...[...this.pending].filter(([source]) => !held.has(source)).map(([source, props]): SourceEdit => ({ kind: 'set', source, props })),@@ -98,6 +125,7 @@ class EditWriter {this.inflight = new Set([...this.inflight, ...this.inserts.keys()].filter((source) => !heldInserts.has(source)));this.inserts = heldInserts;+ this.moves = heldMoves;this.pending = held;writeProject(this.dir, edits)@@ -147,13 +175,26 @@ class EditWriter {const { before: _, ...rest } = insert;this.inserts.set(source, { ...rest, parent, ...(before === undefined ? {} : { before }) });}+ for (const [source, move] of [...this.moves]) {+ const next = rename(source);+ const parent = rename(move.parent);+ // Neither the element nor the place it was going made it into the+ // file; the insert's own discard takes the entity with it.+ if (next === undefined || parent === undefined) {+ this.moves.delete(source);+ continue;+ }+ const before = move.before === undefined ? undefined : rename(move.before);+ this.moves.delete(source);+ this.moves.set(next, { ...move, source: next, parent, ...(before === undefined ? {} : { before }) });+ }for (const source of this.inflight) {if (!ids[source]) editor.discardPending(source);}this.inflight = new Set();// What was held back has its names now.- if (this.inserts.size || this.pending.size) this.schedule();+ if (this.inserts.size || this.moves.size || this.pending.size) this.schedule();}}diff --git a/packages/reconciler/src/document.ts b/packages/reconciler/src/document.tsindex 9ee16901..fc3a970a 100644--- a/packages/reconciler/src/document.ts+++ b/packages/reconciler/src/document.ts@@ -364,11 +364,6 @@ export class RuntimeDocument implements ProjectDocument<HostNode> {throw new Error('<text> only takes text children.');}- // Scenes own a timeline, so one inside another has no coherent reading.- if (node.entity.has(Scene) && !parent.entity.has(Stage)) {- throw new Error('<scene> is only allowed as a direct child of <stage>.');- }-if (getParentEntity(node.entity) !== parent.entity) {// appendChild only takes top-level entities, so a move between two// parents goes back through the stage on the way.diff --git a/packages/runtime/src/actions/index.ts b/packages/runtime/src/actions/index.tsindex e89072c4..1ae92300 100644--- a/packages/runtime/src/actions/index.ts+++ b/packages/runtime/src/actions/index.ts@@ -22,3 +22,4 @@ export * from './frame';export * from './clipboard';export * from './assets';export * from './folders';+export * from './interactive';diff --git a/packages/runtime/src/actions/interactive.ts b/packages/runtime/src/actions/interactive.tsnew file mode 100644index 00000000..d867f995--- /dev/null+++ b/packages/runtime/src/actions/interactive.ts@@ -0,0 +1,86 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// Upkeep of the Interactive tag: which entities a pointer can hit. The render+// system pushes a hit region for every Interactive entity it paints, so this+// decides what clicking the canvas can reach, and drilling into a container+// moves the tag down a level.++import { Not, Or } from 'koota';++import {+ AdjustmentLayer, ChildOf, Culled, Geometry, Group, Hovering, Interactive,+ IsMask, Root, Sequential,+} from '../traits';+import { isScene } from '../queries/predicates';+import { isPointerInEntity } from '../queries/interaction';++import type { Entity, World } from 'koota';+import type { Point } from '../math';++/**+ * Re-derives the Interactive set from the document. A top-level scene passes+ * through to its children (its contents are what an editor works on), and so+ * does a sequence, which is a timing construct rather than a thing on the+ * canvas. Everything else is a clickable unit and exposes its children only+ * once entered (see `enterEntity`).+ */+export function syncInteractiveState(world: World): void {+ for (const entity of world.query(Interactive)) {+ entity.remove(Interactive);+ }++ const walk = (entity: Entity, isRoot: boolean): void => {+ const children = world.query(Or(Geometry, Group, AdjustmentLayer), ChildOf(entity));+ const passThrough = entity.has(Sequential) || (isRoot && isScene(entity) && children.length > 0);++ if (passThrough) {+ for (const child of children) {+ walk(child, false);+ }+ return;+ }++ entity.add(Interactive);+ };++ for (const entity of world.query(Or(Geometry, Group, AdjustmentLayer), ChildOf(world.get(Root)!))) {+ walk(entity, true);+ }+}++/** The topmost child of `parent` under a device-pixel point, or null. */+export function findChildAt(world: World, parent: Entity, point: Point): Entity | null {+ const children = world.query(Or(Geometry, Group), ChildOf(parent), Not(IsMask), Not(Culled));++ for (let i = children.length - 1; i >= 0; i--) {+ const child = children[i]!;+ if (isPointerInEntity(world, child, point)) return child;+ }++ return null;+}++/**+ * Drills into `parent` at a device-pixel point: hands its children the+ * Interactive tag and returns the one under the pointer, or null when the+ * point hits none of them (in which case nothing changes). Selection is the+ * caller's to make, since only it knows how a selection is reported.+ */+export function enterEntity(world: World, parent: Entity, point: Point): Entity | null {+ const child = findChildAt(world, parent, point);+ if (child === null) return null;++ parent.remove(Interactive);+ for (const sibling of world.query(Or(Geometry, Group), ChildOf(parent))) {+ sibling.add(Interactive);+ }++ for (const hovering of world.query(Hovering)) {+ hovering.remove(Hovering);+ }+ child.add(Hovering);++ return child;+}diff --git a/packages/runtime/src/queries/hit-test.ts b/packages/runtime/src/queries/hit-test.tsindex d53cb73b..e7bd227c 100644--- a/packages/runtime/src/queries/hit-test.ts+++ b/packages/runtime/src/queries/hit-test.ts@@ -2,16 +2,17 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-// Document-space hit testing and coordinate mapping for top-level entities.-// LocalTransform is written straight into the SoA store by the transform-// system (never added as a trait), so it is read by entity id here, like-// WorldBounds in ./camera.+// Document-space hit testing and coordinate mapping, for the tools that work+// in the camera's space rather than the canvas's. LocalTransform is written+// straight into the SoA store by the transform system (never added as a+// trait), so it is read by entity id here, like WorldBounds in ./camera.import { Not } from 'koota';import { Computed, Culled, Geometry, Hidden, LocalTransform, Scene } from '../traits';import { store } from '../world/store';-import { aabbFromTransformedRect, invert2D, transformPoint } from '../math';+import { aabbFromTransformedRect, invert2D, multiply2D, transformPoint } from '../math';+import { getParentNode } from './hierarchy';import type { Entity, World } from 'koota';import type { Mat2D, Point } from '../math';@@ -33,34 +34,55 @@ function localMatrix(world: World, entity: Entity): Mat2D {};}+/**+ * An entity's transform in document space: its own, composed with every+ * ancestor's up to the stage. A top-level node's LocalTransform is already in+ * document space, and this is what makes the same true of a nested one.+ */+function documentMatrix(world: World, entity: Entity): Mat2D {+ let mat = localMatrix(world, entity);++ for (let parent = getParentNode(entity); parent !== null; parent = getParentNode(parent)) {+ mat = multiply2D(localMatrix(world, parent), mat);+ }++ return mat;+}+/*** Convert a document-space point (as produced by `screenToWorld`) to an- * entity's local coordinates via its LocalTransform. Meant for top-level- * entities (scenes), whose LocalTransform is in document space.+ * entity's local coordinates, through its own transform and its ancestors'.*/export function worldToLocal(world: World, entity: Entity, worldX: number, worldY: number): Point {- const mat = localMatrix(world, entity);+ const mat = documentMatrix(world, entity);if (Math.abs(mat.a * mat.d - mat.b * mat.c) < MIN_DETERMINANT) return { x: worldX, y: worldY };return transformPoint(invert2D(mat), worldX, worldY);}/**- * The first visible top-level scene whose document-space bounds contain the- * point (as produced by `screenToWorld`), or null.+ * The visible scene whose document-space bounds contain the point (as produced+ * by `screenToWorld`), or null. Scenes nest, so the innermost one wins: it is+ * the one drawn over the others, and the one a click is aimed at.*/export function findSceneAt(world: World, worldX: number, worldY: number): Entity | null {const computed = store(world, Computed);+ let found: Entity | null = null;+ let deepest = -1;- // Scenes are direct children of the stage, so their LocalTransform is in- // document space already.for (const entity of world.query(Scene, Geometry, Not(Culled), Not(Hidden))) {const eid = entity.id();- const bounds = aabbFromTransformedRect(localMatrix(world, entity), computed.width[eid] ?? 0, computed.height[eid] ?? 0);+ const bounds = aabbFromTransformedRect(documentMatrix(world, entity), computed.width[eid] ?? 0, computed.height[eid] ?? 0);++ if (worldX < bounds.minX || worldX > bounds.maxX || worldY < bounds.minY || worldY > bounds.maxY) continue;++ let depth = 0;+ for (let parent = getParentNode(entity); parent !== null; parent = getParentNode(parent)) depth++;- if (worldX >= bounds.minX && worldX <= bounds.maxX && worldY >= bounds.minY && worldY <= bounds.maxY) {- return entity;+ if (depth > deepest) {+ deepest = depth;+ found = entity;}}- return null;+ return found;}diff --git a/packages/runtime/src/queries/index.ts b/packages/runtime/src/queries/index.tsindex f6aca160..1891f407 100644--- a/packages/runtime/src/queries/index.ts+++ b/packages/runtime/src/queries/index.ts@@ -3,3 +3,4 @@ export * from './camera';export * from './hierarchy';export * from './timeline-index';export * from './hit-test';+export * from './interaction';diff --git a/packages/runtime/src/queries/interaction.ts b/packages/runtime/src/queries/interaction.tsnew file mode 100644index 00000000..4f3fd63c--- /dev/null+++ b/packages/runtime/src/queries/interaction.ts@@ -0,0 +1,170 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// Interaction reads: the device-pixel geometry an editor points at (was+// utils/interaction.ts + parts of utils/coordinates.ts). Everything here is in+// canvas device pixels, the space the transform system leaves WorldTransform+// and WorldBounds in, so a pointer position can be compared against it without+// converting anything. Derived transforms are read from the SoA stores by+// entity id: the transform system writes them there without ever adding the+// traits.++import { Not, Or } from 'koota';++import {+ Anchor, Computed, Geometry, Group, LocalTransform, Offset, Selected,+ Sequential, WorldBounds, WorldTransform,+} from '../traits';+import { store } from '../world/store';+import { isStage } from './predicates';+import { getViewMatrix } from './camera';+import {+ decompose2D, identity2D, invert2D, multiply2D, rectToQuad, rotate2D,+ scale2D, skew2D, transformPoint, translate2D,+} from '../math';++import type { Entity, World } from 'koota';+import type { Mat2D, Point, Quad } from '../math';++/**+ * World matrix of `entity`, or the view matrix for the stage (and for null,+ * which is what `getParentNode` answers for a top-level node). Parent-space+ * math over a root therefore works without a special case at the call site.+ */+export function entityWorldMat(world: World, entity: Entity | null): Mat2D {+ if (entity === null || isStage(entity)) return getViewMatrix(world);++ const transform = store(world, WorldTransform);+ const eid = entity.id();++ return {+ a: transform.a[eid] ?? 1, b: transform.b[eid] ?? 0,+ c: transform.c[eid] ?? 0, d: transform.d[eid] ?? 1,+ e: transform.e[eid] ?? 0, f: transform.f[eid] ?? 0,+ };+}++export function entityLocalMat(world: World, entity: Entity): Mat2D {+ const local = store(world, LocalTransform);+ const eid = entity.id();++ return {+ a: local.a[eid] ?? 1, b: local.b[eid] ?? 0,+ c: local.c[eid] ?? 0, d: local.d[eid] ?? 1,+ e: local.e[eid] ?? 0, f: local.f[eid] ?? 0,+ };+}++export function entityOffset(world: World, entity: Entity): Point {+ const offset = store(world, Offset);+ const eid = entity.id();++ return { x: offset.x[eid] ?? 0, y: offset.y[eid] ?? 0 };+}++export function entityAnchor(world: World, entity: Entity): Point {+ const anchor = store(world, Anchor);+ const eid = entity.id();++ return { x: anchor.x[eid] ?? 0.5, y: anchor.y[eid] ?? 0.5 };+}++/** The entity's box in device pixels, as [TL, TR, BR, BL]. */+export function entityQuad(world: World, entity: Entity): Quad {+ const computed = store(world, Computed);+ const eid = entity.id();+ const mat = multiply2D(+ entityWorldMat(world, entity),+ translate2D(computed.originX[eid] ?? 0, computed.originY[eid] ?? 0),+ );++ return rectToQuad(mat, computed.width[eid] ?? 0, computed.height[eid] ?? 0);+}++/** Whether a device-pixel point is inside the entity's box. */+export function isPointerInEntity(world: World, entity: Entity, point: Point): boolean {+ const bounds = store(world, WorldBounds);+ const eid = entity.id();++ if (+ point.x < bounds.minX[eid] || point.x > bounds.maxX[eid] ||+ point.y < bounds.minY[eid] || point.y > bounds.maxY[eid]+ ) {+ return false;+ }++ // Precise test: map the pointer into entity-local space so rotation/skew+ // don't produce false positives along the AABB's outer slack.+ const local = transformPoint(invert2D(entityWorldMat(world, entity)), point.x, point.y);+ const computed = store(world, Computed);+ const originX = computed.originX[eid] ?? 0;+ const originY = computed.originY[eid] ?? 0;++ return local.x >= originX && local.x <= originX + (computed.width[eid] ?? 0)+ && local.y >= originY && local.y <= originY + (computed.height[eid] ?? 0);+}++/** The entities a selection mask spans: sequences are not spatial, so they never do. */+export function getMaskSelection(world: World): Entity[] {+ return [...world.query(Selected, Or(Geometry, Group), Not(Sequential))];+}++/** Every selected node, sequences included (what a transform gesture moves). */+export function getSelection(world: World): Entity[] {+ return [...world.query(Selected, Or(Geometry, Group))];+}++/**+ * The box the selection is manipulated through, in device pixels: for one+ * node its own rotated/skewed frame, for several the upright AABB of them+ * all. Null when nothing selectable is selected.+ */+export type SelectionMask = {+ width: number;+ height: number;+ mat: Mat2D;+};++export function getSelectionMask(world: World): SelectionMask | null {+ const selection = getMaskSelection(world);+ if (selection.length === 0) return null;++ const computed = store(world, Computed);++ if (selection.length === 1) {+ const entity = selection[0]!;+ const eid = entity.id();+ const worldMat = multiply2D(+ entityWorldMat(world, entity),+ translate2D(computed.originX[eid] ?? 0, computed.originY[eid] ?? 0),+ );+ const decomposed = decompose2D(worldMat);++ let mat = identity2D();+ mat = multiply2D(mat, translate2D(decomposed.x, decomposed.y));+ mat = multiply2D(mat, rotate2D(decomposed.rotation));+ mat = multiply2D(mat, scale2D(Math.sign(decomposed.scaleX) || 1, Math.sign(decomposed.scaleY) || 1));+ mat = multiply2D(mat, skew2D(decomposed.skewX, decomposed.skewY));++ return {+ width: (computed.width[eid] ?? 0) * Math.abs(decomposed.scaleX),+ height: (computed.height[eid] ?? 0) * Math.abs(decomposed.scaleY),+ mat,+ };+ }++ let minX = Infinity, minY = Infinity;+ let maxX = -Infinity, maxY = -Infinity;++ for (const entity of selection) {+ for (const point of entityQuad(world, entity)) {+ if (point.x < minX) minX = point.x;+ if (point.y < minY) minY = point.y;+ if (point.x > maxX) maxX = point.x;+ if (point.y > maxY) maxY = point.y;+ }+ }++ return { width: maxX - minX, height: maxY - minY, mat: translate2D(minX, minY) };+}diff --git a/packages/runtime/src/traits/world.ts b/packages/runtime/src/traits/world.tsindex 1bfedfd5..1d8aaadc 100644--- a/packages/runtime/src/traits/world.ts+++ b/packages/runtime/src/traits/world.ts@@ -2,7 +2,7 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-import { trait, type Entity } from 'koota';+import { trait, type Entity, type World } from 'koota';import { createLiveMounts } from '../utils/live-mounts';@@ -93,6 +93,36 @@ export type HudTarget = {kind: 'hud';id: string;quad: Quad;+ entity?: Entity;+};++export type PointerEventType =+ | 'pointermove'+ | 'pointerdown'+ | 'pointerup'+ | 'pointerenter'+ | 'pointerleave'+ | 'dragstart'+ | 'drag'+ | 'dragend'+ | 'click'+ | 'dblclick';++/**+ * A pointer event in canvas device pixels (CSS pixels x resolution), which is+ * the space WorldTransform and the hit region quads are in. Not a DOM event:+ * the app's input layer distills one of these per DOM event, and adds the+ * gesture types (drag*, pointerenter/leave) the DOM has no equivalent for.+ */+export type CanvasPointerEvent = {+ type: PointerEventType;+ clientX: number;+ clientY: number;+ button: number; // 0: left, 1: middle, 2: right+};++export type DispatchedPointerEvent = CanvasPointerEvent & {+ target: EntityTarget | HudTarget;};// Paint-order hit regions collected during a render pass (topmost last). The@@ -102,7 +132,7 @@ export type HudTarget = {// default interaction handlers.export type HitRegion = {target: EntityTarget | HudTarget;- callback?: (world: unknown, event: unknown) => void;+ callback?: (world: World, event: DispatchedPointerEvent) => void;};export const HitRegions = trait({ list: () => [] as HitRegion[] });