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
#33: a panic as a frame draws ends the render with an error naming the frame and the panic, and keeps the frames drawn before it. Each frame loop catches a panic in its drawing (raea_gpu_device::check::frame_caught, or around the pipelined engine's run, which names the newest frame sent) and returns it as an error, "raea panicked drawing frame N: <message>"; the panic hook still prints it and where it was, and the crash log keeps it. On that error, or any other mid-render, the direct path drains the frames in flight to the encoder, the fed path finishes the file without sound, the engine path finishes its encoder, and hashes so far are written, so the file holds every frame before N and the error says how many and where ("no frame was written" when none). Exit 1 now, not a panic's 101. RAEA_PANIC_FAULT=N (docs/settings.md) panics as frame N draws, for the check: bench/frame-panic/check.sh renders an HTML page to .mp4 and .txt, a 2D page to .mp4 and .txt, and a 3D scene to .mp4 and a PNG folder at RAEA_PANIC_FAULT=100, and each exits 1 naming frame 100 with exactly 100 frames kept; without the fault the same renders give all their frames. Speed, two builds of this tree with and without the change, five runs each alternating (the machine was busy: medians), to .mp4: a 2D page 427 fps before, 435 after; #20's HTML page 214 before, 235 after; a 3D scene 71.7 before, 71.5 after (a frame catch costs nothing until something panics).
shinyobjectz1eb646f7b909
diff --git a/bench/frame-panic/check.sh b/bench/frame-panic/check.shnew file mode 100755index 00000000..f23a2314--- /dev/null+++ b/bench/frame-panic/check.sh@@ -0,0 +1,34 @@+#!/bin/bash+# #33: a render that panics as a frame draws ends with an error naming the frame and the panic, and keeps the frames+# drawn before it. RAEA_PANIC_FAULT=100 panics as frame 100 draws; each render below must exit 1 (not a panic's 101),+# say "panicked drawing frame 100", and leave 100 frames: an HTML page (bench/html-repeat) to .mp4 and .txt, the 2D page+# here to .mp4 and .txt, and a 3D scene (bench/at-3d) to .mp4 and a folder of PNGs. Exits 1 on a failure.+# bench/frame-panic/check.sh (RAEA_BIN: the raea to run, default target/release/raea)+cd "$(dirname "$0")/../.." || exit 2+BIN=${RAEA_BIN:-$PWD/target/release/raea}+export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0 RAEA_PANIC_FAULT=100+OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-frame-panic.XXXXXX")+trap 'rm -rf "$OUT"' EXIT+frames() {+ if [ -d "$1" ]; then ls "$1" | grep -c '\.png$'+ elif [[ $1 == *.txt ]]; then wc -l < "$1" | tr -d ' '+ elif [ -f "$1" ]; then ffprobe -v error -count_frames -show_entries stream=nb_read_frames -of csv=p=0 "$1"+ else echo 0; fi+}+status=0+while read -r src out; do+ "$BIN" render "$src" -o "$OUT/$out" > "$OUT/$out.log" 2>&1+ rc=$?+ said=$(grep -c "panicked drawing frame 100: RAEA_PANIC_FAULT" "$OUT/$out.log")+ n=$(frames "$OUT/$out")+ if [ "$rc" = 1 ] && [ "$said" -ge 1 ] && [ "$n" = 100 ]; then echo "PASS $src -> $out: exit 1, frame 100 named, 100 frames kept"+ else echo "FAIL $src -> $out: exit $rc, frame named ${said}x, $n frames kept (want 1, 1, 100)"; status=1; fi+done <<LIST+bench/html-repeat/index.html html.mp4+bench/html-repeat/index.html html.txt+bench/frame-panic/page.tsx page.mp4+bench/frame-panic/page.tsx page.txt+bench/at-3d/scene.tsx scene.mp4+bench/at-3d/scene.tsx scene+LIST+exit $statusdiff --git a/bench/frame-panic/page.tsx b/bench/frame-panic/page.tsxnew file mode 100644index 00000000..975ecf41--- /dev/null+++ b/bench/frame-panic/page.tsx@@ -0,0 +1,12 @@+// bench/frame-panic's 2D page: a box crossing the frame over 150 frames, drawn by the page engine alone+import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";+function Page() {+ const f = useCurrentFrame();+ return (+ <AbsoluteFill style={{ background: "#0f172a" }}>+ <div style={{ position: "absolute", left: 40 + f * 7, top: 300, width: 160, height: 120, borderRadius: 16, background: "#38bdf8" }} />+ <div style={{ position: "absolute", left: 60, top: 80, color: "#f8fafc", fontSize: 48 }}>frame {f}</div>+ </AbsoluteFill>+ );+}+registerRoot(() => <Composition id="page" component={Page} width={1280} height={720} fps={30} durationInFrames={150} />);diff --git a/docs/settings.md b/docs/settings.mdindex 58d43afd..14f7415f 100644--- a/docs/settings.md+++ b/docs/settings.md@@ -48,3 +48,4 @@ libraries (pianos, General MIDI instruments, orchestral and percussion samples,|---|---|| `RAEA_VELLO_BUMP=full` | Pages are drawn with Vello's own buffer sizes from the first frame, instead of raea's smaller ones (about 100 MB less GPU memory). A page past raea's sizes is found and drawn again at Vello's anyway, with a line on stderr, so this only saves that redraw || `RAEA_PAGE_DRAWN_CHECK=0` | Pages are drawn without checking that Vello drew them. For measuring what the check costs (about 2% in one test): a page past Vello's buffers then shows the frame before it again, or nothing |+| `RAEA_PANIC_FAULT=N` | A panic while frame N draws, for checking what a failing render keeps (bench/frame-panic). The render then ends with an error naming the frame and the panic, and keeps the frames drawn before it |diff --git a/engine/render/src/engine/output.rs b/engine/render/src/engine/output.rsindex e0262faa..99c7f6af 100644--- a/engine/render/src/engine/output.rs+++ b/engine/render/src/engine/output.rs@@ -123,6 +123,7 @@ impl Engine {pub fn frame(&mut self, f: i64) -> Result<Vec<u8>, String> {self.catch_up(f)?;self.app.world_mut().resource_mut::<Clock>().0 = f;+ raea_gpu_device::check::panic_fault(f);let want = tag_colour(f, self.app.world().resource::<Gen>().0);let mut prev: Option<Vec<u8>> = None;for i in 0..240 {@@ -130,9 +131,7 @@ impl Engine {eprintln!("trace frame {f} update {i}");}self.step();- if let Some(e) = self.app.world_mut().resource_mut::<Error>().0.take() {- return Err(e);- }+ self.app.world_mut().resource_mut::<Error>().0.take().map_or(Ok(()), Err)?;let got = std::mem::take(&mut self.app.world_mut().resource_mut::<Out>().0);// the first frame after a load: readbacks the warm-up queued carry its tag but can predate parts that take a// few updates to show (a spot light's first frames drew without it), so the first few updates' are dropped@@ -198,7 +197,8 @@ impl Engine {if many {self.warm = false;}- self.frames_run(r, &mut sink)?;+ // a panic drawing a frame an error naming the newest frame sent, the one drawing (#33)+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.frames_run(r, &mut sink))).map_err(|p| raea_gpu_device::check::panicked(p, self.app.world().resource::<Clock>().0))??;}Ok(())}@@ -219,6 +219,7 @@ impl Engine {if sent < list.len() && sent < next + 3 {self.catch_up(list[sent])?;self.app.world_mut().resource_mut::<Clock>().0 = list[sent];+ raea_gpu_device::check::panic_fault(list[sent]);sent += 1;}if std::env::var_os("RAEA_TRACE").is_some() {@@ -232,9 +233,7 @@ impl Engine {let dev = self.app.sub_app(bevy::render::RenderApp).world().resource::<bevy::render::renderer::RenderDevice>().clone();let _ = dev.wgpu_device().poll(bevy::render::render_resource::PollType::wait_indefinitely());}- if let Some(e) = self.app.world_mut().resource_mut::<Error>().0.take() {- return Err(e);- }+ self.app.world_mut().resource_mut::<Error>().0.take().map_or(Ok(()), Err)?;for d in std::mem::take(&mut self.app.world_mut().resource_mut::<Out>().0) {// only this load's frames (a motion-blur pre-step's carry generation 0)if let Some(t) = self.tag_at(&d).filter(|t| t.2 == generation) {diff --git a/gpu/device/src/check.rs b/gpu/device/src/check.rsindex d961f571..9da4342b 100644--- a/gpu/device/src/check.rs+++ b/gpu/device/src/check.rs@@ -79,6 +79,32 @@ pub fn injected(mut px: Vec<u8>, redraw: bool) -> Vec<u8> {px}+/// RAEA_PANIC_FAULT=N, the panicking-frame check (bench/frame-panic): a panic as frame N draws, as the page engine's+/// was in #24 (#33).+pub fn panic_fault(f: i64) {+ static AT: std::sync::OnceLock<Option<i64>> = std::sync::OnceLock::new();+ if *AT.get_or_init(|| std::env::var("RAEA_PANIC_FAULT").ok().and_then(|v| v.parse().ok())) == Some(f) {+ panic!("RAEA_PANIC_FAULT at frame {f}");+ }+}++/// A panic caught while frame `f` drew (`p`, catch_unwind's payload) as the render's error (#33): the frame and the+/// panic's message. The hook has printed the panic and where it was, so the render ends naming both, and its caller+/// keeps the frames it has.+pub fn panicked(p: Box<dyn std::any::Any + Send>, f: i64) -> String {+ let msg = p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_else(|| "a panic with no message".into());+ format!("raea panicked drawing frame {f}: {msg}")+}++/// `draw`, frame `f`'s drawing, with a panic in it as the render's error (`panicked`) rather than the process's end.+pub fn frame_caught<T>(f: i64, draw: impl FnOnce() -> Result<T, String>) -> Result<T, String> {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ panic_fault(f);+ draw()+ }))+ .map_err(|p| panicked(p, f))?+}+static SCENE_BLACK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);/// Whether this render's scene is known to draw black: a black frame of it was drawn black twice and the GPU passed itsdiff --git a/runtime/encode/src/render.rs b/runtime/encode/src/render.rsindex e05c451a..879744cb 100644--- a/runtime/encode/src/render.rs+++ b/runtime/encode/src/render.rs@@ -15,6 +15,29 @@ pub fn render(prog: &Program, rows: &[Tup], dir: &Path, out: &Path, ro: &RenderO/// textures). `prog` is the picture's program (its size, rate, length and background; no rows: the page is the/// picture), and `sound_of` the sound's, asked for once the last frame is made (the caller learns it from the frames):/// a track mixed and mastered already (the one mixer core's bounce, raea-mixer).+/// A direct render's frame `f`: to the encoder's queue, or with none (an .txt out) its NV12 hash to `lines`.+fn direct_sink(tx: Option<&std::sync::mpsc::SyncSender<Vec<u8>>>, lines: &mut Vec<String>, f: i64, px: Vec<u8>) -> Result<(), String> {+ if let Some(tx) = tx {+ return tx.send(px).map_err(|_| "the encoder stopped".to_string());+ }+ let mut hsh = 0xcbf2_9ce4_8422_2325u64;+ for b in &px {+ hsh ^= *b as u64;+ hsh = hsh.wrapping_mul(0x100_0000_01b3);+ }+ lines.push(format!("{f} {hsh:016x}"));+ Ok(())+}++/// A render that failed after `n` frames reached `out` (#33): its error, and what of it is there, so a long render that+/// fails near its end keeps what it drew and says so+fn kept_note(e: String, out: &Path, n: usize) -> String {+ match n {+ 0 => format!("{e}; no frame was written"),+ _ => format!("{e}; the {n} frames drawn before it are in {} (the render stops there)", out.display()),+ }+}+pub fn render_fed(prog: &Program,dir: &Path,@@ -57,17 +80,10 @@ pub fn render_fed(}));}let t_frames = std::time::Instant::now();+ let mut n = 0;let dt = v.render_nv12_fed(&list, feed, |f, px| {- if let Some(tx) = tx.as_ref() {- return tx.send(px).map_err(|_| "the encoder stopped".to_string());- }- let mut hsh = 0xcbf2_9ce4_8422_2325u64;- for b in &px {- hsh ^= *b as u64;- hsh = hsh.wrapping_mul(0x100_0000_01b3);- }- lines.push(format!("{f} {hsh:016x}"));- Ok(())+ n += 1;+ direct_sink(tx.as_ref(), &mut lines, f, px)});drop(tx);let sent = match dt {@@ -77,13 +93,23 @@ pub fn render_fed(let _ = mix_tx.send(mix);Some(ta.elapsed().as_secs_f64())}- _ => None,+ // a failed render's frames are finished as they are, without sound (#33)+ _ => {+ let _ = mix_tx.send(None);+ None+ }};drop(mix_tx);let joined = match enc_thread {Some(j) => Some(j.join().map_err(|_| "the encoder panicked".to_string())?),None => None,};+ if let Err(e) = dt {+ if hashes {+ let _ = std::fs::write(out, lines.join("\n") + "\n");+ }+ return Err(kept_note(e, out, n));+ }let dt = dt?;let joined = joined.transpose()?;let finish_s = joined.as_ref().map(|j| j.1).unwrap_or(0.0);@@ -209,26 +235,28 @@ pub fn render_with(prog: &Program, rows: &[Tup], dir: &Path, out: &Path, ro: &Re}));}let t_frames = std::time::Instant::now();+ let mut n = 0;let dt = v.render_nv12(&list, |f, px| {- if let Some(tx) = tx.as_ref() {- return tx.send(px).map_err(|_| "the encoder stopped".to_string());- }- let mut hsh = 0xcbf2_9ce4_8422_2325u64;- for b in &px {- hsh ^= *b as u64;- hsh = hsh.wrapping_mul(0x100_0000_01b3);- }- lines.push(format!("{f} {hsh:016x}"));- Ok(())- })- ?;+ n += 1;+ direct_sink(tx.as_ref(), &mut lines, f, px)+ });let t = std::time::Instant::now();drop(tx);let joined = match enc_thread {Some(j) => Some(j.join().map_err(|_| "the encoder panicked".to_string())??),None => None,};+ // a failed render: the encoder has finished the frames it got (#33)+ let dt = match dt {+ Ok(dt) => dt,+ Err(e) => {+ if hashes {+ let _ = std::fs::write(out, lines.join("\n") + "\n");+ }+ return Err(kept_note(e, out, n));+ }+ };// frames: until the last frame is encoded (the queue drained), without the file's finishinglet finish_s = joined.as_ref().map(|j| j.1).unwrap_or(0.0);let frames_s = t_frames.elapsed().as_secs_f64() - finish_s;@@ -268,7 +296,9 @@ pub fn render_with(prog: &Program, rows: &[Tup], dir: &Path, out: &Path, ro: &Relet keep = ro.ssim;let mut kept: Vec<(i64, Vec<u8>)> = Vec::new();let nv12 = e.nv12;- e.frames(&list, |f, px| {+ let mut n = 0;+ let drawn = e.frames(&list, |f, px| {+ n += 1;if keep && f % 30 == 0 {kept.push((f, px.clone()));}@@ -276,8 +306,11 @@ pub fn render_with(prog: &Program, rows: &[Tup], dir: &Path, out: &Path, ro: &Relet r = if nv12 { enc.push_nv12(&px, w as usize, h as usize) } else { enc.push(&px) };encode_s += t.elapsed().as_secs_f64();r- })- ?;+ });+ if let Err(e) = drawn {+ // the frames encoded so far finished as a file (#33)+ return Err(kept_note(e, &out, enc.finish(mix.as_ref()).map_or(0, |_| n)));+ }let render_s = t_all.elapsed().as_secs_f64() - encode_s;let t = std::time::Instant::now();let stats = enc.finish(mix.as_ref())?;@@ -323,7 +356,7 @@ pub fn render_with(prog: &Program, rows: &[Tup], dir: &Path, out: &Path, ro: &Re} else if out.extension().is_some_and(|x| x == "txt") {// hash-only: one line per frame, "frame fnv64-of-rgba", nothing else on disklet mut lines = Vec::new();- e.frames(&list, |f, px| {+ let drawn = e.frames(&list, |f, px| {let mut h = 0xcbf2_9ce4_8422_2325u64;for b in &px {h ^= *b as u64;@@ -331,9 +364,11 @@ pub fn render_with(prog: &Program, rows: &[Tup], dir: &Path, out: &Path, ro: &Re}lines.push(format!("{f} {h:016x}"));Ok(())- })- ?;+ });std::fs::write(&out, lines.join("\n") + "\n").map_err(|e| e.to_string())?;+ if let Err(e) = drawn {+ return Err(kept_note(e, &out, lines.len()));+ }} else {std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;let nv12 = e.nv12;@@ -354,7 +389,13 @@ pub fn render_with(prog: &Program, rows: &[Tup], dir: &Path, out: &Path, ro: &Re}px};- e.frames(&list, |f, px| save_png(&out.join(format!("frame-{f:05}.png")), &rgba_of(px), w, h))?;+ let mut n = 0;+ e.frames(&list, |f, px| {+ save_png(&out.join(format!("frame-{f:05}.png")), &rgba_of(px), w, h)?;+ n += 1;+ Ok(())+ })+ .map_err(|e| kept_note(e, &out, n))?;}eprintln!("{} ({} frames) in {:.2}s", out.display(), list.len(), t0.elapsed().as_secs_f64());Ok(())diff --git a/runtime/export/src/render.rs b/runtime/export/src/render.rsindex ae6e5af1..9b4099b5 100644--- a/runtime/export/src/render.rs+++ b/runtime/export/src/render.rs@@ -258,6 +258,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Optistd::fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;}for (i, &f) in wanted.iter().enumerate() {+ let px = raea_gpu_device::check::frame_caught(f, || { // a panic drawing it an error naming it (#33)engine_before(&app, &mut cx, f);app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frame", "value": f}));settle(&mut app, Some(f), 20.0)?;@@ -274,14 +275,13 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti}}let (px, twice) = raea_gpu_device::check::black_checked(f, px, raea_sys_page::redraw_full, || bevy_over_3d(app.world_mut(), pg, &mut cx, fps))?;- if twice {- raea_gpu_device::check::black_twice(f, pg.canary().and_then(|()| cx.scene3d.as_ref().map_or(Ok(()), |e| e.canary())))?;- }+ if twice { raea_gpu_device::check::black_twice(f, pg.canary().and_then(|()| cx.scene3d.as_ref().map_or(Ok(()), |e| e.canary())))?; }+ Ok(px)+ })+ .map_err(|e| if i == 0 { format!("{e}; no frame was written") } else { format!("{e}; the {i} frames before it are in {}", out.display()) })?;let dest = if folder { out.join(format!("frame-{i:05}.png")) } else { out.to_path_buf() };image::save_buffer(&dest, &px, w, h, image::ColorType::Rgba8).map_err(|e| format!("{}: {e}", dest.display()))?;- if folder {- write_aov(out, i, cx.scene3d.as_mut())?;- }+ if folder { write_aov(out, i, cx.scene3d.as_mut())?; }}// with --manifest, its file as a 2D render writes it (it wrote none, and an older one stayed looking current, #28)let clipping = FED_CLIPPING.lock().unwrap().take().and_then(|t| t.join().ok()).unwrap_or_default();diff --git a/runtime/view/src/gpuview/render.rs b/runtime/view/src/gpuview/render.rsindex 4e0b0fe4..7f7fdf27 100644--- a/runtime/view/src/gpuview/render.rs+++ b/runtime/view/src/gpuview/render.rs@@ -80,13 +80,26 @@ impl GpuView {if flight.len() == depth {drain(self, &mut flight, &mut dt)?;}- self.ts_uploads = 0;- if let Some(feed) = feed.as_mut() {- let t = Instant::now();- self.fed = Some(feed(f)?);- dt.fed += t.elapsed().as_secs_f64() * 1e3;- }- let ft = self.frame_wait(f, false)?;+ // the frame's page and overlay, a panic in them an error naming the frame (#33); on any failure the frames+ // in flight reach the sink first, so the render keeps every frame drawn before this one+ let drawn = raea_gpu_device::check::frame_caught(f, || {+ self.ts_uploads = 0;+ if let Some(feed) = feed.as_mut() {+ let t = Instant::now();+ self.fed = Some(feed(f)?);+ dt.fed += t.elapsed().as_secs_f64() * 1e3;+ }+ self.frame_wait(f, false)+ });+ let ft = match drawn {+ Ok(ft) => ft,+ Err(e) => {+ while !flight.is_empty() {+ drain(self, &mut flight, &mut dt)?;+ }+ return Err(e);+ }+ };dt.rules += ft.rules;dt.overlay += ft.overlay;dt.decode_upload += ft.decode_upload;