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
LR0: bench/layout-reads, compositions that measure their text and layout against headless Chrome: check.sh runs a corpus (modules exporting Comp, conf and props) at its first, middle and last frames in raea and in Chrome (React DOM in raea's Clock, mounted once its fonts are in), and compare.jq pairs their text runs by words (raea's manifest against boxes.ts, made the same way), box and ink within 1 px. probes/ is raea's own corpus, #54's repro first ("here" at x 0 where Chrome puts it at 342); snapcn's 33 run through the private tree's adapter. The baseline, recorded in docs/layout-reads.feature: 3 of snapcn's 33 pass (all hold-only); 13 of the 27 that measure throw and the rest drift up to 87 px
shinyobjectzfc7bfa3a0ce6
diff --git a/bench/layout-reads/.gitignore b/bench/layout-reads/.gitignorenew file mode 100644index 00000000..7f0c07e5--- /dev/null+++ b/bench/layout-reads/.gitignore@@ -0,0 +1,3 @@+# the entries check.sh makes beside each module of a corpus+lr/+*.raea.tsxdiff --git a/bench/layout-reads/boxes.ts b/bench/layout-reads/boxes.tsnew file mode 100644index 00000000..cd0e2a3f--- /dev/null+++ b/bench/layout-reads/boxes.ts@@ -0,0 +1,53 @@+// The page's text runs in Chrome, made the way raea's render manifest makes them (engine/page/src/motion/manifest.rs),+// so the two can be compared run by run. A run is the words of the text nodes owned by one element: the nearest+// ancestor that isn't inline and has a box. Its box is that element's bounding rect, and its ink spans where its+// letters are. Text under opacity 0.01 or less is skipped, as the manifest skips it.+export type Run = { text: string; box: number[]; ink?: number[] };++const r = (v: number) => Math.round(v * 10) / 10;++function alpha(el: Element | null): number {+ let a = 1;+ for (let e = el; e; e = e.parentElement) a *= Number(getComputedStyle(e).opacity);+ return a;+}++function sized(el: Element): DOMRect | null {+ const b = el.getBoundingClientRect();+ return b.width > 0 && b.height > 0 ? b : null;+}++export function runs(root: Element): Run[] {+ const owned = new Map<Element, Text[]>();+ const walk = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ for (let n = walk.nextNode() as Text | null; n; n = walk.nextNode() as Text | null) {+ if (!n.data || !n.parentElement) continue;+ if (n.parentElement.closest("style, script")) continue;+ let up: Element | null = n.parentElement;+ while (up && (getComputedStyle(up).display.startsWith("inline") || !sized(up))) up = up.parentElement;+ if (!up || alpha(n.parentElement) <= 0.01) continue;+ owned.set(up, [...(owned.get(up) ?? []), n]);+ }+ const out: Run[] = [];+ for (const [owner, texts] of owned) {+ // run_text's join: the trimmed pieces with a space between, or letters set one a span read back as their words+ const words = texts.map((t) => t.data.trim()).filter(Boolean);+ const text = words.length && words.every((w) => [...w].length === 1) ? texts.map((t) => t.data).join("").split(/\s+/).filter(Boolean).join(" ") : words.join(" ");+ const b = sized(owner);+ if (!text || !b) continue;+ let x0 = Infinity, x1 = -Infinity;+ for (const t of texts) {+ const range = document.createRange();+ range.selectNodeContents(t);+ for (const q of range.getClientRects()) {+ if (q.width <= 0) continue;+ x0 = Math.min(x0, q.left);+ x1 = Math.max(x1, q.right);+ }+ }+ const run: Run = { text, box: [r(b.x), r(b.y), r(b.width), r(b.height)] };+ if (x1 > x0) run.ink = [r(x0), r(b.y), r(x1 - x0), r(b.height)];+ out.push(run);+ }+ return out;+}diff --git a/bench/layout-reads/check.sh b/bench/layout-reads/check.shnew file mode 100755index 00000000..efb355f9--- /dev/null+++ b/bench/layout-reads/check.sh@@ -0,0 +1,126 @@+#!/bin/bash+# Layout reads against Chrome (docs/layout-reads.feature LR0, #54): compositions that measure their text and layout,+# rendered by raea and by headless Chrome at their first, middle and last frames.+# - A corpus is a folder of modules, each exporting `Comp` (the component), `conf` ({ width, height, fps,+# durationInFrames }) and `props`. Its list.txt names the ones to run (the first word of each line), else every+# .tsx. Each gets two entries made beside it: NAME.raea.tsx for raea, lr/NAME.chrome.tsx for Chrome. The default corpus is probes/, raea's own: each reads one part of the DOM a web component reads. Another is+# named by LAYOUT_READS_CORPUS; Chrome resolves its imports through the nearest tsconfig.json above it.+# - raea renders each with `raea render --at`. Its manifest's text runs are the words, box and ink as raea laid them out.+# - Chrome runs the same module under React DOM, in raea's Clock at the same frame, mounted once the fonts it asked+# for are in, and boxes.ts lists its text runs the way the manifest does.+# - compare.jq pairs the runs by their words. A frame passes when every run pairs, and box and ink are within 1 px.+# - The frames' dissimilarity (1 - SSIM, ImageMagick 7's SSIM metric) is printed too, for information.+# A composition passes when raea renders it without throwing, and all three frames pass.+# bench/layout-reads/check.sh [NAME ...] (RAEA_BIN: the raea to run, default target/release/raea;+# KEEP=DIR keeps the frames and logs there)+# Prints one line per composition, then the count. Exits 1 when one fails.+cd "$(dirname "$0")/../.." || exit 2+RAEA=$PWD+BENCH=$RAEA/bench/layout-reads+BIN=${RAEA_BIN:-$RAEA/target/release/raea}+C=$(cd "${LAYOUT_READS_CORPUS:-$BENCH/probes}" && pwd) || exit 2+export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0+for t in bun jq magick python3; do command -v $t > /dev/null || { echo "layout-reads: needs $t" >&2; exit 2; }; done+CH=$(bash "$RAEA/sdk/ui/parity/chrome.sh") || exit 2++# the corpus's tsconfig (the nearest above it), and Chrome's: its paths, raea's SDK paths made absolute, and one React+TS=$C+while [ "$TS" != / ] && [ ! -f "$TS/tsconfig.json" ]; do TS=$(dirname "$TS"); done+L=$C/lr+mkdir -p "$L"+jq -n --slurpfile base "$RAEA/sdk/tsconfig.base.json" --arg sdk "$RAEA/sdk" --arg root "$TS" \+ --argjson own "$([ -f "$TS/tsconfig.json" ] && jq -c '.compilerOptions.paths // {}' "$TS/tsconfig.json" || echo '{}')" '+ {compilerOptions: {jsx: "react-jsx", module: "esnext", target: "es2022", moduleResolution: "bundler", baseUrl: $root,+ paths: (([$base[0].compilerOptions.paths | to_entries[] | select(.key | test("^react") | not)+ | .value |= map($sdk + "/" + ltrimstr("./"))] | from_entries) + $own+ # each SDK package has its own node_modules/react, and two copies break hooks+ + ({"react": "react/index.js", "react/jsx-runtime": "react/jsx-runtime.js", "react/jsx-dev-runtime": "react/jsx-dev-runtime.js",+ "react-dom": "react-dom/index.js", "react-dom/client": "react-dom/client.js", "scheduler": "scheduler/index.js"}+ | map_values([$sdk + "/raea/node_modules/" + .])))}}' > "$L/tsconfig.chrome.json" || exit 2++names=("$@")+if [ ${#names[@]} -eq 0 ]; then+ if [ -f "$C/list.txt" ]; then+ while read -r n _; do names+=("$n"); done < <(grep -vE '^(#|$)' "$C/list.txt")+ else+ for f in "$C"/*.tsx; do case $f in *.raea.tsx) ;; *) names+=("$(basename "$f" .tsx)") ;; esac; done+ fi+fi++O=${KEEP:-$(mktemp -d "${TMPDIR:-/tmp}/raea-layout-reads.XXXXXX")}+mkdir -p "$O"+PORT=$((20000 + RANDOM % 20000))+python3 -m http.server $PORT --bind 127.0.0.1 --directory "$C" > /dev/null 2>&1 &+SRV=$!+if [ -n "${KEEP:-}" ]; then trap 'kill $SRV 2> /dev/null' EXIT; else trap 'kill $SRV 2> /dev/null; rm -rf "$O"' EXIT; fi++pass=0 fail=0+for n in "${names[@]}"; do+ [ -f "$C/$n.tsx" ] || { echo "$n FAIL no $n.tsx in the corpus"; fail=$((fail + 1)); continue; }+ D=$O/$n && rm -rf "$D" && mkdir -p "$D"+ # raea's entry beside the module (raea resolves an edit's imports through the tsconfig of its own folder)+ cat > "$C/$n.raea.tsx" <<EOF+import { Composition, registerRoot } from "raea";+import { Comp, conf, props } from "./$n";+const Main = () => <Comp {...props} />;+registerRoot(() => <Composition id="$n" component={Main} {...conf} />);+EOF+ cat > "$L/$n.chrome.tsx" <<EOF+import { createRoot } from "react-dom/client";+import { Clock } from "raea/clock";+import { Comp, conf, props } from "../$n";+import { runs } from "$BENCH/boxes";+const [frame, dump] = location.hash.slice(1).split(",");+document.body.style.margin = "0";+const el = document.getElementById("root")!;+el.style.cssText = \`position:relative;width:\${conf.width}px;height:\${conf.height}px;overflow:hidden\`;+// mounted once the fonts it asked for (loadFont's stylesheets) are in, as a render holds for them+const sheets = [...document.querySelectorAll<HTMLLinkElement>("link[rel=stylesheet]")].map((l) => (l.sheet ? Promise.resolve() : new Promise((ok) => { l.onload = l.onerror = ok; })));+await Promise.all(sheets);+await Promise.all([...document.fonts].map((f) => f.load().catch(() => {})));+createRoot(el).render(<Clock frame={Number(frame)} {...conf}><Comp {...props} /></Clock>);+if (dump) document.fonts.ready.then(() => setTimeout(() => {+ const s = document.createElement("script");+ s.type = "application/json";+ s.id = "lr-runs";+ s.textContent = JSON.stringify(runs(el));+ document.body.appendChild(s);+}, 1000));+EOF+ # its size and length, from frame 0's render+ (cd "$C" && "$BIN" render "$n.raea.tsx" --at 0 -o "$D/first/" --manifest "$D/first.json") > "$D/first.log" 2>&1+ read -r width height dur < <(jq -r '[.width, .height, .length] | @tsv' "$D/first.json" 2> /dev/null)+ if [ -z "$dur" ]; then+ echo "$n FAIL raea: $(grep -m1 -E 'threw|Error:|panicked|REFUSED' "$D/first.log" | sed -E 's/\x1b\[[0-9;]*m//g' | cut -c1-200)"+ fail=$((fail + 1)); continue+ fi+ frames=(0 $((dur / 2)) $((dur - 1)))+ (cd "$C" && RUST_LOG=info "$BIN" render "$n.raea.tsx" --at "$(IFS=,; echo "${frames[*]}")" -o "$D/raea/" --manifest "$D/manifest.json") > "$D/raea.log" 2>&1+ rr=$?+ threw=$(grep -m1 -E 'threw|Error:|panicked|REFUSED' "$D/raea.log" | sed -E 's/\x1b\[[0-9;]*m//g' | cut -c1-200)+ (cd "$L" && bun build "$n.chrome.tsx" --tsconfig-override tsconfig.chrome.json --target browser --outfile "$n.js" \+ --define 'process.env.NODE_ENV="production"') > "$D/bun.log" 2>&1 || { echo "$n FAIL Chrome's bundle: $(grep -m1 -i error "$D/bun.log" | cut -c1-150)"; fail=$((fail + 1)); continue; }+ printf '<!doctype html><meta charset=utf-8><body style="background:#000"><div id=root></div><script type=module src="/lr/%s.js"></script>' "$n" > "$L/$n.html"+ line="" ok=1+ [ $rr = 0 ] && [ -z "$threw" ] || ok=0+ for i in 0 1 2; do+ f=${frames[$i]}+ url="http://127.0.0.1:$PORT/lr/$n.html"+ "$CH" --headless --hide-scrollbars --window-size="$width,$height" --virtual-time-budget=8000 --screenshot="$D/chrome-$f.png" "$url#$f" > /dev/null 2>&1+ "$CH" --headless --hide-scrollbars --window-size="$width,$height" --virtual-time-budget=8000 --dump-dom "$url#$f,dump" 2> /dev/null \+ | sed -n 's/.*<script type="application\/json" id="lr-runs">\(.*\)<\/script>.*/\1/p' > "$D/chrome-$f.json"+ r=$D/raea/frame-0000$i.png+ if [ $rr != 0 ] || [ ! -f "$r" ]; then line="$line @$f no frame"; ok=0; continue; fi+ [ -s "$D/chrome-$f.json" ] || { line="$line @$f no Chrome runs"; ok=0; continue; }+ cmp=$(jq -c -n --slurpfile m "$D/manifest.json" --slurpfile c "$D/chrome-$f.json" --argjson i $i \+ "\$m[0].frames[\$i].text as \$r | \$c[0] as \$c | $(cat "$BENCH/compare.jq")")+ echo "$cmp" > "$D/compare-$f.json"+ dssim=$(magick compare -metric SSIM <(magick "$r" -background black -alpha remove png:-) <(magick "$D/chrome-$f.png" -background black -alpha remove png:-) null: 2>&1 | grep -oE '\(([0-9.e-]+)\)' | tr -d '()')+ read -r paired alone box ink < <(echo "$cmp" | jq -r '[.paired, (.raea_only + .chrome_only | length), (.box * 10 | round / 10), (.ink * 10 | round / 10)] | @tsv')+ if [ "$alone" = 0 ] && awk "BEGIN { exit !($box <= 1 && $ink <= 1) }"; then mark=ok; else mark=off; ok=0; fi+ line="$line @$f $mark runs $paired+$alone box $box ink $ink dssim ${dssim:-?}"+ done+ if [ $ok = 1 ]; then pass=$((pass + 1)); echo "$n PASS$line"; else fail=$((fail + 1)); echo "$n FAIL$line${threw:+ $threw}"; fi+done+echo "layout-reads: $pass passed, $fail failed (of ${#names[@]})"+[ $fail = 0 ]diff --git a/bench/layout-reads/compare.jq b/bench/layout-reads/compare.jqnew file mode 100644index 00000000..9f092c99--- /dev/null+++ b/bench/layout-reads/compare.jq@@ -0,0 +1,19 @@+# One frame's text runs, raea's ($r, the render manifest's) against Chrome's ($c, boxes.ts): each raea run is paired+# with the first unpaired Chrome run of the same words, in order. Says how many paired, the words each side has alone,+# and the largest differences in px: box (x, y, width, height) and ink (x and width).+def gap(a; b; at): [at[] | ((a[.] // 0) - (b[.] // 0)) | fabs] | max // 0;+reduce $r[] as $x ({used: [], pairs: [], alone: []};+ . as $s+ | ([$c | to_entries[] | select(.value.text == $x.text) | .key | select(. as $k | $s.used | any(.[]; . == $k) | not)]) as $k+ | if ($k | length) > 0 then+ .used += [$k[0]]+ | .pairs += [{text: $x.text, box: gap($x.box; $c[$k[0]].box; [0, 1, 2, 3]),+ ink: (if $x.ink and $c[$k[0]].ink then gap($x.ink; $c[$k[0]].ink; [0, 2]) else 0 end)}]+ else .alone += [$x.text] end)+| . as $s+| {paired: ($s.pairs | length),+ raea_only: $s.alone,+ chrome_only: [$c | to_entries[] | select(.key as $k | $s.used | any(.[]; . == $k) | not) | .value.text],+ box: ([$s.pairs[].box] | max // 0),+ ink: ([$s.pairs[].ink] | max // 0),+ worst: (($s.pairs | max_by([.box, .ink] | max)) // null)}diff --git a/bench/layout-reads/probes/repro.tsx b/bench/layout-reads/probes/repro.tsxnew file mode 100644index 00000000..068308e6--- /dev/null+++ b/bench/layout-reads/probes/repro.tsx@@ -0,0 +1,27 @@+// #54's repro as a probe (docs/layout-reads.feature LR0, LR3): a span's offsetWidth, read in an effect, places the+// word under it. In Chrome "Hello world" at 64 px is 335 px wide, so "here" starts at x 335; with no width to read it+// starts at 0.+import { AbsoluteFill } from "raea";+import { loadFont } from "raea/text";+import { useEffect, useRef, useState } from "react";++const { fontFamily } = loadFont("Inter");++export const conf = { width: 640, height: 240, fps: 30, durationInFrames: 3 };+export const props = {};++export function Comp() {+ const ref = useRef<HTMLSpanElement>(null);+ const [w, setW] = useState(0);+ useEffect(() => setW(Number(ref.current?.offsetWidth) || 0), []);+ return (+ <AbsoluteFill style={{ background: "#fff", color: "#111", fontFamily }}>+ <div style={{ position: "absolute", top: 0, left: 0 }}>+ <span ref={ref} style={{ fontSize: 64 }}>+ Hello world+ </span>+ </div>+ <div style={{ position: "absolute", top: 120, left: w, fontSize: 32 }}>here</div>+ </AbsoluteFill>+ );+}diff --git a/docs/layout-reads.feature b/docs/layout-reads.featureindex 4152934f..cb8874ee 100644--- a/docs/layout-reads.feature+++ b/docs/layout-reads.feature@@ -43,15 +43,38 @@ Feature: Layout reads: a composition measures its text and layout as Chrome doesRule: it is measured against Chrome from the start+ @doneScenario: LR0. A harness runs snapcn's measuring components in raea and in Chrome- Given bench/layout-reads holds snapcn's 27 measuring components (MIT, with its licence) and #54's repro- Then each one renders in raea and in headless Chrome- And for each it records whether it threw, the numbers it measured (logged under a "measure" tag), and its- elements' boxes on frames 0, mid and last- And it prints one line per component (pass, or what differs and by how much), and exits 1 on a failure- And the first run is the baseline, recorded here: what throws and what drifts- And the bar: nothing throws, a measured number is within 0.5 px of Chrome's, and a box within 1 px; a gap that- remains is stated per component, with its cause+ Given bench/layout-reads/check.sh runs a corpus: a folder of modules each exporting Comp, conf and props+ And its own corpus, bench/layout-reads/probes, is raea's: a composition per DOM read, #54's repro first+ And snapcn's components (MIT, pinned at 18b973d7) are a corpus the private tree's adapter makes, pointing their+ imports of the package they're written for at raea's own API, a name the public tree doesn't hold+ Then each composition renders at its first, middle and last frames, in raea (`raea render --at`, with its+ manifest) and in headless Chrome (React DOM in raea's Clock, Chrome for Testing pinned by+ sdk/ui/parity/chrome.sh, mounted once its fonts are in)+ And compare.jq pairs the text runs by their words: raea's from the render manifest, Chrome's from boxes.ts,+ which makes runs the way the manifest does+ And a frame passes when every run pairs and each run's box and ink are within 1 px of Chrome's; a component+ passes when it renders without throwing and all three frames pass. 1 - SSIM of the two frames is printed too,+ for information+ And snapcn's list holds 33 components: the 27 that measure, and 6 that only hold a frame (LR9)+ And the repro probe fails today as #54 says: "here" sits at x 0, where Chrome puts it at 342+ And 11-12, the baseline (raea from the 11-12 tree, before any LR work), 3 of 33 pass:+ | outcome | components |+ | throws: no `document` | bloom-lockup, hello-zoom, sky-lockup, spec-sweep, title-sweep |+ | throws: refs have no DOM | karaoke-captions, word-captions (getBoundingClientRect), text-reveal (NaN |+ | | from offsetWidth), text-rewrite (querySelectorAll), type-morph (children), |+ | | search-typing (style) |+ | throws: canvas | orb-swarm (putImageData) |+ | panicked | text-build, text-swell: the black-frame warning read a text node's box |+ | | (559d8274e, #96), fixed on its own lane. Both now render, and drift |+ | drifts | announce-title (to 72 px), block-wordmark, capture-reveal, check-cycle, |+ | | drop-line, font-shuffle, portal-intro (13.5), prompt-send (87), punch-lines |+ | | (30), status-cycle, text-select, word-flip (37), word-gather (16) |+ | hold only, drift | card-rail (161), hero-launch (5), wordmark-cut (47) |+ | hold only, pass | channel-thread, logo-collapse, pulsing-border |+ And "drifts" with no number means raea's words have no box of their own and fall to an ancestor's (check-cycle's+ all go to the frame's), or are missing from raea's frameRule: a read gets the layout that draws the frame, synchronously@@ -121,6 +144,8 @@ Feature: Layout reads: a composition measures its text and layout as Chrome doesshaped from the font files the page draws with, through a synchronous native callAnd a composition's <canvas> ref measures the same way, so canvas text no longer depends on the `fonts` event'sestimates+ And the 2D context has putImageData and getImageData that read back what it drew (orb-swarm throws without+ putImageData)And with the same font, the width is within 0.5 px of Chrome's@needs:LR1@@ -128,7 +153,8 @@ Feature: Layout reads: a composition measures its text and layout as Chrome doesThen document.fonts has ready, load(font) and check(font). ready and load resolve once the faces the compositionasked for (loadFont, @font-face, packaged fonts) are in the pageAnd document has body, documentElement, getElementById, querySelector and querySelectorAll over the- composition's tree, plus createElement and createTextNode+ composition's tree, plus createElement, createTextNode and createRange (a Range's getBoundingClientRect and+ getClientRects over text: search-typing places its caret by one)And an element made with createElement and appended into the composition is laid out and measurable, thendrawn or removed as in Chrome. Components measure that way: they append a hidden copy, read it, and remove itAnd window has innerWidth, innerHeight and devicePixelRatio for the composition's size, and getComputedStyle