Skip to content

The VS Code of video editing, built for agents.

TypeScript

Implement camera controls and refactor related components

konstantin-paulusd08c07f2a168
diff --git a/apps/web/src/components/canvas/canvas.tsx b/apps/web/src/components/canvas/canvas.tsx
index 9caa448d..6bd783df 100644
--- a/apps/web/src/components/canvas/canvas.tsx
+++ b/apps/web/src/components/canvas/canvas.tsx
@@ -4,13 +4,13 @@
import { useEngine } from "@/context/engine";
import { loadAsset, getAssetFile } from "@/components/engine";
-import { EngineCanvas } from "@/engine";
+import { CameraController, EngineCanvas } from "@/engine";
import { Toolbar } from "./toolbar";
import { DrawOverlay } from "./draw-overlay";
import { DesktopAppBanner } from "./desktop-app-banner";
import { toast } from "somoto"
import { findSceneAt, screenToWorld, worldToLocal, secondsToFrames, GeometryType, PaintType, createEntity, addComponent, appendChild, setComponent, resizeEntity } from "../engine";
-import { SceneInitOverlay } from "./scene-init-overlay";
+// import { SceneInitOverlay } from "./scene-init-overlay";
import { CLASSIC_PRESET_HEIGHT, CLASSIC_PRESET_WIDTH } from "../engine/decoders/caption/classic";
@@ -161,6 +161,7 @@ export function Canvas() {
onDragOver={handleDragOver}
/> */}
<EngineCanvas />
+ <CameraController />
{/** Deprecated bitecs canvas */}
<canvas
diff --git a/apps/web/src/components/sidebar-right/inspector/inspector-header.tsx b/apps/web/src/components/sidebar-right/inspector/inspector-header.tsx
index ef00663e..9ab2e900 100644
--- a/apps/web/src/components/sidebar-right/inspector/inspector-header.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/inspector-header.tsx
@@ -2,8 +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/. */
-import { createMemo } from "solid-js";
-
import { Icon } from "@/components/ui/icon";
import {
DropdownMenu,
@@ -13,48 +11,20 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
-import { useWorldState } from "@/components/engine/hooks/use-ecs";
-import { useEngine } from "@/context/engine";
+import { useWorld } from "@diffusionstudio/koota-solid";
+import { focusContent, setCameraZoom, zoomCameraBy } from "@diffusionstudio/runtime";
+import { useCameraScale } from "@/engine";
export function InspectorHeader() {
- const { world, camera } = useEngine();
-
- const cameraA = useWorldState(w => w.camera.a, 1);
- const cameraB = useWorldState(w => w.camera.b, 0);
-
- const zoom = createMemo(() => {
- const scale = Math.hypot(cameraA(), cameraB());
- if (!Number.isFinite(scale)) return null;
- return scale * 100;
- });
-
- const zoomLabel = () => {
- const value = zoom();
- if (typeof value === "number" && Number.isFinite(value)) {
- return `${Math.round(value)}%`;
- }
- return "72%";
- };
+ const world = useWorld();
- const getCanvasCenter = () => {
- const canvas = world.canvas;
- if (!(canvas instanceof HTMLCanvasElement)) return { x: 0, y: 0 };
- const rect = canvas.getBoundingClientRect();
- return { x: rect.width / 2, y: rect.height / 2 };
- };
-
- const zoomBy = (factor: number) => {
- const { x, y } = getCanvasCenter();
- camera.zoom(x, y, factor);
- };
-
- const zoomTo = (targetPercent: number) => {
- const currentScale = Math.hypot(world.camera.a, world.camera.b);
- if (!currentScale || !Number.isFinite(currentScale)) return;
- const factor = (targetPercent / 100) / currentScale;
- const { x, y } = getCanvasCenter();
- camera.zoom(x, y, factor);
- };
+ // Every operation here is anchored on the stage itself — its center, or its
+ // content — so the menu needs no canvas geometry of its own.
+ const scale = useCameraScale();
+ const zoomLabel = () => `${Math.round(scale() * 100)}%`;
+ const zoomBy = (factor: number) => zoomCameraBy(world, factor);
+ const zoomTo = (percent: number) => setCameraZoom(world, percent / 100);
+ const zoomToFit = () => focusContent(world);
return (
<div class="h-12 shrink-0 flex items-center px-4">
@@ -83,6 +53,9 @@ export function InspectorHeader() {
<DropdownMenuItem onSelect={() => zoomBy(0.8)}>
Zoom out
</DropdownMenuItem>
+ <DropdownMenuItem onSelect={zoomToFit}>
+ Zoom to fit
+ </DropdownMenuItem>
<DropdownMenuItem onSelect={() => zoomTo(50)}>
Zoom to 50%
</DropdownMenuItem>
diff --git a/apps/web/src/engine/camera-controller.tsx b/apps/web/src/engine/camera-controller.tsx
new file mode 100644
index 00000000..7c923f22
--- /dev/null
+++ b/apps/web/src/engine/camera-controller.tsx
@@ -0,0 +1,184 @@
+/* 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/. */
+
+// Input bindings for the stage camera. The camera's semantics live in the
+// runtime (pan/zoom/focus actions); this file only translates DOM events into
+// calls on them, which is why it stays app-side.
+
+import { createEffect, createMemo, onCleanup } from 'solid-js';
+import { useTrait, useWorld } from '@diffusionstudio/koota-solid';
+import { panCamera, setCamera, zoomCameraAt, getCamera, RenderSurface } from '@diffusionstudio/runtime';
+
+import type { JSX } from 'solid-js';
+import type { World } from 'koota';
+
+/** deltaY is in lines (deltaMode 1) or pages (deltaMode 2) on some devices. */
+const DELTA_MODE_SCALE = [1, 16, 600];
+
+/** Cap a single wheel notch so a coarse mouse wheel doesn't jump zoom levels. */
+const MAX_ZOOM_DELTA = 50;
+
+/** Wheel pixels → zoom exponent. Higher = faster ctrl/pinch zoom. */
+const ZOOM_SENSITIVITY = 0.01;
+
+const MIDDLE_BUTTON = 1;
+
+function isEditable(target: EventTarget | null): boolean {
+ if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) return true;
+ return target instanceof HTMLElement && target.isContentEditable;
+}
+
+/**
+ * Bind camera gestures to `canvas` and return a disposer. Pointer and wheel
+ * events are canvas-scoped so the rest of the editor keeps its own scrolling;
+ * the space-key modifier is tracked on the document (and window blur) because
+ * a held key is global state the canvas never sees.
+ */
+function bindCameraInput(world: World, canvas: HTMLCanvasElement): () => void {
+ let spaceHeld = false;
+ let panning = false;
+ let panPointerId: number | null = null;
+ let startX = 0;
+ let startY = 0;
+ let startE = 0;
+ let startF = 0;
+
+ const updateCursor = (): void => {
+ canvas.style.cursor = panning ? 'grabbing' : (spaceHeld ? 'grab' : '');
+ };
+
+ /** Pointer position in canvas CSS pixels. */
+ const localPoint = (event: { clientX: number; clientY: number }): [x: number, y: number] => {
+ const rect = canvas.getBoundingClientRect();
+ return [event.clientX - rect.left, event.clientY - rect.top];
+ };
+
+ const endPan = (): void => {
+ if (!panning) return;
+ panning = false;
+ if (panPointerId !== null && canvas.hasPointerCapture(panPointerId)) {
+ canvas.releasePointerCapture(panPointerId);
+ }
+ panPointerId = null;
+ updateCursor();
+ };
+
+ const handleWheel = (event: WheelEvent): void => {
+ // The page must not scroll and the browser must not run its own
+ // ctrl-wheel page zoom while the cursor is over the stage.
+ event.preventDefault();
+
+ const scale = DELTA_MODE_SCALE[event.deltaMode] ?? 1;
+
+ if (event.ctrlKey || event.metaKey) {
+ const [x, y] = localPoint(event);
+ const dy = Math.max(-MAX_ZOOM_DELTA, Math.min(MAX_ZOOM_DELTA, event.deltaY * scale));
+ zoomCameraAt(world, x, y, Math.exp(-dy * ZOOM_SENSITIVITY));
+ } else {
+ panCamera(world, event.deltaX * scale, event.deltaY * scale);
+ }
+ };
+
+ const handlePointerDown = (event: PointerEvent): void => {
+ if (panning) return;
+ if (!spaceHeld && event.button !== MIDDLE_BUTTON) return;
+
+ // Middle-click would otherwise start autoscroll on some platforms.
+ event.preventDefault();
+
+ panning = true;
+ panPointerId = event.pointerId;
+ canvas.setPointerCapture(event.pointerId);
+
+ [startX, startY] = localPoint(event);
+ const camera = getCamera(world);
+ startE = camera.e;
+ startF = camera.f;
+ updateCursor();
+ };
+
+ const handlePointerMove = (event: PointerEvent): void => {
+ if (!panning || event.pointerId !== panPointerId) return;
+
+ // Absolute offset from the drag origin rather than per-move deltas, so
+ // a long drag can't accumulate rounding error.
+ const [x, y] = localPoint(event);
+ setCamera(world, { e: startE + (x - startX), f: startF + (y - startY) });
+ };
+
+ const handlePointerUp = (event: PointerEvent): void => {
+ if (event.pointerId !== panPointerId) return;
+ endPan();
+ };
+
+ const handleKeyDown = (event: KeyboardEvent): void => {
+ if (event.code !== 'Space' || event.repeat || isEditable(event.target)) return;
+ spaceHeld = true;
+ updateCursor();
+ };
+
+ 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();
+ };
+
+ const handleBlur = (): void => {
+ // Key-up never arrives when focus leaves mid-hold (⌘-tab, devtools).
+ spaceHeld = false;
+ endPan();
+ updateCursor();
+ };
+
+ canvas.addEventListener('wheel', handleWheel, { passive: false });
+ canvas.addEventListener('pointerdown', handlePointerDown);
+ canvas.addEventListener('pointermove', handlePointerMove);
+ canvas.addEventListener('pointerup', handlePointerUp);
+ canvas.addEventListener('pointercancel', handlePointerUp);
+ document.addEventListener('keydown', handleKeyDown);
+ document.addEventListener('keyup', handleKeyUp);
+ window.addEventListener('blur', handleBlur);
+
+ return () => {
+ canvas.removeEventListener('wheel', handleWheel);
+ canvas.removeEventListener('pointerdown', handlePointerDown);
+ canvas.removeEventListener('pointermove', handlePointerMove);
+ canvas.removeEventListener('pointerup', handlePointerUp);
+ canvas.removeEventListener('pointercancel', handlePointerUp);
+ document.removeEventListener('keydown', handleKeyDown);
+ document.removeEventListener('keyup', handleKeyUp);
+ window.removeEventListener('blur', handleBlur);
+ endPan();
+ };
+}
+
+/**
+ * Gives the stage its camera gestures: wheel to scroll-pan, ctrl/⌘-wheel (and
+ * trackpad pinch, which browsers report the same way) to zoom at the cursor,
+ * and drag to pan while space is held or with the middle button. Renders
+ * nothing — drop it anywhere under an EngineProvider, in any order relative to
+ * EngineCanvas: it follows the canvas through the world's RenderSurface, so it
+ * binds as soon as one is mounted and rebinds if it is replaced.
+ */
+export function CameraController(): JSX.Element {
+ const world = useWorld();
+ const surface = useTrait(world, RenderSurface);
+
+ // Memoized on identity: RenderSurface also changes on every resize, and
+ // listeners must not be torn down and rebuilt for that.
+ const canvas = createMemo(() => {
+ const target = surface()?.canvas;
+ return target instanceof HTMLCanvasElement ? target : null;
+ });
+
+ createEffect(() => {
+ const target = canvas();
+ if (target) onCleanup(bindCameraInput(world, target));
+ });
+
+ return null;
+}
diff --git a/apps/web/src/engine/canvas.tsx b/apps/web/src/engine/canvas.tsx
index 330ad96e..632f4431 100644
--- a/apps/web/src/engine/canvas.tsx
+++ b/apps/web/src/engine/canvas.tsx
@@ -9,7 +9,8 @@ import { useEngineContext } from './context';
/**
* Mounts the engine onto a canvas sized to fill its container, and starts
- * the tick loop. Must render under an EngineProvider.
+ * the tick loop. Must render under an EngineProvider. Camera gestures are a
+ * separate concern: render a CameraController alongside it.
*/
export function EngineCanvas(): JSX.Element {
const engine = useEngineContext();
diff --git a/apps/web/src/engine/hooks/use-camera.ts b/apps/web/src/engine/hooks/use-camera.ts
index aeac7a66..50fd9e31 100644
--- a/apps/web/src/engine/hooks/use-camera.ts
+++ b/apps/web/src/engine/hooks/use-camera.ts
@@ -7,8 +7,20 @@ import { useTrait, useWorld } from '@diffusionstudio/koota-solid';
import type { Accessor } from 'solid-js';
-/** Reactive read of the document's Camera trait. Write via getDocument(world).set(Camera, ...). */
+/**
+ * Reactive read of the document's Camera trait. Write it with the operations
+ * in ../camera (they take the world), never by mutating the record.
+ */
export function useCamera(): Accessor<Camera2D | undefined> {
const world = useWorld();
return useTrait(world.get(Root)!, Camera);
}
+
+/** Reactive zoom factor of the stage camera (1 = 100%). */
+export function useCameraScale(): Accessor<number> {
+ const camera = useCamera();
+ return () => {
+ const { a = 1, b = 0 } = camera() ?? {};
+ return Math.hypot(a, b);
+ };
+}
diff --git a/apps/web/src/engine/index.ts b/apps/web/src/engine/index.ts
index 01cca498..1eb3d6ec 100644
--- a/apps/web/src/engine/index.ts
+++ b/apps/web/src/engine/index.ts
@@ -5,4 +5,5 @@
export * from './create-engine';
export * from './context';
export * from './canvas';
+export * from './camera-controller';
export * from './hooks';
diff --git a/packages/encoder/src/encoder.ts b/packages/encoder/src/encoder.ts
index 3b7e9ae9..300fff98 100644
--- a/packages/encoder/src/encoder.ts
+++ b/packages/encoder/src/encoder.ts
@@ -11,14 +11,15 @@ import {
import { Or } from 'koota';
import {
createRuntimeWorld, switchActiveScene, serializeEntity, cloneFromRecords,
- getEntityTree, getDocument, propagateTimeRangeDown, framesToSeconds,
+ getEntityTree, propagateTimeRangeDown, framesToSeconds,
assert, store, disposeDecoders,
playbackSystem, motionSystem, transformSystem, renderSystem,
AudioBus, AudioBusHandle,
ChildOf, Geometry, Group, Paint, Workarea, Playback,
AudioPlayback, Computed, Delay, Trim, Transition, Keyframe, Animation,
Position, Offset, Rotation, Scale, Skew,
- Project, Mode, Time, FrameRate, Camera, RenderSurface, AudioEngine,
+ Project, Mode, Time, FrameRate, RenderSurface, AudioEngine, Root,
+ resetCamera,
Assets, Fonts, FramePromises,
} from '@diffusionstudio/runtime';
@@ -100,7 +101,7 @@ export async function createEncoder(sourceWorld: World, config: EncoderConfig) {
world.set(FrameRate, { value: frameRate });
world.set(FramePromises, { list: [] });
- getDocument(world).set(Camera, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
+ resetCamera(world);
const eidMap = cloneFromRecords(world, subtreeRecords);
const scene = eidMap.get(sourceScene);
@@ -345,7 +346,7 @@ export async function createEncoder(sourceWorld: World, config: EncoderConfig) {
// Release decoder file handles/caches, then the world slot itself
// (koota caps live worlds at 16, so throwaway offline worlds must
// be destroyed — bitecs could just drop them).
- disposeDecoders(world, getDocument(world));
+ disposeDecoders(world, world.get(Root)!);
world.destroy();
}
};
@@ -505,7 +506,7 @@ export async function resolverSystem(world: World) {
* walk; koota has no hierarchy-ordered queries).
*/
export function recomputeAllTimeRanges(world: World): void {
- const document = getDocument(world);
+ const document = world.get(Root)!;
for (const node of world.query(Or(Geometry, Group), ChildOf(document))) {
propagateTimeRangeDown(world, node);
}
diff --git a/packages/encoder/src/image-encoder.ts b/packages/encoder/src/image-encoder.ts
index 7e59b6bf..d7c58d1a 100644
--- a/packages/encoder/src/image-encoder.ts
+++ b/packages/encoder/src/image-encoder.ts
@@ -5,12 +5,13 @@
import { Or } from 'koota';
import {
createRuntimeWorld, createEntity, appendChild, serializeEntity,
- cloneFromRecords, getEntityTree, getDocument, framesToSeconds,
+ cloneFromRecords, getEntityTree, framesToSeconds,
formatTimecode, assert, store, disposeDecoders,
playbackSystem, motionSystem, transformSystem, renderSystem,
ChildOf, Geometry, Group, Hidden, IsMask, Muted, Culled,
ClipsContent, Playback, Computed, WorldBounds,
- Project, Mode, Camera, RenderSurface, AudioEngine, Assets, Fonts,
+ Project, Mode, RenderSurface, AudioEngine, Assets, Fonts, Root,
+ resetCamera, setCamera,
FramePromises, Time, FrameRate,
} from '@diffusionstudio/runtime';
@@ -68,7 +69,7 @@ export async function createImageEncoder(sourceWorld: World, config: ImageEncode
world.set(FrameRate, { value: sourceFrameRate });
world.set(FramePromises, { list: [] });
- getDocument(world).set(Camera, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
+ resetCamera(world);
const eidMap = cloneFromRecords(world, records);
const root = eidMap.get(config.entity);
@@ -178,7 +179,7 @@ export async function createImageEncoder(sourceWorld: World, config: ImageEncode
resize(config.resolution);
// Shift the measured box onto the canvas so the node is centered in view;
// the camera translation is scaled by the surface resolution at render time.
- getDocument(world).set(Camera, { e: -bounds.minX, f: -bounds.minY });
+ setCamera(world, { e: -bounds.minX, f: -bounds.minY });
let canceled = false;
const cancel = () => (canceled = true);
@@ -217,7 +218,7 @@ export async function createImageEncoder(sourceWorld: World, config: ImageEncode
// document.body), then release decoders and the world slot itself
// (koota caps live worlds at 16).
mounts?.disposeAll();
- disposeDecoders(world, getDocument(world));
+ disposeDecoders(world, world.get(Root)!);
world.destroy();
}
};
diff --git a/packages/runtime/src/actions/camera.ts b/packages/runtime/src/actions/camera.ts
new file mode 100644
index 00000000..3a03f55d
--- /dev/null
+++ b/packages/runtime/src/actions/camera.ts
@@ -0,0 +1,127 @@
+/* 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/. */
+
+// Camera write path (was the app's systems/camera-controller.ts). Every write
+// goes through entity.set(Camera, …) so koota fires a change event and
+// reactive readers update — never mutate the record getCamera returns.
+//
+// These are the camera's semantics, not its input bindings: wheel, drag, and
+// keyboard handling live with the editor's DOM layer, which calls in here.
+
+import { Camera, Root } from '../traits';
+import { MAX_CAMERA_ZOOM, MIN_CAMERA_ZOOM } from '../constants';
+import { clamp, transformPoint } from '../math';
+import { getCamera, getCameraInverse, getCameraScale, getContentBounds, getEntityBounds, getViewport } from '../queries/camera';
+
+import type { Entity, World } from 'koota';
+import type { Camera2D } from '../traits';
+import type { Rect } from '../math';
+
+/** Default breathing room, in CSS pixels, left around a focused rect. */
+const FOCUS_PADDING = 80;
+
+/** Write camera components directly. Prefer the operations below. */
+export function setCamera(world: World, camera: Partial<Camera2D>): void {
+ world.get(Root)!.set(Camera, camera);
+}
+
+/** Reset to identity: no zoom, no offset. The capture pipeline renders here. */
+export function resetCamera(world: World): void {
+ setCamera(world, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
+}
+
+/**
+ * Scroll the view by a delta in canvas CSS pixels, as a wheel or trackpad
+ * gesture does: the content moves against the delta. Independent of zoom —
+ * the camera's offset is already in screen pixels.
+ */
+export function panCamera(world: World, screenDx: number, screenDy: number): void {
+ const { e, f } = getCamera(world);
+ setCamera(world, { e: e - screenDx, f: f - screenDy });
+}
+
+/**
+ * Zoom by `factor` while keeping the document point under (screenX, screenY)
+ * pinned there. Clamped to [MIN_CAMERA_ZOOM, MAX_CAMERA_ZOOM].
+ */
+export function zoomCameraAt(world: World, screenX: number, screenY: number, factor: number): void {
+ const inverse = getCameraInverse(world);
+ if (inverse === null) return;
+
+ const { a, b, c, d } = getCamera(world);
+ const anchor = transformPoint(inverse, screenX, screenY);
+
+ // Resolve the requested factor against the clamped scale, so zooming past
+ // a limit stops instead of drifting the pinned point.
+ const scale = Math.hypot(a, b);
+ if (scale <= 0) return;
+ const s = clamp(scale * factor, MIN_CAMERA_ZOOM, MAX_CAMERA_ZOOM) / scale;
+ if (s === 1) return;
+
+ // M' = T(anchor) · S(s) · T(-anchor) · M
+ setCamera(world, {
+ a: a * s,
+ b: b * s,
+ c: c * s,
+ d: d * s,
+ e: screenX - (a * s * anchor.x + c * s * anchor.y),
+ f: screenY - (b * s * anchor.x + d * s * anchor.y),
+ });
+}
+
+/** Zoom by `factor` around the center of the viewport. */
+export function zoomCameraBy(world: World, factor: number): void {
+ const viewport = getViewport(world);
+ if (!viewport) return;
+ zoomCameraAt(world, viewport.width / 2, viewport.height / 2, factor);
+}
+
+/** Zoom to an absolute scale (1 = 100%) around the center of the viewport. */
+export function setCameraZoom(world: World, scale: number): void {
+ const current = getCameraScale(world);
+ if (current <= 0) return;
+ zoomCameraBy(world, scale / current);
+}
+
+/** Zoom back to 100%, keeping the center of the viewport in place. */
+export function resetCameraZoom(world: World): void {
+ setCameraZoom(world, 1);
+}
+
+/**
+ * Frame a document-space rect: centered, scaled to fit inside the viewport
+ * with `padding` CSS pixels to spare. Never zooms past 100% — framing a small
+ * rect should bring it into view, not magnify it.
+ */
+export function focusRect(world: World, rect: Rect, padding = FOCUS_PADDING): void {
+ const viewport = getViewport(world);
+ if (!viewport || rect.width <= 0 || rect.height <= 0) return;
+
+ const width = viewport.width - padding * 2;
+ const height = viewport.height - padding * 2;
+ if (width <= 0 || height <= 0) return;
+
+ const scale = clamp(Math.min(width / rect.width, height / rect.height), MIN_CAMERA_ZOOM, 1);
+
+ setCamera(world, {
+ a: scale,
+ b: 0,
+ c: 0,
+ d: scale,
+ e: viewport.width / 2 - (rect.x + rect.width / 2) * scale,
+ f: viewport.height / 2 - (rect.y + rect.height / 2) * scale,
+ });
+}
+
+/** Frame the given entities. No-op if none of them has bounds yet. */
+export function focusEntities(world: World, entities: Iterable<Entity>, padding = FOCUS_PADDING): void {
+ const bounds = getEntityBounds(world, entities);
+ if (bounds) focusRect(world, bounds, padding);
+}
+
+/** Frame everything visible on the stage. No-op on an empty document. */
+export function focusContent(world: World, padding = FOCUS_PADDING): void {
+ const bounds = getContentBounds(world);
+ if (bounds) focusRect(world, bounds, padding);
+}
diff --git a/packages/runtime/src/actions/index.ts b/packages/runtime/src/actions/index.ts
index 2acf0fa9..e89072c4 100644
--- a/packages/runtime/src/actions/index.ts
+++ b/packages/runtime/src/actions/index.ts
@@ -10,6 +10,7 @@
// events on the traits these actions touch.
export * from './entities';
+export * from './camera';
export * from './hierarchy';
export * from './cache';
export * from './timing';
diff --git a/packages/runtime/src/constants.ts b/packages/runtime/src/constants.ts
index 85ac283f..7a95e2d4 100644
--- a/packages/runtime/src/constants.ts
+++ b/packages/runtime/src/constants.ts
@@ -6,6 +6,10 @@ export const CONONICAL_TIME_BASE = 1e6;
export const DEFAULT_DURATION_FRAMES = 16 * 30;
+// Stage camera zoom limits (1 = 100%).
+export const MIN_CAMERA_ZOOM = 0.01;
+export const MAX_CAMERA_ZOOM = 10;
+
export enum BlendMode {
SOURCE_OVER,
MULTIPLY,
diff --git a/packages/runtime/src/math/aabb.ts b/packages/runtime/src/math/aabb.ts
index e5856e5e..fdd71a42 100644
--- a/packages/runtime/src/math/aabb.ts
+++ b/packages/runtime/src/math/aabb.ts
@@ -45,6 +45,9 @@ export function aabbsIntersect(a: AABB, b: AABB): boolean {
export type Point = { x: number; y: number };
+/** An axis-aligned rectangle by origin and size (AABB by min/max corners). */
+export type Rect = { x: number; y: number; width: number; height: number };
+
/** Four corners of a transformed rect: [TL, TR, BR, BL]. */
export type Quad = [Point, Point, Point, Point];
diff --git a/packages/runtime/src/queries/camera.ts b/packages/runtime/src/queries/camera.ts
new file mode 100644
index 00000000..d0f60b30
--- /dev/null
+++ b/packages/runtime/src/queries/camera.ts
@@ -0,0 +1,130 @@
+/* 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/. */
+
+// Camera read path. The Camera trait on the document root is the viewport
+// transform: it maps document space to canvas CSS pixels, and the render and
+// transform systems scale it by RenderSurface.resolution to reach device
+// pixels (getViewMatrix). Writes live in actions/camera.ts.
+
+import { Or } from 'koota';
+
+import { Camera, Root, RenderSurface, WorldBounds, Geometry, Group, Hidden, ChildOf } from '../traits';
+import { store } from '../world/store';
+import { invert2D, transformPoint } from '../math';
+
+import type { Entity, World } from 'koota';
+import type { Camera2D } from '../traits';
+import type { Mat2D, Point, Rect } from '../math';
+
+/** Below this the camera is singular and screen↔document mapping is undefined. */
+const MIN_DETERMINANT = 1e-12;
+
+export type Viewport = { width: number; height: number };
+
+/** Current camera matrix. Read-only — write it through actions/camera.ts. */
+export function getCamera(world: World): Camera2D {
+ return world.get(Root)!.get(Camera)!;
+}
+
+/** Uniform zoom factor of the camera (1 = 100%). */
+export function getCameraScale(world: World): number {
+ const { a, b } = getCamera(world);
+ return Math.hypot(a, b);
+}
+
+/**
+ * Camera inverse, for mapping canvas CSS pixels back into the document, or
+ * null when the camera has been scaled to nothing.
+ */
+export function getCameraInverse(world: World): Mat2D | null {
+ const camera = getCamera(world);
+ if (Math.abs(camera.a * camera.d - camera.b * camera.c) < MIN_DETERMINANT) return null;
+ return invert2D(camera);
+}
+
+/**
+ * Camera × resolution: the document→device-pixel matrix the renderer puts on
+ * the context and the transform system feeds top-level nodes.
+ */
+export function getViewMatrix(world: World): Mat2D {
+ const { a, b, c, d, e, f } = getCamera(world);
+ const resolution = world.get(RenderSurface)?.resolution ?? 1;
+
+ return {
+ a: a * resolution, b: b * resolution,
+ c: c * resolution, d: d * resolution,
+ e: e * resolution, f: f * resolution,
+ };
+}
+
+/**
+ * Visible stage size in CSS pixels, or null before a surface is mounted. Taken
+ * from the render surface rather than the DOM so it matches what was drawn.
+ */
+export function getViewport(world: World): Viewport | null {
+ const surface = world.get(RenderSurface);
+ const canvas = surface?.canvas;
+ if (!canvas) return null;
+
+ const resolution = surface.resolution || 1;
+ return { width: canvas.width / resolution, height: canvas.height / resolution };
+}
+
+/** Convert a point in canvas CSS pixels to document space. */
+export function screenToWorld(world: World, screenX: number, screenY: number): Point {
+ const inverse = getCameraInverse(world);
+ return inverse === null ? { x: 0, y: 0 } : transformPoint(inverse, screenX, screenY);
+}
+
+/** Convert a point in document space to canvas CSS pixels. */
+export function worldToScreen(world: World, worldX: number, worldY: number): Point {
+ return transformPoint(getCamera(world), worldX, worldY);
+}
+
+/**
+ * Union of the entities' bounds in document space, or null when none of them
+ * has been through the transform system yet. WorldBounds are written straight
+ * into the SoA store (never added as a trait) and hold post-camera, post-DPR
+ * values, so read them by entity id and undo the view matrix here.
+ */
+export function getEntityBounds(world: World, entities: Iterable<Entity>): Rect | null {
+ const view = getViewMatrix(world);
+ if (Math.abs(view.a * view.d - view.b * view.c) < MIN_DETERMINANT) return null;
+ const inverse = invert2D(view);
+
+ const bounds = store(world, WorldBounds);
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
+
+ for (const entity of entities) {
+ const eid = entity.id();
+ if (bounds.minX[eid] === undefined) continue;
+
+ // All four corners, so the result stays an AABB even if the camera is
+ // ever given a rotation.
+ for (const [x, y] of [
+ [bounds.minX[eid], bounds.minY[eid]], [bounds.maxX[eid], bounds.minY[eid]],
+ [bounds.maxX[eid], bounds.maxY[eid]], [bounds.minX[eid], bounds.maxY[eid]],
+ ] as const) {
+ const point = transformPoint(inverse, x, y);
+ minX = Math.min(minX, point.x);
+ maxX = Math.max(maxX, point.x);
+ minY = Math.min(minY, point.y);
+ maxY = Math.max(maxY, point.y);
+ }
+ }
+
+ const width = maxX - minX;
+ const height = maxY - minY;
+ if (!(width > 0) || !(height > 0)) return null;
+
+ return { x: minX, y: minY, width, height };
+}
+
+/** Bounds of everything visible on the stage, or null on an empty document. */
+export function getContentBounds(world: World): Rect | null {
+ const content = world.query(Or(Geometry, Group), ChildOf(world.get(Root)!))
+ .filter((entity) => !entity.has(Hidden));
+
+ return getEntityBounds(world, content);
+}
diff --git a/packages/runtime/src/queries/index.ts b/packages/runtime/src/queries/index.ts
index a20852d5..b52cbf34 100644
--- a/packages/runtime/src/queries/index.ts
+++ b/packages/runtime/src/queries/index.ts
@@ -1,3 +1,4 @@
export * from './predicates';
+export * from './camera';
export * from './hierarchy';
export * from './timeline-index';
diff --git a/packages/runtime/src/systems/render.ts b/packages/runtime/src/systems/render.ts
index 3c1b2ef4..4a631a9f 100644
--- a/packages/runtime/src/systems/render.ts
+++ b/packages/runtime/src/systems/render.ts
@@ -27,6 +27,7 @@ import {
Root,
} from '../traits';
import { getParentNode } from '../queries/hierarchy';
+import { getViewMatrix } from '../queries/camera';
import { colorToHex } from '../utils/color';
import { renderText } from '../utils/text';
import { getTransitionWindow } from '../utils/transition';
@@ -854,16 +855,8 @@ export function renderSystem(world: World): void {
}
// Apply camera transform: DPR * Camera
- const camera = world.get(Root)!.get(Camera)!
- const resolution = surface.resolution;
- ctx.setTransform(
- camera.a * resolution,
- camera.b * resolution,
- camera.c * resolution,
- camera.d * resolution,
- camera.e * resolution,
- camera.f * resolution,
- );
+ const view = getViewMatrix(world);
+ ctx.setTransform(view.a, view.b, view.c, view.d, view.e, view.f);
// Render top-level nodes.
const document = world.get(Root)!;
diff --git a/packages/runtime/src/systems/transform.ts b/packages/runtime/src/systems/transform.ts
index 15bc627b..fe819451 100644
--- a/packages/runtime/src/systems/transform.ts
+++ b/packages/runtime/src/systems/transform.ts
@@ -8,10 +8,11 @@ import { store } from '../world/store';
import {
ChildOf, Geometry, Group, Hidden, Sequential, AdjustmentLayer,
Culled, Flip, Anchor, Computed, Cache, LocalTransform, WorldTransform,
- WorldBounds, Camera, RenderSurface,
+ WorldBounds, RenderSurface,
Root,
} from '../traits';
import { getParentNode } from '../queries/hierarchy';
+import { getViewMatrix } from '../queries/camera';
import {
multiply2D,
@@ -93,13 +94,7 @@ export function computeWorldTransform(world: World, entity: Entity, parentEntity
e: worldStore.e[pid], f: worldStore.f[pid],
};
} else {
- const camera = world.get(Root)!.get(Camera)!;
- const res = world.get(RenderSurface)?.resolution ?? 1;
- parent = {
- a: camera.a * res, b: camera.b * res,
- c: camera.c * res, d: camera.d * res,
- e: camera.e * res, f: camera.f * res,
- };
+ parent = getViewMatrix(world);
}
const local: Mat2D = {