Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
Compositions get the web's canvas 2D context, requestAnimationFrame and Image (#55, #56)
shinyobjectz645b0853cc83
diff --git a/runtime/bundle/src/entry.rs b/runtime/bundle/src/entry.rsindex b1e1e2ad..233bc25c 100644--- a/runtime/bundle/src/entry.rs+++ b/runtime/bundle/src/entry.rs@@ -11,8 +11,10 @@ pub fn entry(file: &str, o: &CompOpts) -> String {// RAEA_STILL_TREE=0 makes it each frame, as before. In the entry's text, so the bundle cache tells the two apartlet still = std::env::var("RAEA_STILL_TREE").map_or(true, |v| v != "0");format!(- r#"import {{ pureAgain, pureFrame, pureSession, seedOf }} from "./motion/pure";-import {{ mount, addEventListener }} from "bevy-react";+ r#"import {{ frameCallbacks, pureAgain, pureFrame, pureSession, seedOf }} from "./motion/pure";+import {{ canvas2d }} from "./motion/canvas2d";+import {{ mount, addEventListener, BevyCanvasElement }} from "bevy-react";+canvas2d(BevyCanvasElement); // a <canvas> ref's getContext("2d") is the web's (motion canvas2d.ts, #55)import {{ Component, useEffect, useMemo, useState }} from "react";import * as M from "./src/{file}";import {{ Clock, getCompositions, tickClocks }} from "./motion";@@ -89,7 +91,7 @@ class Catch extends Component<{{ children?: any }}, {{ err: string | null }}> {{const LIVE: any = {{}};let live = false;function Root() {{- const [f, setF0] = useState(-1); const setF = (n: number) => {{ tickClocks(); setF0(n); }}; // the Clocks' frame readers told in the same batch (motion clock.tsx tickClocks)+ const [f, setF0] = useState(-1); const setF = (n: number) => {{ tickClocks(); frameCallbacks(n, cfg.fps); setF0(n); }}; // the Clocks' frame readers told in the same batch (motion clock.tsx tickClocks), and requestAnimationFrame's callbacks (motion frame-globals.ts)// the stage's size, for a composition that lays out from useVideoConfig (raea-size)const [size, setSize] = useState<{{ w: number; h: number }} | null>(null);useEffect(() => addEventListener("raea-size", (v: any) => setSize(v)), []);@@ -157,7 +159,7 @@ pub fn entry_lite(file: &str, o: &CompOpts) -> String {let end = full.find("// a throw while rendering the composition").expect("entry's Root");let bridge = raea_io_home::home().join("sdk/react/js/node_modules/bevy-react/src/bridge.ts");format!(- r#"import {{ pureAgain, pureFrame, pureSession, seedOf }} from "./motion/pure";+ r#"import {{ frameCallbacks, pureAgain, pureFrame, pureSession, seedOf }} from "./motion/pure";import {{ addEventListener, reset, runEventLoop }} from {bridge:?};import {{ renderRoot, takeRendered }} from "react";{preamble}const LIVE: any = {{}};@@ -175,8 +177,8 @@ function toneOut() {{return toneEl;}}function tree() {{- // the frame's Math.random and Date (motion/pure.ts)- if (f >= 0) pureFrame(f, cfg.fps);+ // the frame's Math.random and Date, and requestAnimationFrame's callbacks (motion/pure.ts)+ if (f >= 0) {{ frameCallbacks(f, cfg.fps); pureFrame(f, cfg.fps); }}if (f < 0) return <surface id="motion" w={{1}} px={{cfg.width}} pxH={{cfg.height}}><div data-raea-frame={{-1}} data-raea-config={{conf}} /></surface>;return (<surface id="motion" w={{1}} px={{cfg.width}} pxH={{cfg.height}}>diff --git a/runtime/bundle/src/rewrite.rs b/runtime/bundle/src/rewrite.rsindex 76344349..a4a8639c 100644--- a/runtime/bundle/src/rewrite.rs+++ b/runtime/bundle/src/rewrite.rs@@ -5,14 +5,10 @@ pub fn copy_dir(from: &Path, to: &Path, depth: usize) -> R<()> {for e in std::fs::read_dir(from).map_err(|e| format!("{}: {e}", from.display()))? {let e = e.map_err(|e| e.to_string())?;let name = e.file_name().to_string_lossy().to_string();- if name.starts_with('.') || name == "node_modules" || name == "target" {- continue;- }+ if name.starts_with('.') || name == "node_modules" || name == "target" { continue; }let p = e.path();if p.is_dir() {- if depth < 6 {- copy_dir(&p, &to.join(&name), depth + 1)?;- }+ if depth < 6 { copy_dir(&p, &to.join(&name), depth + 1)?; }} else if matches!(p.extension().and_then(|x| x.to_str()), Some("ts" | "tsx" | "js" | "jsx" | "json" | "css")) {std::fs::copy(&p, to.join(&name)).map_err(|e| format!("{}: {e}", p.display()))?;}@@ -124,10 +120,10 @@ pub fn sources(root: &Path) -> R<Vec<PathBuf>> {/// A file of motion's own copy with its imports of the packages its code moved into (`sdks`) pointed at their copies/// beside it, `up` being the way from its folder to the copy's root (motion/x.ts imports "@raea/app/clock":-/// "../app/clock"; motion/3d/x.ts, "../../app/clock").+/// "../app/clock"; motion/3d/x.ts, "../../app/clock"). A module listed alone ("@raea/ui/canvas") is pointed too.pub fn point_sdks(src: &str, up: &str, sdks: &[(String, String)]) -> String {let re = regex::Regex::new(r#"(\bfrom\s+)(["'])(@raea/[a-z]+)((?:/[^"']*)?)["']"#).unwrap();- re.replace_all(src, |c: ®ex::Captures| match sdks.iter().find(|(name, _)| *name == &c[3]) {+ re.replace_all(src, |c: ®ex::Captures| match sdks.iter().find(|(name, _)| *name == &c[3] || name.strip_prefix(&c[3]) == Some(&c[4])) {Some((_, dir)) => format!("{}\"{up}{}{}\"", &c[1], dir.rsplit('/').nth(1).unwrap_or(dir), &c[4]),None => c[0].to_string(),})diff --git a/runtime/bundle/src/tests.rs b/runtime/bundle/src/tests.rsindex be589420..5989447d 100644--- a/runtime/bundle/src/tests.rs+++ b/runtime/bundle/src/tests.rs@@ -37,6 +37,7 @@ fn point_sdks_climbs_from_a_nested_file() {let src = "import { useClockState } from \"@raea/app/clock\";\nimport { x } from \"@raea/nope\";\n";assert_eq!(point_sdks(src, "../", &sdks()), src.replace("@raea/app/clock", "../app/clock"));assert_eq!(point_sdks(src, "../../", &sdks()), src.replace("@raea/app/clock", "../../app/clock"));+ assert_eq!(point_sdks("import { C } from \"@raea/ui/canvas\";", "../", &sdks()), "import { C } from \"../ui/canvas\";");}#[test]diff --git a/sdk/raea/conformance/frame-globals.test.ts b/sdk/raea/conformance/frame-globals.test.tsnew file mode 100644index 00000000..d6d3fc3a--- /dev/null+++ b/sdk/raea/conformance/frame-globals.test.ts@@ -0,0 +1,43 @@+// requestAnimationFrame and Image where a composition's runtime has none (#56): callbacks run once per frame, given the+// frame's time, and a preload's load fires.+import { expect, test } from "bun:test";++const g = globalThis as any;+const had = { raf: g.requestAnimationFrame, caf: g.cancelAnimationFrame, Image: g.Image };+delete g.requestAnimationFrame;+delete g.cancelAnimationFrame;+delete g.Image;+const { frameCallbacks } = await import("../src/frame-globals");+const ours = { raf: g.requestAnimationFrame, caf: g.cancelAnimationFrame, Image: g.Image };+Object.assign(g, { requestAnimationFrame: had.raf, cancelAnimationFrame: had.caf, Image: had.Image });++test("a frame callback runs once, at the next frame, with that frame's time", () => {+ const got: number[] = [];+ ours.raf((t: number) => got.push(t));+ const gone = ours.raf(() => got.push(-1));+ ours.caf(gone);+ frameCallbacks(3, 30);+ frameCallbacks(3, 30);+ frameCallbacks(4, 30);+ expect(got).toEqual([100]);+});++test("a callback asked for while one runs waits for the frame after", () => {+ const got: number[] = [];+ ours.raf(() => ours.raf((t: number) => got.push(t)));+ frameCallbacks(10, 25);+ expect(got).toEqual([]);+ frameCallbacks(11, 25);+ expect(got).toEqual([440]);+});++test("an Image's load fires once its src is set", async () => {+ const img = new ours.Image();+ const seen: string[] = [];+ img.onload = () => seen.push("onload");+ img.addEventListener("load", () => seen.push("listener"));+ img.src = "/media/x.png";+ expect(img.complete).toBe(false);+ await Promise.resolve();+ expect([seen, img.complete, img.src]).toEqual([["onload", "listener"], true, "/media/x.png"]);+});diff --git a/sdk/raea/src/canvas2d.ts b/sdk/raea/src/canvas2d.tsnew file mode 100644index 00000000..9475ed42--- /dev/null+++ b/sdk/raea/src/canvas2d.ts@@ -0,0 +1,77 @@+// A composition's <canvas> with the web's 2D context (#55): getContext("2d") on its ref is @raea/ui's+// CanvasRenderingContext2D (setTransform, createImageData, text, gradients, paths), the one an app page has, and its+// display list goes to the element as its `__canvas2d` prop, which the page draws into the canvas's bitmap+// (systems/canvas) as it does an app page's. bevy-react's own context records another API that nothing here draws.+//+// The handle bevy-react gives a ref keeps no props, so a canvas's width and height (its bitmap's size, 300 x 150 unset,+// as a browser has it) are read from the ops the bridge sends, each batch passing the host's op_flush as JSON; setting+// them on the ref sends them as props, and clears the bitmap, as it does in a browser. getImageData reads zeros: a+// composition has no host to read pixels back from.++import { CanvasRenderingContext2D_ } from "@raea/ui/canvas";++/** bevy-react's canvas handle, as the entry passes it (this module can't import bevy-react: the SDK's checks load it+ * where only the bundle's runtime has it) */+type Handle = { readonly id: number };+type HandleClass = { prototype: Handle };++type Size = { width: number; height: number };+type Op = { op: string; id?: number; kind?: string; props?: Record<string, unknown> };++const sizes = new Map<number, Size>();+const contexts = new Map<number, CanvasRenderingContext2D_>();+const HOST = (globalThis as any).__bevyHost;++const dim = (v: unknown, d: number) => {+ const n = typeof v === "number" ? v : parseInt(String(v ?? ""), 10);+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : d;+};++/** A batch's canvas creates and updates: their width and height as the element now has them. */+function sniff(json: string): void {+ if (!json.includes('"canvas"')) return;+ for (const op of JSON.parse(json) as Op[]) {+ if (op.kind !== "canvas" || op.id === undefined || !op.props) continue;+ const was = sizes.get(op.id) ?? { width: 300, height: 150 };+ const now = { width: dim(op.props.width ?? was.width, 300), height: dim(op.props.height ?? was.height, 150) };+ sizes.set(op.id, now);+ if (now.width !== was.width || now.height !== was.height) contexts.get(op.id)?._reset();+ }+}++/** Props sent to canvas `id` now, outside React's commits (its own batch, as bevy-react sends a canvas's draws). */+function send(id: number, props: Record<string, unknown>): void {+ HOST.op_flush(JSON.stringify([{ op: "update", id, kind: "canvas", props }]), false);+}++/** Installs the context on bevy-react's canvas handle (`El`, its BevyCanvasElement), once, from the entry. */+export function canvas2d(El: HandleClass): void {+ if (!HOST || typeof HOST.op_flush !== "function" || HOST.__canvas2d) return;+ HOST.__canvas2d = true;+ const flush = HOST.op_flush;+ HOST.op_flush = (json: string, devtools: boolean) => {+ sniff(json);+ return flush(json, devtools);+ };+ const size = (id: number) => sizes.get(id) ?? { width: 300, height: 150 };+ const resize = (id: number, k: keyof Size, v: number) => {+ const s = { ...size(id), [k]: Math.max(0, Math.floor(Number(v) || 0)) };+ sizes.set(id, s);+ send(id, { [k]: s[k] });+ contexts.get(id)?._reset();+ };+ Object.defineProperties(El.prototype, {+ width: { configurable: true, get(this: Handle) { return size(this.id).width; }, set(this: Handle, v: number) { resize(this.id, "width", v); } },+ height: { configurable: true, get(this: Handle) { return size(this.id).height; }, set(this: Handle, v: number) { resize(this.id, "height", v); } },+ });+ (El.prototype as any).getContext = function (this: Handle, kind = "2d") {+ if (kind !== "2d") return null;+ const id = this.id;+ let ctx = contexts.get(id);+ if (!ctx) {+ const canvas = { get width() { return size(id).width; }, get height() { return size(id).height; }, getAttribute: (k: string) => (k === "width" || k === "height" ? String(size(id)[k]) : null), _send: (list: unknown) => send(id, { __canvas2d: list }) };+ contexts.set(id, (ctx = new CanvasRenderingContext2D_(canvas)));+ }+ return ctx;+ };+}diff --git a/sdk/raea/src/frame-globals.ts b/sdk/raea/src/frame-globals.tsnew file mode 100644index 00000000..6bcfa043--- /dev/null+++ b/sdk/raea/src/frame-globals.ts@@ -0,0 +1,92 @@+// Browser globals a composition's runtime doesn't have, installed only where one is missing (#56): components written+// for a web page call them. requestAnimationFrame's callbacks run once per frame the composition draws, given that frame's+// time (f * 1000 / fps ms), so a frame drawn again (a resumed render, `--at`) gets the same calls; one asked for while a+// frame draws runs at the next frame. `new Image()` loads: setting its src fires load (and onload) on the next microtask,+// so a preload resolves. It has no pixel size (naturalWidth and the rest stay 0): nothing reads a file's size+// synchronously here, and `<img>` draws the file itself.++type FrameCallback = (time: number) => void;++let queue = new Map<number, FrameCallback>();+let next = 1;+let ran = -1;++/** Frame `f` at `fps` starts: the callbacks asked for before it run, once (a second draw of the same frame runs none). */+export function frameCallbacks(f: number, fps: number): void {+ if (f === ran || queue.size === 0) return;+ ran = f;+ const due = queue;+ queue = new Map();+ const time = (f * 1000) / (fps > 0 ? fps : 30);+ for (const cb of due.values()) {+ try {+ cb(time);+ } catch (e) {+ console.error(e);+ }+ }+}++type Listener = (e: { type: string; target: unknown; currentTarget: unknown }) => void;++/** A preloadable image: its src set, load fires. */+class FrameImage {+ onload: Listener | null = null;+ onerror: Listener | null = null;+ complete = true;+ width = 0;+ height = 0;+ naturalWidth = 0;+ naturalHeight = 0;+ alt = "";+ crossOrigin: string | null = null;+ decoding = "auto";+ loading = "eager";+ #src = "";+ #listeners = new Map<string, Set<Listener>>();++ constructor(width?: number, height?: number) {+ this.width = width ?? 0;+ this.height = height ?? 0;+ }++ get src(): string {+ return this.#src;+ }++ set src(v: string) {+ this.#src = String(v);+ this.complete = false;+ queueMicrotask(() => {+ this.complete = true;+ const e = { type: "load", target: this, currentTarget: this };+ this.onload?.call(this, e);+ for (const l of this.#listeners.get("load") ?? []) l.call(this, e);+ });+ }++ addEventListener(type: string, l: Listener): void {+ const set = this.#listeners.get(type) ?? new Set();+ set.add(l);+ this.#listeners.set(type, set);+ }++ removeEventListener(type: string, l: Listener): void {+ this.#listeners.get(type)?.delete(l);+ }++ decode(): Promise<void> {+ return Promise.resolve();+ }+}++const g = globalThis as any;+if (typeof g.requestAnimationFrame !== "function") {+ g.requestAnimationFrame = (cb: FrameCallback) => {+ const id = next++;+ queue.set(id, cb);+ return id;+ };+ g.cancelAnimationFrame = (id: number) => void queue.delete(id);+}+if (typeof g.Image !== "function") g.Image = FrameImage;diff --git a/sdk/raea/src/pure.ts b/sdk/raea/src/pure.tsindex fa164ca0..1dc4f654 100644--- a/sdk/raea/src/pure.ts+++ b/sdk/raea/src/pure.ts@@ -95,3 +95,6 @@ if (!g.__raeaPure) {// for @raea/app's game fold, which raea is built on and so can't import thisg.__raeaPureStep = pureStep;}++// requestAnimationFrame's callbacks, run by the entry as each frame starts (frame-globals.ts, #56)+export { frameCallbacks } from "./frame-globals";diff --git a/sdk/tsconfig.base.json b/sdk/tsconfig.base.jsonindex bdc74f2b..6a05dad6 100644--- a/sdk/tsconfig.base.json+++ b/sdk/tsconfig.base.json@@ -101,6 +101,7 @@"@raea/render": ["./render/src/index.ts"],"@raea/render/*": ["./render/src/*"],"@raea/ui/plugin": ["./ui/src/plugin.ts"],+ "@raea/ui/canvas": ["./ui/src/canvas.ts"],"@raea/physics": ["./physics/src/index.ts"],"@raea/physics/*": ["./physics/src/*"],"@raea/web": ["./web/src/index.tsx"],diff --git a/sdk/ui/src/canvas/context.ts b/sdk/ui/src/canvas/context.tsindex 96f94cbb..74247545 100644--- a/sdk/ui/src/canvas/context.ts+++ b/sdk/ui/src/canvas/context.ts@@ -63,9 +63,11 @@ export class CanvasRenderingContext2D_ {this.pending = true;queueMicrotask(() => {this.pending = false;+ const list = { gen: this.gen, w: this.size[0], h: this.size[1], ops: this.list };+ if (this.canvas._send) return this.canvas._send(list);const id = this.canvas.__wid;if (id === undefined || !this.canvas._wired) return;- wire.set(id, "__canvas2d", { gen: this.gen, w: this.size[0], h: this.size[1], ops: this.list });+ wire.set(id, "__canvas2d", list);});}private static uids = 0;diff --git a/sdk/ui/src/canvas/paths.ts b/sdk/ui/src/canvas/paths.tsindex 2a821a62..e7ccfd8c 100644--- a/sdk/ui/src/canvas/paths.ts+++ b/sdk/ui/src/canvas/paths.ts@@ -151,5 +151,7 @@ wire.on<{ default: string; families: Record<string, { em: number; adv: Record<stexport interface CanvasHost {__wid?: number;_wired?: boolean;+ /** Sends the list itself, for a canvas that isn't on this wire (a composition's, sdk/raea canvas.ts: #55) */+ _send?(list: { gen: number; w: number; h: number; ops: unknown[] }): void;getAttribute(k: string): string | null;}diff --git a/tools/manual-ref/sdk.ts b/tools/manual-ref/sdk.tsindex a9f2111c..9aaeacae 100644--- a/tools/manual-ref/sdk.ts+++ b/tools/manual-ref/sdk.ts@@ -14,7 +14,7 @@ const ROOT = path.resolve(import.meta.dir, "../..")const ts = createRequire(path.join(ROOT, "sdk/shell/package.json"))("typescript") as typeof import("typescript")const SRC = path.join(ROOT, "sdk/raea/src")const REPO = "https://github.com/shinyobjectz/raea/blob/main"-const SKIP = /(\.gen\.ts|^test\.tsx|^native-calls\.ts|^prelude\.ts|^pure\.ts)$/+const SKIP = /(\.gen\.ts|^test\.tsx|^native-calls\.ts|^prelude\.ts|^pure\.ts|^frame-globals\.ts|^canvas2d\.ts)$/const [mode = "check", dirArg] = process.argv.slice(2)if (mode !== "gen" && mode !== "check") throw new Error("usage: sdk.ts gen|check [DIR]")const out = path.resolve(dirArg ?? path.join(ROOT, "docs/manual/reference/sdk"))diff --git a/tools/skills.sh b/tools/skills.shindex 6727ba56..3825073b 100755--- a/tools/skills.sh+++ b/tools/skills.sh@@ -225,7 +225,7 @@ gen_sdk() {bun -e 'const root = process.argv[1], dir = root + "/sdk/raea/src"const t = new Bun.Transpiler({ loader: "tsx" })- const skip = /(\.gen\.ts|^test\.tsx|^native-calls\.ts|^prelude\.ts|^pure\.ts)$/+ const skip = /(\.gen\.ts|^test\.tsx|^native-calls\.ts|^prelude\.ts|^pure\.ts|^frame-globals\.ts|^canvas2d\.ts)$/const files = [...new Bun.Glob("*.{ts,tsx}").scanSync(dir)].filter((f) => !skip.test(f)).sort()const rows = files.map((f) => ({ entry: f.startsWith("index.") ? "raea" : "raea/" + f.replace(/\.tsx?$/, ""), file: "sdk/raea/src/" + f, names: t.scan(require("fs").readFileSync(dir + "/" + f, "utf8")).exports.filter((n) => n !== "default").sort() }))console.log(JSON.stringify(rows.sort((a, b) => (a.entry === "raea" ? -1 : b.entry === "raea" ? 1 : a.entry.localeCompare(b.entry)))))