Skip to content

armgit / raea

Public Imported from GitHub
0

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.

LR2: every host that runs a composition answers its layout reads. Live play (preview, raea play, the app's stage, an exported game) answers from its live page, synced mid-settle as a render's is. Live play's lite runtime set no refs (a ref was null, a canvas drawn through one drew nothing): its hosts now keep bevy-react's BevyElement, BevyCanvasElement and BevyTextNode linked as React's tree is and set and clear refs, and entry_lite installs canvas2d and the DOM reads. raea world answers from the page it lays its frames out with; a baked timeline (raea play --baked) refuses a read plainly instead of baking it as 0. #54's repro played live puts "here" at x 342 (x 0 before); every layout-reads probe played live is its render's frame (SSIM 1.000), and the games replay (pong, platformer, lite against React) stays 1.000. A read costs a live frame about 1.5 ms (step p50 0.4 -> 1.9 ms, one read a frame on a 40-line page)

shinyobjectz53d5f948885f
diff --git a/docs/layout-reads.feature b/docs/layout-reads.feature
index 02cf1e3a..461cdb77 100644
--- a/docs/layout-reads.feature
+++ b/docs/layout-reads.feature
@@ -112,6 +112,7 @@ Feature: Layout reads: a composition measures its text and layout as Chrome does
Chrome (Inter at 64 px). geometry prints each value it read, and all match Chrome's words.
@needs:LR1
+ @done
Scenario: LR2. Every host that runs a composition answers
Then each host below answers LR1's call, or states plainly why it can't:
| host | where |
@@ -123,6 +124,25 @@ Feature: Layout reads: a composition measures its text and layout as Chrome does
| the portable bundle | the iPhone's player |
| an exported game | raea-app-game's player |
And in live play a read costs at most one frame's wait, which is stated with its measurement
+ And 11-12, built:
+ - Render and export, a bundle drawn by render_bundle (the portable bundle's player) and the fed render answer
+ from their frame's page (LR1). The sound pass and the 3D rows' pre-pass draw no page and answer with no
+ boxes (layout::nothing_drawn).
+ - Live play (preview, raea play, the app's stage and an exported game, all runtime/live step_inner) answers
+ from its live page: settle_with syncs the page to the World mid-settle, lays it out and snapshots it.
+ - Live play runs on raea's lite runtime (sdk/react/js/lite), which set no refs, so a ref was null there and
+ a canvas drawn through one drew nothing. Lite's hosts now keep bevy-react's nodes (BevyElement,
+ BevyCanvasElement, BevyTextNode) linked as React's tree is, and set a ref when its host is made and clear it
+ when it's dropped. entry_lite installs canvas2d and the DOM reads as React's entry does.
+ - raea world answers from the page it lays its frames out with (made for a read even under --no-layout).
+ - A baked timeline (raea play --baked) lays no page out while it bakes: a read is refused with "a baked timeline
+ (raea play --baked; play it without --baked) lays no page out", not baked as 0.
+ - #54's repro played live puts "here" at x 342, as the render and Chrome do (x 0 before). Every probe
+ (geometry, tree, document, measure, observe, hold) played live is the render's frame (SSIM 1.000), and
+ sdk/react/bench/games/replay.sh (pong, platformer: lite against React) stays at SSIM 1.000.
+ - The cost, measured on a 640x720 page of 40 lines, one getBoundingClientRect a frame at 60 fps (raea play
+ --offscreen --no-vsync, 5 s, twice): a frame's step p50 0.39-0.41 ms without the read, 1.8-2.0 ms with it;
+ work p50 3.8-4.2 ms against 4.3-5.0 ms. Under a tenth of a 60 fps frame.
Rule: a ref has the DOM a web component reads
diff --git a/runtime/bake/src/lib.rs b/runtime/bake/src/lib.rs
index a3d66fe3..33ea7d7c 100644
--- a/runtime/bake/src/lib.rs
+++ b/runtime/bake/src/lib.rs
@@ -205,7 +205,13 @@ pub fn runs<'a>(frames: impl IntoIterator<Item = &'a i64>) -> Vec<(i64, i64)> {
/// Frames `a..b` stepped as one range (lightspeed T3): React renders them back to back (raea-frames), with no round
/// trip to Rust between frames, and each frame's commit is applied on its own (OneBatch), `each` reading the world
/// after it. Stepped one event a frame, each frame waited on the JS thread and back: most of an incremental bake.
-pub fn step_frames(app: &mut App, a: i64, b: i64, mut each: impl FnMut(&mut App, i64) -> R<()>) -> R<()> {
+pub fn step_frames(app: &mut App, a: i64, b: i64, each: impl FnMut(&mut App, i64) -> R<()>) -> R<()> {
+ step_frames_with(app, a, b, &mut raea_runtime_react::layout::nothing_drawn(), each)
+}
+
+/// [`step_frames`], a layout read the composition makes answered by `answer` (`page.layout`, docs/layout-reads.feature
+/// LR2): a host that lays a page out answers from it, a pass that draws none with no boxes.
+pub fn step_frames_with(app: &mut App, a: i64, b: i64, answer: &mut raea_runtime_react::layout::Answer, mut each: impl FnMut(&mut App, i64) -> R<()>) -> R<()> {
if b <= a {
return Ok(());
}
@@ -214,8 +220,7 @@ pub fn step_frames(app: &mut App, a: i64, b: i64, mut each: impl FnMut(&mut App,
let mut t_each = std::time::Duration::ZERO;
app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frames", "value": {"from": a, "to": b}}));
for g in a..b {
- // a layout read gets no boxes: the frames stepped here draw no page (the 3D rows' pre-pass; docs/layout-reads.feature LR2)
- raea_runtime_react::scene::settle_with(app, Some(g), 20.0, &mut raea_runtime_react::layout::nothing_drawn())?;
+ raea_runtime_react::scene::settle_with(app, Some(g), 20.0, answer)?;
let te = std::time::Instant::now();
each(app, g)?;
t_each += te.elapsed();
@@ -242,8 +247,10 @@ fn take_ops(app: &mut App) -> Vec<String> {
/// runtime's node ids don't follow on from the range before).
fn step_range(app: &mut App, a: i64, b: i64, reset: bool) -> R<Range> {
let mut r = Range { frame_ops: Vec::with_capacity((b - a) as usize), comps: Vec::with_capacity((b - a) as usize), keys: Vec::new(), has_3d: false };
- // the render's own steps: frame numbers (not live play's {frame, input}), so the commits are a render's
- step_frames(app, a, b, |app, f| {
+ // the render's own steps: frame numbers (not live play's {frame, input}), so the commits are a render's. A bake lays
+ // no page out, so a layout read is refused, plainly, rather than baked as 0 (docs/layout-reads.feature LR2)
+ let mut answer = raea_runtime_react::layout::no_page("a baked timeline (raea play --baked; play it without --baked)");
+ step_frames_with(app, a, b, &mut answer, |app, f| {
r.comps.push(comps_of(app.world_mut()));
let ops = take_ops(app);
r.has_3d |= ops.iter().any(|j| j.contains("data-3d"));
diff --git a/runtime/bundle/src/entry.rs b/runtime/bundle/src/entry.rs
index b1414c42..134600e7 100644
--- a/runtime/bundle/src/entry.rs
+++ b/runtime/bundle/src/entry.rs
@@ -163,9 +163,19 @@ pub fn entry_lite(file: &str, o: &CompOpts) -> String {
let start = full.find("import * as M").expect("entry's imports");
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");
+ let nodes = raea_io_home::home().join("sdk/react/js/node_modules/bevy-react/src/nodes.ts");
+ let canvas = raea_io_home::home().join("sdk/react/js/node_modules/bevy-react/src/canvas.ts");
format!(
r#"import {{ frameCallbacks, pureAgain, pureFrame, pureSession, seedOf }} from "./motion/pure";
import {{ addEventListener, reset, runEventLoop }} from {bridge:?};
+// a ref has the DOM a web component reads, as under React's entry: lite's hosts keep the same nodes (sdk/react/js/lite
+// hosts.ts), and a <canvas> ref's getContext("2d") is the web's (layout-reads LR2; #55)
+import {{ canvas2d }} from "./motion/canvas2d";
+import {{ domReads }} from "./motion/dom-reads";
+import * as BevyNodes from {nodes:?};
+import {{ BevyCanvasElement }} from {canvas:?};
+canvas2d(BevyCanvasElement);
+domReads(BevyNodes as any);
import {{ renderRoot, takeRendered }} from "react";
{preamble}const LIVE: any = {{}};
let live = false;
diff --git a/runtime/live/src/lib.rs b/runtime/live/src/lib.rs
index fec648db..4d691e79 100644
--- a/runtime/live/src/lib.rs
+++ b/runtime/live/src/lib.rs
@@ -232,7 +232,15 @@ impl Live {
}
}
self.app.world().resource::<ReactOutbox>().send_raw(frame_event(f, keys, pointer, Some(self.session)));
- raea_runtime_react::scene::settle(&mut self.app, Some(f), 5.0)?;
+ // a layout read the composition makes (docs/layout-reads.feature LR2): the live page synced to the World as
+ // it is mid-settle, laid out, and its boxes; the frame's draw syncs it again with the 3D's holders. Preview,
+ // play, the app's stage and an exported game all step here
+ let (page, brand) = (&mut self.page, self.brand.as_deref());
+ raea_runtime_react::scene::settle_with(&mut self.app, Some(f), 5.0, &mut |w, q| {
+ page.sync(w, &std::collections::HashMap::new(), brand).map_err(|e| e.to_string())?;
+ page.lay_out();
+ Ok(page.layout_snapshot(q))
+ })?;
// a game's 3D: this frame's scene, as it was just computed, set on the live engine
if let Some(ls) = self.live3d.as_mut() {
let t = std::time::Instant::now();
diff --git a/runtime/world/src/lib.rs b/runtime/world/src/lib.rs
index df649e62..3b5bc9ec 100644
--- a/runtime/world/src/lib.rs
+++ b/runtime/world/src/lib.rs
@@ -81,13 +81,18 @@ fn stepped(js: &Path, tsx: &Path, ask: &Ask, words: Option<&Value>) -> R<Vec<Fac
let wanted: BTreeSet<i64> = asked.iter().copied().collect();
// and each one's next frame, for what moves (the camera's velocity)
let all: BTreeSet<i64> = wanted.iter().flat_map(|&f| [f, f + 1]).filter(|f| *f < length).collect();
- let mut page = page::Page::new(ask.layout, w, h, dir);
+ // one page for the frames' layout and for the layout reads the composition makes while they step (LR2)
+ let page = std::cell::RefCell::new(page::Page::new(ask.layout, w, h, dir));
+ let at = std::cell::Cell::new(0i64);
let mut snaps: BTreeMap<i64, Snap> = BTreeMap::new();
for (a, b) in raea_runtime_bake::runs(&all) {
- raea_runtime_bake::step_frames(&mut app, a, b, |app, f| {
+ at.set(a);
+ let mut answer = |w: &mut bevy::prelude::World, q: &str| page.borrow_mut().answer(w, at.get(), fps, q);
+ raea_runtime_bake::step_frames_with(&mut app, a, b, &mut answer, |app, f| {
+ at.set(f + 1);
let world = app.world_mut();
let scene = raea_runtime_scene::items_of(&scene_of(world));
- let (tree, laid) = if wanted.contains(&f) { (timeline::tree(world), page.laid_out(world, f, fps)) } else { (Vec::new(), None) };
+ let (tree, laid) = if wanted.contains(&f) { (timeline::tree(world), page.borrow_mut().laid_out(world, f, fps)) } else { (Vec::new(), None) };
snaps.insert(f, Snap { scene, tree, laid });
Ok(())
})?;
diff --git a/runtime/world/src/page.rs b/runtime/world/src/page.rs
index 82fab3fa..5981769a 100644
--- a/runtime/world/src/page.rs
+++ b/runtime/world/src/page.rs
@@ -22,6 +22,20 @@ impl Page {
Page { on, size: (w, h), dir: dir.to_path_buf(), page: None, failed: false }
}
+ /// A layout read the composition makes while frame `f` steps (`page.layout`, docs/layout-reads.feature LR2): the
+ /// page synced to the React World as it is mid-settle, laid out, and its boxes, as a render answers. The page is
+ /// made for the read, asked for or not.
+ pub(crate) fn answer(&mut self, react: &mut World, f: i64, fps: f64, request: &str) -> Result<String, String> {
+ if self.page.is_none() {
+ self.page = Some(raea_runtime_page::BevyPage::new(self.size.0, self.size.1, &self.dir).map_err(|e| format!("raea world couldn't make the page to answer a layout read: {e}"))?);
+ }
+ let page = self.page.as_mut().ok_or("no page")?;
+ page.at_frame(f, fps);
+ page.sync(react, &HashMap::new(), None).map_err(|e| e.to_string())?;
+ page.lay_out();
+ Ok(page.layout_snapshot(request))
+ }
+
/// Frame `f`'s page as laid out: the render manifest's frame entry ({videos, text}); None when the page isn't
/// laid out (not asked for, or it couldn't be).
pub(crate) fn laid_out(&mut self, react: &mut World, f: i64, fps: f64) -> Option<Value> {
diff --git a/sdk/react/js/lite/parts/hosts.ts b/sdk/react/js/lite/parts/hosts.ts
index 5964a5ca..ca119fcc 100644
--- a/sdk/react/js/lite/parts/hosts.ts
+++ b/sdk/react/js/lite/parts/hosts.ts
@@ -1,5 +1,8 @@
-// Host nodes made, patched and dropped.
-import { allocId, buildUpdateOp, dropHandlers, push, serializeProps } from "../../node_modules/bevy-react/src/bridge";
+// Host nodes made, patched and dropped. Each host keeps the node a ref to it holds (bevy-react's BevyElement, its
+// BevyCanvasElement for a <canvas>, a BevyTextNode for a text) linked into the tree bevy-react keeps under React, so a
+// composition played live reads its refs as it does when rendered (docs/layout-reads.feature LR2).
+import { allocId, buildUpdateOp, createCanvasElement, dropHandlers, push, serializeProps, ROOT_ID } from "../../node_modules/bevy-react/src/bridge";
+import { BevyElement, BevyTextNode, containerNode } from "../../node_modules/bevy-react/src/nodes";
import { Host, Instance, Out, Slot, same } from "./all";
function kindOf(type: string, inText: boolean) {
@@ -17,37 +20,54 @@ function ownerOf(inst: Instance | null): string {
return names;
}
+/** A ref given `node` (null to let go), a callback or an object, as React sets one. */
+function setRef(ref: any, node: unknown) {
+ if (typeof ref === "function") ref(node);
+ else if (ref && typeof ref === "object") ref.current = node;
+}
+
function create(o: Out): Host {
const id = allocId();
if (o.type === "#text") {
push(o.inText ? { op: "createTextSpan", id, text: o.text } : { op: "createText", id, text: o.text });
- return { id, type: "#text", kind: "#text", text: true, props: null, value: o.text, kids: [], slot: o.slot, out: o };
+ return { id, type: "#text", kind: "#text", text: true, props: null, value: o.text, kids: [], slot: o.slot, out: o, node: new BevyTextNode(id, o.text ?? "") };
}
const kind = kindOf(o.type, o.inText);
const props = serializeProps(id, o.props, o.type);
// the components it was rendered in, nearest first: what the feed's play stage names a picked element by
if (o.owner && props) props["data-raea-owner"] = ownerOf(o.owner);
push({ op: "create", id, kind, props, text: o.text });
- const h: Host = { id, type: o.type, kind, text: false, props: o.props, value: o.text, kids: [], slot: o.slot, out: o };
+ let node: BevyElement;
+ if (o.type === "canvas") {
+ node = createCanvasElement(id);
+ node.props = o.props;
+ } else node = new BevyElement(id, o.type, kind, o.props);
+ const h: Host = { id, type: o.type, kind, text: false, props: o.props, value: o.text, kids: [], slot: o.slot, out: o, node };
for (const k of o.kids) {
const c = create(k);
push({ op: "append", parent: id, child: c.id });
h.kids.push(c);
+ node.childNodes.push(c.node);
+ c.node.parentNode = node;
}
+ if (o.ref != null) setRef(o.ref, node);
return h;
}
function drop(h: Host) {
dropHandlers(h.id);
+ if (h.out?.ref != null) setRef(h.out.ref, null);
for (const k of h.kids) drop(k);
}
function patch(h: Host, o: Out) {
if (h.out === o) return;
+ const was = h.out;
h.out = o;
if (h.text) {
if (h.value !== o.text) push({ op: "updateText", id: h.id, text: o.text });
h.value = o.text;
+ (h.node as BevyTextNode).data = o.text ?? "";
return;
}
const op = buildUpdateOp(h.id, h.props, o.props, h.type, h.kind);
@@ -56,12 +76,18 @@ function patch(h: Host, o: Out) {
else if (o.text === undefined && h.value !== undefined && h.type === "text") push({ op: "updateText", id: h.id, text: "" });
h.value = o.text;
h.props = o.props;
- h.kids = children(h.id, h.kids, o.kids);
+ (h.node as BevyElement).props = o.props;
+ h.kids = children(h.id, h.kids, o.kids, h.node as BevyElement);
+ // a ref that changed lets the old one go and gives the new one the node, as React does
+ if (was?.ref !== o.ref) {
+ if (was?.ref != null) setRef(was.ref, null);
+ if (o.ref != null) setRef(o.ref, h.node);
+ }
}
/** A host parent's children matched to what the render yields: same place and type kept (patched), the rest made or
- * removed, and moved where their order changed. */
-export function children(parent: number, old: Host[], next: Out[]): Host[] {
+ * removed, and moved where their order changed. `node` is the parent's node, whose children follow. */
+export function children(parent: number, old: Host[], next: Out[], node: BevyElement = containerNode(ROOT_ID)): Host[] {
// the usual frame: the same places in the same order, each patched where it is (no maps, nothing moves)
if (old.length === next.length) {
let same = true;
@@ -94,8 +120,12 @@ export function children(parent: number, old: Host[], next: Out[]): Host[] {
if (!kept.has(h)) {
push({ op: "remove", parent, child: h.id });
drop(h);
+ if (h.node.parentNode === node) h.node.parentNode = null;
}
}
+ // the parent's node holds them in their new order
+ node.childNodes = out.map((h) => h.node);
+ for (const h of out) h.node.parentNode = node;
// order: walk from the end, each one in place before the next (only those out of place move)
const pos = new Map<Host, number>();
old.forEach((h, i) => kept.has(h) && pos.set(h, i));
diff --git a/sdk/react/js/lite/parts/render.ts b/sdk/react/js/lite/parts/render.ts
index 6a109df2..72f40a90 100644
--- a/sdk/react/js/lite/parts/render.ts
+++ b/sdk/react/js/lite/parts/render.ts
@@ -113,7 +113,7 @@ export function render(node: any, parent: Instance, slot: Slot, out: Out[], inTe
// an element with no children shares one empty list (each frame made one for every leaf)
const kids: Out[] = inline || c === undefined || c === null ? EMPTY : [];
if (kids !== EMPTY) render(c, parent, inner(slot), kids, inText || childText);
- const o: Out = { slot, type: t, props: node.props, kids, inText, text: inline ? String(c) : undefined, owner: parent };
+ const o: Out = { slot, type: t, props: node.props, kids, inText, text: inline ? String(c) : undefined, owner: parent, ref: node.ref };
out.push(o);
if (S.components === before) {
node._o = o;
diff --git a/sdk/react/js/lite/parts/slots.ts b/sdk/react/js/lite/parts/slots.ts
index 1dc5c610..b6f14728 100644
--- a/sdk/react/js/lite/parts/slots.ts
+++ b/sdk/react/js/lite/parts/slots.ts
@@ -1,5 +1,6 @@
// Host nodes, places in the tree, the codes rendered, and Z3's bailout.
import { Context, Instance, S } from "./all";
+import type { BevyNode } from "../../node_modules/bevy-react/src/nodes";
// ---- host nodes
@@ -15,10 +16,13 @@ export interface Host {
slot: Slot;
/** the output it was last made or patched from: the same one again (a reused component's) changes nothing under it */
out?: Out;
+ /** what a ref to it holds, kept in the tree bevy-react keeps (its nodes.ts): the DOM reads a composition makes on a ref
+ * (sdk/raea dom-*.ts) walk it, as they do under React (docs/layout-reads.feature LR2) */
+ node: BevyNode;
}
/** What a render yields: host elements and texts, in order, under one host parent. */
-export type Out = { slot: Slot; type: string; props: any; text?: string; kids: Out[]; inText: boolean; owner?: Instance };
+export type Out = { slot: Slot; type: string; props: any; text?: string; kids: Out[]; inText: boolean; owner?: Instance; ref?: any };
/** The children of an output with none: shared, never written (children() maps into a new list) */
export const EMPTY: Out[] = Object.freeze([]) as unknown as Out[];