Skip to content

The VS Code of video editing, built for agents.

TypeScript

Refactor world and document interactions to utilize getDocument for trait management

konstantin-paulus880a11214d82
diff --git a/apps/web/src/components/sidebar-right/inspector/background.tsx b/apps/web/src/components/sidebar-right/inspector/background.tsx
index b4570b97..84b45818 100644
--- a/apps/web/src/components/sidebar-right/inspector/background.tsx
+++ b/apps/web/src/components/sidebar-right/inspector/background.tsx
@@ -16,20 +16,21 @@ import { ColorOpacityRow } from "@/components/ui/color-opacity-row";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { createSignal } from "solid-js";
-import { Background, DEFAULT_BACKGROUND } from "@diffusionstudio/runtime";
+import { Background, DEFAULT_BACKGROUND, getDocument } from "@diffusionstudio/runtime";
import { useTrait, useWorld } from "@diffusionstudio/koota-solid";
export function BackgroundSettings() {
const world = useWorld();
const [isPickerOpen, setIsPickerOpen] = createSignal(false);
- const background = useTrait(world, Background);
+ const document = getDocument(world);
+ const background = useTrait(document, Background);
const color = () => background()?.value ?? DEFAULT_BACKGROUND;
let anchorRef: HTMLDivElement | undefined;
- const assignColor = (value: number) => world.set(Background, { value });
+ const assignColor = (value: number) => document.set(Background, { value });
return (
<PanelSection title="Background" ref={anchorRef}>
diff --git a/apps/web/src/engine/hooks/use-camera.ts b/apps/web/src/engine/hooks/use-camera.ts
index 9a8ae40a..9999a5cb 100644
--- a/apps/web/src/engine/hooks/use-camera.ts
+++ b/apps/web/src/engine/hooks/use-camera.ts
@@ -2,12 +2,12 @@
* 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 { Camera, type Camera2D } from '@diffusionstudio/runtime';
+import { Camera, getDocument, type Camera2D } from '@diffusionstudio/runtime';
import { useTrait, useWorld } from '@diffusionstudio/koota-solid';
import type { Accessor } from 'solid-js';
-/** Reactive read of the world's Camera trait. Write via world.set(Camera, ...). */
+/** Reactive read of the document's Camera trait. Write via getDocument(world).set(Camera, ...). */
export function useCamera(): Accessor<Camera2D | undefined> {
- return useTrait(useWorld(), Camera);
+ return useTrait(getDocument(useWorld()), Camera);
}
diff --git a/packages/encoder/src/encoder.ts b/packages/encoder/src/encoder.ts
index 7ea3404d..89de2097 100644
--- a/packages/encoder/src/encoder.ts
+++ b/packages/encoder/src/encoder.ts
@@ -97,10 +97,11 @@ export async function createEncoder(sourceWorld: World, config: EncoderConfig) {
world.set(Fonts, { list: [...(sourceWorld.get(Fonts)?.list ?? [])] });
world.set(RenderSurface, { canvas: offscreenCanvas, ctx: offscreenCtx, resolution: scale });
world.set(AudioEngine, { context: offlineAudioCtx });
- world.set(Camera, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
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 });
+
const eidMap = cloneFromRecords(world, subtreeRecords);
const scene = eidMap.get(sourceScene);
assert(scene !== undefined, 'Failed to clone scene subtree');
diff --git a/packages/encoder/src/image-encoder.ts b/packages/encoder/src/image-encoder.ts
index 0f89df65..da911806 100644
--- a/packages/encoder/src/image-encoder.ts
+++ b/packages/encoder/src/image-encoder.ts
@@ -65,10 +65,11 @@ export async function createImageEncoder(sourceWorld: World, config: ImageEncode
world.set(Fonts, { list: [...(sourceWorld.get(Fonts)?.list ?? [])] });
world.set(RenderSurface, { canvas: offscreenCanvas, ctx: offscreenCtx, resolution: 1 });
world.set(AudioEngine, { context: offlineAudioCtx });
- world.set(Camera, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
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 });
+
const eidMap = cloneFromRecords(world, records);
const root = eidMap.get(config.entity);
assert(root !== undefined, 'Failed to clone entity subtree');
@@ -177,7 +178,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.
- world.set(Camera, { e: -bounds.minX, f: -bounds.minY });
+ getDocument(world).set(Camera, { e: -bounds.minX, f: -bounds.minY });
let canceled = false;
const cancel = () => (canceled = true);
diff --git a/packages/reconciler/src/document.ts b/packages/reconciler/src/document.ts
index 9544c0e4..5ed84394 100644
--- a/packages/reconciler/src/document.ts
+++ b/packages/reconciler/src/document.ts
@@ -119,7 +119,7 @@ export class RuntimeDocument implements ProjectDocument<SceneNode> {
}
case 'background': {
const color = typeof value === 'string' ? parseColor(value) : null;
- this.world.set(Background, { value: color ?? DEFAULT_BACKGROUND });
+ this.stage.entity.set(Background, { value: color ?? DEFAULT_BACKGROUND });
return;
}
default:
@@ -147,7 +147,7 @@ export class RuntimeDocument implements ProjectDocument<SceneNode> {
for (const child of this.children(node)) {
this.removeNode(node, child);
}
- this.world.set(Background, { value: DEFAULT_BACKGROUND });
+ node.entity.set(Background, { value: DEFAULT_BACKGROUND });
return;
}
// ChildOf auto-destroys orphans, so paints go with it.
diff --git a/packages/runtime/src/systems/render.ts b/packages/runtime/src/systems/render.ts
index 6088699d..d040fce4 100644
--- a/packages/runtime/src/systems/render.ts
+++ b/packages/runtime/src/systems/render.ts
@@ -427,7 +427,7 @@ function renderShadows(world: World, entity: Entity): void {
// ctx.shadowBlur/OffsetX/OffsetY are in device-pixel space and are not
// affected by the current transform, so scale them up to match the
// content transform (camera * resolution).
- const camera = world.get(Camera);
+ const camera = getDocument(world).get(Camera);
const resolution = world.get(RenderSurface)?.resolution ?? 1;
const shadowScale = (camera?.a ?? 1) * resolution;
@@ -845,7 +845,7 @@ export function renderSystem(world: World): void {
// renders just the scene onto a transparent canvas (the scene paints its
// own fill if it has one).
if (world.get(Mode)?.value === 'realtime') {
- ctx.fillStyle = colorToHex(world.get(Background)?.value ?? 0);
+ ctx.fillStyle = colorToHex(getDocument(world).get(Background)?.value ?? 0);
ctx.fillRect(0, 0, cw, ch);
world.get(HitRegions)?.list.push({
target: { kind: 'hud', id: 'canvas', quad: getCanvasQuad(cw, ch) },
@@ -853,7 +853,7 @@ export function renderSystem(world: World): void {
}
// Apply camera transform: DPR * Camera
- const camera = world.get(Camera) ?? { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };
+ const camera = getDocument(world).get(Camera)!
const resolution = surface.resolution;
ctx.setTransform(
camera.a * resolution,
diff --git a/packages/runtime/src/systems/transform.ts b/packages/runtime/src/systems/transform.ts
index 2469d6bd..00ae0d6e 100644
--- a/packages/runtime/src/systems/transform.ts
+++ b/packages/runtime/src/systems/transform.ts
@@ -92,7 +92,7 @@ export function computeWorldTransform(world: World, entity: Entity, parentEntity
e: worldStore.e[pid], f: worldStore.f[pid],
};
} else {
- const camera = world.get(Camera)!;
+ const camera = getDocument(world).get(Camera)!;
const res = world.get(RenderSurface)?.resolution ?? 1;
parent = {
a: camera.a * res, b: camera.b * res,
diff --git a/packages/runtime/src/traits/world.ts b/packages/runtime/src/traits/world.ts
index 01c0e943..d9a1186e 100644
--- a/packages/runtime/src/traits/world.ts
+++ b/packages/runtime/src/traits/world.ts
@@ -20,20 +20,15 @@ export const Project = trait({ id: '' });
// Tag on the single document root entity every runtime world owns. All
// rendered entities are its descendants (ChildOf), so "top-level" means
// "direct child of the document", never "has no parent". Destroying it
-// cascades through the whole document tree.
+// cascades through the whole document tree. Document-level state (Camera,
+// Background) lives on this entity, not on the world; read it via
+// getDocument(world).
export const DocumentRoot = trait();
-export type RuntimeMode = 'realtime' | 'offline-video' | 'offline-audio';
-
-export const Mode = trait({ value: 'realtime' as RuntimeMode });
-
-// Scene the playhead, timeline, and capture operate on (was selection.scene).
-export const ActiveScene = trait({ entity: null as Entity | null });
-
/**
- * 2D affine camera transform in CSS pixel space (before DPR scaling). The
- * render system multiplies this by RenderSurface.resolution to derive the
- * canvas transform.
+ * 2D affine camera transform in CSS pixel space (before DPR scaling), on the
+ * document root. The render system multiplies this by RenderSurface.resolution
+ * to derive the canvas transform.
*/
export const Camera = trait({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
@@ -41,8 +36,16 @@ export type Camera2D = { a: number; b: number; c: number; d: number; e: number;
export const DEFAULT_BACKGROUND = 0x161616;
+// Stage background color, on the document root.
export const Background = trait({ value: DEFAULT_BACKGROUND });
+export type RuntimeMode = 'realtime' | 'offline-video' | 'offline-audio';
+
+export const Mode = trait({ value: 'realtime' as RuntimeMode });
+
+// Scene the playhead, timeline, and capture operate on (was selection.scene).
+export const ActiveScene = trait({ entity: null as Entity | null });
+
// Frame clock (was timestamp).
export const Time = trait({ now: 0, delta: 0 });
diff --git a/packages/runtime/src/utils/text.ts b/packages/runtime/src/utils/text.ts
index 25571863..f26b02d5 100644
--- a/packages/runtime/src/utils/text.ts
+++ b/packages/runtime/src/utils/text.ts
@@ -14,6 +14,7 @@ import {
Chars, TextStyle, TextRange, TextCache, Cache, Computed, Camera,
RenderSurface,
} from '../traits';
+import { getDocument } from '../queries/hierarchy';
import { clamp } from '../math/common';
import { colorToHex } from './color';
import { createLinearGradient, createRadialGradient } from '../systems/gradients';
@@ -298,7 +299,7 @@ function renderTokens(ctx: Ctx, world: World, entity: Entity): void {
// ctx.shadowBlur/OffsetX/OffsetY are in device-pixel space and are not
// affected by the current transform, so scale them up to match the
// content transform (camera * resolution).
- const camera = world.get(Camera);
+ const camera = getDocument(world).get(Camera);
const resolution = world.get(RenderSurface)?.resolution ?? 1;
const shadowScale = (camera?.a ?? 1) * resolution;
diff --git a/packages/runtime/src/world/create-world.ts b/packages/runtime/src/world/create-world.ts
index f08db4b8..ec4960cc 100644
--- a/packages/runtime/src/world/create-world.ts
+++ b/packages/runtime/src/world/create-world.ts
@@ -36,8 +36,6 @@ export function createRuntimeWorld(projectId: string) {
Project({ id: projectId }),
Mode,
ActiveScene,
- Camera,
- Background,
Time,
FrameRate,
RenderSurface,
@@ -51,8 +49,8 @@ export function createRuntimeWorld(projectId: string) {
HitRegions,
);
- // The document root all rendered entities hang off (see DocumentRoot).
- world.spawn(DocumentRoot);
+ // The document root all rendered entities hang off (see DocumentRoot);
+ world.spawn(DocumentRoot, Camera, Background);
// Cache upkeep, Computed mirrors, and time-range reactions.
observeWorld(world);