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.

LT1: live frame time, flicker against the path-traced shot, light measured on 8x8 blocks, a converged FLOOR3

shinyobjectzf7484f2eb5b4
diff --git a/bench/light/scenes.json b/bench/light/scenes.json
index 5cedbb43..ecb944b0 100644
--- a/bench/light/scenes.json
+++ b/bench/light/scenes.json
@@ -17,7 +17,12 @@
16
],
"reference": false,
- "why": "its city is drawn by shader hooks the path tracer can't run and its people aren't traced (M3, M5): after LT2, LT3 and LT5"
+ "why": "its city is drawn by shader hooks the path tracer can't run and its people aren't traced (M3, M5): after LT2, LT3 and LT5",
+ "live": true,
+ "shot": [
+ 0,
+ 4
+ ]
},
{
"name": "floor3-room",
@@ -25,13 +30,15 @@
"file": "compositions/floor3.tsx",
"composition": "floor3",
"stills": [
- 300,
- 900
+ 1500,
+ 4000
],
"shot": [
- 600,
- 630
- ]
+ 1500,
+ 1504
+ ],
+ "live": true,
+ "spp": 2048
},
{
"name": "kitchen",
@@ -44,8 +51,12 @@
],
"shot": [
100,
- 124
- ]
+ 104
+ ],
+ "live": true,
+ "spp": 1024,
+ "reference": false,
+ "why": "its daylight is RectLight panels (the window, the court's sky, a bounce panel), which neither Solari nor the path tracer draws (M9), and its hands are skinned (M3): after LT5b and LT5"
},
{
"name": "glade",
@@ -58,8 +69,10 @@
],
"shot": [
10,
- 34
- ]
+ 14
+ ],
+ "live_why": "raea play runs a file's first composition, and v3/film.tsx's isn't the wide shot",
+ "spp": 512
}
]
}
diff --git a/docs/manual/reference/cli/light.md b/docs/manual/reference/cli/light.md
index 085a9738..568e25d6 100644
--- a/docs/manual/reference/cli/light.md
+++ b/docs/manual/reference/cli/light.md
@@ -6,18 +6,33 @@ sources: ["engine/light/src/lib.rs", "engine/light/src/metric.rs", "engine/rende
---
`raea light check` is the bar raea's lighting is held to (docs/realism.feature LT1). Each scene in a list is
-rendered on each light path, raster and Solari, and against its reference: the same frames path-traced, each drawn
-`--spp` times so it converges. For each path it reports how far the stills are from the reference in stops (the
-mean, the bias, brighter positive, and the worst 64-pixel tile), how much a moving shot flickers (each pixel's
-second difference in time, in 8-bit steps), and what a frame costs. A reference is made once and kept until
+rendered on each light path (raster as the composition has it; `traced-ao`, raster with traced occlusion in place of
+SSAO on a camera with `<AmbientOcclusion>`; and Solari) and against its reference: the same frames path-traced, each
+drawn `--spp` times so it converges. For each path it reports:
+
+- how far the stills are from the reference, in stops: the mean, the bias (brighter is positive) and the worst
+ 64-pixel tile. It compares each 8x8-pixel square's mean luminance, so it measures the light, not antialiasing that
+ differs by path or noise left in the reference;
+- how much a short moving shot flickers against the same shot path-traced: each pixel's error in stops, and that
+ error's second difference in time. Motion is in the reference too, so only light that changes when the truth
+ doesn't counts. The frames' own second difference, in 8-bit steps, is beside it as `raw`;
+- what a still costs to render, and what a frame costs live: the scene played headless and unthrottled for six
+ seconds (`raea play --offscreen --no-vsync --3d`), as milliseconds a frame. The 3D draws at its composition's size
+ whatever the stage's, so there's no half-size measure yet.
+
+A reference is kept and used again while it's the same frames of the same composition at the same samples, until
`--fresh`.
The scenes are a JSON file: `{ "scenes": [{ "name", "dir", "file", "composition", "stills": [frames], "shot":
-[first, last], "reference": false, "why": "..." }] }`. `dir` is the scene's project (renders run there), `file` its
-composition in it; a scene whose reference can't be made yet says so with `"reference": false` and why.
+[first, last], "spp": N, "reference": false, "why": "...", "live": true, "size": [w, h] }] }`. `dir` is the scene's
+project (renders run there), `file` its composition in it. A few frames make a shot, since each is path-traced.
+`"spp"` sets the scene's reference samples in place of `--spp` (an interior lit by small lamps needs thousands). A
+scene whose reference can't be made yet says so with `"reference": false` and why. `"live": true` plays it live as
+well; `raea play` runs a file's first composition, so only a scene that's first in its file can be (`"live_why"` says
+why another isn't). `"size"` is the live stage, 1920x1080 by default.
Any render takes the same switches: `RAEA_LIGHT=raster|solari|pathtracer` puts every 3D camera on that path,
-whatever the composition asks, and `RAEA_LIGHT_SPP=N` draws each frame N times.
+whatever the composition asks, and `RAEA_LIGHT_SPP=N` draws each frame N times, the path tracer's accumulation started afresh on each frame.
```sh
raea light check bench/light/scenes.json -o out/light/
@@ -29,7 +44,7 @@ raea light check bench/light/scenes.json -o out/light/ --scene kitchen --paths s
## Usage
```sh
-raea light check SCENES.json -o DIR [--scene NAME] [--paths raster,solari] [--spp N] [--fresh] (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)
+raea light check SCENES.json -o DIR [--scene NAME] [--paths raster,traced-ao,solari] [--spp N] [--fresh] (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)
```
Headless: it needs nothing running and opens no window. Takes up to 2 arguments besides its flags.
@@ -39,7 +54,7 @@ Headless: it needs nothing running and opens no window. Takes up to 2 arguments
| Flag | Takes | What it does |
| --- | --- | --- |
| `--fresh` | – | Make the references again, even where they're kept from an earlier check. |
-| `--paths` | `raster,solari` | The light paths to measure, comma-separated (both by default). |
+| `--paths` | `raster,traced-ao,solari` | The light paths to measure, comma-separated (all three by default). |
| `--scene` | `NAME` | Check only the scene with this name. |
| `--spp` | `N` | How many times each reference frame is path-traced: its samples a pixel (256 by default). |
| `-o` | `DIR` | The folder for each scene's frames and report.json. |
diff --git a/docs/realism.feature b/docs/realism.feature
index ffcd3ce9..a156c493 100644
--- a/docs/realism.feature
+++ b/docs/realism.feature
@@ -104,12 +104,37 @@ Feature: raea Light: one realism system for shading, ray tracing and occlusion,
room (interior, light jumps), a kitchen (gambit's first-person table, fp-lab-table: contact shadows and occlusion;
the anything film's kitchen doesn't render on 11-17, every composition in content/anything throwing "Can't find
variable: raea" before its first frame) and the glade (foliage, sun through leaves)
+ And the plan
+ | crate | file | lines | job |
+ | raea-light | src/lib.rs | 260 | `raea light check`: scenes, references kept, paths, live |
+ | raea-light | src/metric.rs | 190 | stops on 8x8 blocks, worst tile, flicker against the shot |
+ | raea-render-raytrace | src/force.rs | 70 | RAEA_LIGHT: every camera on one path |
+ | raea-render-raytrace | src/lib.rs | 55 | restart_pathtracer, Solari wanted when forced |
+ | raea-render | src/lib.rs | 40 | restart_pathtracer for the frame loop |
+ | raea-runtime-export | src/bevy_frame.rs | 340 | RAEA_LIGHT_SPP: a frame drawn N times, accumulated afresh |
+ | bevy_solari | src/pathtracer/extract.rs | 40 | raea: the path tracer's reset one-shot, as Solari's |
+ | raea-cli | src/cli.rs | 384 | the `light` verb |
Then each has a converged <Pathtracer> frame as its reference, in the same units and exposure; gambit's, whose
world is drawn by hooks the path tracer can't run (M5), only once LT2 and LT3 put them in the traced path
+ And Berlin (gambit's people-ingame) is the main scene, every step aimed at it first and shown on it before and
+ after (Shane, 11-17); the other three prove the check until the path tracer can draw Berlin
And `raea light check` renders each with the current path and reports distance to the reference (mean and
worst tile, in stops), temporal stability over a moving shot, and the live frame time at 1080p and half size
+ (half size waits on a switch that draws the 3D smaller: the live 3D draws at its composition's size whatever
+ the stage's, so `raea play --size` measured the same frame, 11-17)
And the numbers for today's paths (flat ambient, captured environment, traced AO, Solari) are recorded here as
the baseline before any step below lands
+ And measured 11-17 on this Mac: FLOOR3, stills 1500 and 4000 against a 2048-sample reference (44 s a frame), the
+ distance on 8x8-pixel blocks, flicker against the path-traced shot 1500-1504, live 6 s unthrottled at 1080p
+ | scene | path | mean stops | bias | worst tile | flicker | live ms a frame |
+ | floor3 | raster | 1.379 | -0.80 | 3.37 | 0.101 | 18.0 |
+ | floor3 | traced-ao | 1.379 | -0.80 | 3.37 | 0.101 | 18.6 |
+ | floor3 | solari | 0.959 | -0.95 | 2.62 | 0.113 | 47.6 |
+ And what they say: Solari is nearer the truth than raster, its error almost all one bias (a stop dark, the
+ bounce an interior lives on), raster's patchy; but Solari costs 2.6 times raster's frame. traced-ao is raster
+ here (FLOOR3's camera has no <AmbientOcclusion>). The shot held still (raster's frames are identical), so its
+ flicker is the reference's own noise, about 0.10 stops at 2048 samples: a moving shot is still to pick. Berlin
+ and the kitchen have no reference yet (M5, M9); the glade waits on a re-run
Rule: One material, one scene
diff --git a/engine/light/src/lib.rs b/engine/light/src/lib.rs
index b4803458..0920866e 100644
--- a/engine/light/src/lib.rs
+++ b/engine/light/src/lib.rs
@@ -1,11 +1,15 @@
//! `raea light check SCENES.json -o DIR` (docs/realism.feature LT1): the bar raea Light is measured by. Each scene
//! is rendered on each light path (RAEA_LIGHT, engine/render/raytrace force.rs) and against its reference, the path
//! tracer held RAEA_LIGHT_SPP draws a frame: how far each path's stills are from it in stops (mean, bias, worst tile),
-//! how much its moving shot flickers, and what a frame costs. The numbers go to DIR/report.json and a table.
+//! how much its moving shot flickers against the shot path-traced, and what a frame costs. The numbers go to
+//! DIR/report.json and a table.
//!
//! A scene in SCENES.json: { "name", "dir" (its project, where its renders run; ~ is the home folder), "file" (in dir),
-//! "composition", "stills": [frame, ...], "shot": [first, last] (optional), "reference": false (optional: its
-//! reference can't be made yet, and why, in "why") }.
+//! "composition", "stills": [frame, ...], "shot": [first, last] (optional; a few frames are enough, each is
+//! path-traced), "spp": N (optional: its reference's samples a pixel, in place of --spp), "reference": false (optional: its
+//! reference can't be made yet, and why, in "why"), "live": true (optional: `raea play FILE` plays this composition,
+//! its file's first, so its live frame time is measured; false with "live_why" says why not), "size": [w, h] (the
+//! live stage, 1920x1080 by default) }.
pub mod metric;
@@ -14,10 +18,19 @@ use serde_json::{json, Value};
use std::path::{Path, PathBuf};
use std::time::Instant;
-pub const USAGE: &str = "raea light check SCENES.json -o DIR [--scene NAME] [--paths raster,solari] [--spp N] [--fresh]";
+pub const USAGE: &str = "raea light check SCENES.json -o DIR [--scene NAME] [--paths raster,traced-ao,solari] [--spp N] [--fresh]";
-/// The light paths a check compares, as RAEA_LIGHT names them.
-const PATHS: [&str; 2] = ["raster", "solari"];
+/// The light paths a check compares: RAEA_LIGHT's, and traced-ao, raster with systems/rt's traced occlusion in place
+/// of SSAO (on a camera with <AmbientOcclusion>; on any other it draws as raster).
+const PATHS: [&str; 3] = ["raster", "traced-ao", "solari"];
+
+/// The switches a path is drawn with (the reference is `pathtracer`).
+fn switches(path: &str) -> Vec<(&'static str, String)> {
+ match path {
+ "traced-ao" => vec![("RAEA_LIGHT", "raster".into()), ("RAEA_TRACED_AO", "0.5".into())],
+ p => vec![("RAEA_LIGHT", p.to_string())],
+ }
+}
struct Scene {
name: String,
@@ -27,8 +40,14 @@ struct Scene {
stills: Vec<i64>,
shot: Option<(i64, i64)>,
reference: Result<(), String>,
+ live: Result<(), String>,
+ size: (i64, i64),
+ spp: Option<u32>,
}
+/// How long a live play runs, in seconds, its first second not counted.
+const LIVE_SECONDS: &str = "6";
+
fn home(p: &str) -> PathBuf {
match (p.strip_prefix("~/"), std::env::var_os("HOME")) {
(Some(rest), Some(h)) => PathBuf::from(h).join(rest),
@@ -46,7 +65,10 @@ fn scenes(path: &Path) -> R<Vec<Scene>> {
let frames = |k: &str| s[k].as_array().map(|a| a.iter().filter_map(Value::as_i64).collect::<Vec<_>>());
let shot = frames("shot").filter(|f| f.len() == 2).map(|f| (f[0], f[1]));
let reference = if s["reference"] == json!(false) { Err(s["why"].as_str().unwrap_or("not yet").to_string()) } else { Ok(()) };
- Ok(Scene { name: text("name")?, dir: home(&text("dir")?), file: text("file")?, composition: text("composition")?, stills: frames("stills").unwrap_or_default(), shot, reference })
+ let live = if s["live"] == json!(true) { Ok(()) } else { Err(s["live_why"].as_str().unwrap_or("not asked").to_string()) };
+ let size = frames("size").filter(|f| f.len() == 2).map_or((1920, 1080), |f| (f[0], f[1]));
+ let spp = s["spp"].as_u64().map(|n| n.max(1) as u32);
+ Ok(Scene { name: text("name")?, dir: home(&text("dir")?), file: text("file")?, composition: text("composition")?, stills: frames("stills").unwrap_or_default(), shot, reference, live, size, spp })
})
.collect()
}
@@ -60,7 +82,7 @@ fn render(scene: &Scene, path: &str, spp: u32, at: &[i64], out: &Path) -> R<f64>
let t = Instant::now();
let run = std::process::Command::new(exe)
.current_dir(&scene.dir)
- .env("RAEA_LIGHT", path)
+ .envs(switches(path))
.env("RAEA_LIGHT_SPP", spp.to_string())
.args(["render", &scene.file, "--composition", &scene.composition, "--at", &at.join(","), "-o"])
.arg(format!("{}/", out.display()))
@@ -74,6 +96,34 @@ fn render(scene: &Scene, path: &str, spp: u32, at: &[i64], out: &Path) -> R<f64>
Ok(t.elapsed().as_secs_f64())
}
+/// The scene played live on `path` at `size`, headless and unthrottled (`raea play --offscreen --no-vsync --3d`): what
+/// a frame costs, from play's report (DIR/PATH-live-WxH.json): the frames presented a second as milliseconds a frame,
+/// and each frame's work at the median and the 99th percentile.
+fn live(scene: &Scene, path: &str, size: (i64, i64), out: &Path) -> R<Value> {
+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;
+ let size = format!("{}x{}", size.0, size.1);
+ let json_out = out.join(format!("{path}-live-{size}.json"));
+ let run = std::process::Command::new(exe)
+ .current_dir(&scene.dir)
+ .envs(switches(path))
+ .env("RAEA_AUDIO_MUTE", "1")
+ .args(["play", &scene.file, "--offscreen", "--no-vsync", "--3d", "--seconds", LIVE_SECONDS, "--size", &size, "--json"])
+ .arg(&json_out)
+ .output()
+ .map_err(|e| e.to_string())?;
+ let text = std::fs::read_to_string(&json_out).map_err(|_| {
+ let err = String::from_utf8_lossy(&run.stderr);
+ format!("{} on {path}: play wrote no report: {}", scene.name, err.lines().rev().take(3).collect::<Vec<_>>().join(" | "))
+ })?;
+ let r: Value = serde_json::from_str(&text).map_err(|e| format!("{}: {e}", json_out.display()))?;
+ let fps = r["presented_fps"].as_f64().unwrap_or(0.0);
+ Ok(json!({
+ "size": size,
+ "ms_a_frame": if fps > 0.0 { json!(((1000.0 / fps) * 10.0).round() / 10.0) } else { Value::Null },
+ "work_ms_p50": r["work_ms"]["p50"], "work_ms_p99": r["work_ms"]["p99"], "presented": r["presented"], "error": r["error"],
+ }))
+}
+
fn frames(dir: &Path, n: usize) -> R<Vec<metric::Luma>> {
(0..n).map(|k| metric::load(&dir.join(format!("frame-{k:05}.png")))).collect()
}
@@ -82,24 +132,45 @@ fn round(x: f32, k: f32) -> f64 {
((x * k).round() / k) as f64
}
-/// One scene: its reference (made once, kept unless --fresh), then each path's stills against it and its shot.
+/// Frames `at` path-traced at `spp` into `dir`, kept from an earlier check when it made the same frames of the same
+/// composition at the same samples (DIR/made.json) and --fresh isn't given; the frames, and how they were had.
+fn reference(scene: &Scene, spp: u32, at: &[i64], dir: &Path, fresh: bool) -> R<(Vec<metric::Luma>, Value)> {
+ let made = json!({ "file": scene.file, "composition": scene.composition, "frames": at, "spp": spp });
+ let kept = std::fs::read_to_string(dir.join("made.json")).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());
+ let how = if !fresh && kept.as_ref() == Some(&made) {
+ json!({ "spp": spp, "kept": true })
+ } else {
+ let s = render(scene, "pathtracer", spp, at, dir)?;
+ std::fs::write(dir.join("made.json"), made.to_string()).map_err(|e| e.to_string())?;
+ json!({ "spp": spp, "seconds_a_frame": round(s as f32 / at.len().max(1) as f32, 10.0) })
+ };
+ Ok((frames(dir, at.len())?, how))
+}
+
+/// One scene: its reference stills and shot (kept as `reference` says), then each path's stills and shot against them,
+/// and each path live.
fn check(scene: &Scene, paths: &[String], spp: u32, out: &Path, fresh: bool) -> R<Value> {
let root = out.join(&scene.name);
- let ref_dir = root.join("reference");
- let mut report = json!({ "name": scene.name, "stills": scene.stills, "paths": {} });
- let reference = match &scene.reference {
+ let spp = scene.spp.unwrap_or(spp);
+ let shot: Option<Vec<i64>> = scene.shot.map(|(a, b)| (a..=b).collect());
+ let mut report = json!({ "name": scene.name, "stills": scene.stills, "shot": shot, "paths": {} });
+ let (reference, ref_shot) = match &scene.reference {
Err(why) => {
report["reference"] = json!({ "made": false, "why": why });
- None
+ (None, None)
}
Ok(()) => {
- if fresh || !ref_dir.join("frame-00000.png").is_file() {
- let s = render(scene, "pathtracer", spp, &scene.stills, &ref_dir)?;
- report["reference"] = json!({ "made": true, "spp": spp, "seconds": round(s as f32, 10.0) });
- } else {
- report["reference"] = json!({ "made": true, "kept": true });
- }
- Some(frames(&ref_dir, scene.stills.len())?)
+ let (stills, how) = reference(scene, spp, &scene.stills, &root.join("reference"), fresh)?;
+ report["reference"] = json!({ "made": true, "stills": how });
+ let ref_shot = match &shot {
+ Some(at) => {
+ let (frames, how) = reference(scene, spp, at, &root.join("reference-shot"), fresh)?;
+ report["reference"]["shot"] = how;
+ Some(frames)
+ }
+ None => None,
+ };
+ (Some(stills), ref_shot)
}
};
for path in paths {
@@ -115,15 +186,24 @@ fn check(scene: &Scene, paths: &[String], spp: u32, out: &Path, fresh: bool) ->
r["worst_tile_stops"] = json!(round(d.iter().map(|x| x.worst).fold(0.0, f32::max), 1000.0));
r["per_still"] = json!(d.iter().map(|x| json!({ "mean": round(x.mean, 1000.0), "bias": round(x.bias, 1000.0), "worst": round(x.worst, 1000.0), "worst_tile": [x.worst_at.0, x.worst_at.1] })).collect::<Vec<_>>());
}
- if let Some((a, b)) = scene.shot {
- let at: Vec<i64> = (a..=b).collect();
- let shot = root.join(format!("{path}-shot"));
- let secs = render(scene, path, 1, &at, &shot)?;
- r["flicker"] = json!(metric::flicker(&frames(&shot, at.len())?).map(|f| round(f, 1000.0)));
+ if let Some(at) = &shot {
+ let dir = root.join(format!("{path}-shot"));
+ let secs = render(scene, path, 1, at, &dir)?;
+ let got = frames(&dir, at.len())?;
+ // in stops, against the shot path-traced; and the frames' own second difference, in 8-bit steps, which
+ // counts the shot's motion as well
+ if let Some(refs) = &ref_shot {
+ r["flicker_stops"] = json!(metric::error_flicker(&got, refs)?.map(|f| round(f, 1000.0)));
+ }
+ r["flicker_raw"] = json!(metric::flicker(&got).map(|f| round(f, 100.0)));
r["seconds_a_shot_frame"] = json!(round(secs as f32 / at.len() as f32, 100.0));
}
- // the live frame time is measured in play, not here: LT1 leaves it to `raea play`'s own numbers
- r["live_ms"] = Value::Null;
+ r["live"] = match &scene.live {
+ // at the scene's size only: the live 3D draws at its composition's size whatever the stage's
+ // (runtime/live scene_3d), so a smaller stage measured the same frame (11-17), and no switch draws it smaller
+ Ok(()) => json!({ "full": live(scene, path, scene.size, &root)? }),
+ Err(why) => json!({ "measured": false, "why": why }),
+ };
report["paths"][path] = r;
}
Ok(report)
@@ -131,13 +211,14 @@ fn check(scene: &Scene, paths: &[String], spp: u32, out: &Path, fresh: bool) ->
/// The table a person reads: a line a scene and path.
fn table(reports: &[Value]) -> String {
- let mut s = format!("{:<18} {:<8} {:>7} {:>7} {:>7} {:>8} {:>8}\n", "scene", "path", "mean", "bias", "worst", "flicker", "s/still");
+ let mut s = format!("{:<18} {:<9} {:>7} {:>7} {:>7} {:>8} {:>7} {:>8} {:>8}\n", "scene", "path", "mean", "bias", "worst", "flicker", "raw", "s/still", "live ms");
for r in reports {
let name = r["name"].as_str().unwrap_or("");
let Some(paths) = r["paths"].as_object() else { continue };
for (p, v) in paths {
let f = |k: &str| v[k].as_f64().map_or("-".to_string(), |x| format!("{x:.3}"));
- s += &format!("{name:<18} {p:<8} {:>7} {:>7} {:>7} {:>8} {:>8}\n", f("mean_stops"), f("bias_stops"), f("worst_tile_stops"), f("flicker"), f("seconds_a_still"));
+ let ms = |k: &str| v["live"][k]["ms_a_frame"].as_f64().map_or("-".to_string(), |x| format!("{x:.1}"));
+ s += &format!("{name:<18} {p:<9} {:>7} {:>7} {:>7} {:>8} {:>7} {:>8} {:>8}\n", f("mean_stops"), f("bias_stops"), f("worst_tile_stops"), f("flicker_stops"), f("flicker_raw"), f("seconds_a_still"), ms("full"));
}
if r["reference"]["made"] == json!(false) {
s += &format!("{name:<18} (no reference: {})\n", r["reference"]["why"].as_str().unwrap_or(""));
@@ -155,7 +236,7 @@ pub fn light(args: &[String]) -> R<String> {
let only = flag(args, "--scene");
let paths: Vec<String> = flag(args, "--paths").map_or_else(|| PATHS.iter().map(|p| p.to_string()).collect(), |p| p.split(',').map(str::to_string).collect());
if let Some(p) = paths.iter().find(|p| !PATHS.contains(&p.as_str())) {
- return Err(format!("--paths: {p} isn't a light path to check (raster, solari)"));
+ return Err(format!("--paths: {p} isn't a light path to check ({})", PATHS.join(", ")));
}
let spp: u32 = flag(args, "--spp").map(|v| v.parse().map_err(|_| format!("--spp {v}: a count of samples"))).transpose()?.unwrap_or(256);
let fresh = args.iter().any(|a| a == "--fresh");
diff --git a/engine/light/src/metric.rs b/engine/light/src/metric.rs
index 5bb8893d..e5e0e463 100644
--- a/engine/light/src/metric.rs
+++ b/engine/light/src/metric.rs
@@ -2,8 +2,10 @@
//! a moving shot flickers.
//!
//! Both read the frames as they're delivered (8-bit sRGB after tone mapping), each pixel's luminance made linear
-//! again (Rec. 709 weights). A stop is a factor of two in that luminance; pixels darker than FLOOR are compared at
-//! FLOOR, so the noise in near-black doesn't count as error.
+//! again (Rec. 709 weights). A stop is a factor of two in that luminance; anything darker than FLOOR is compared at
+//! FLOOR, so the noise in near-black doesn't count as error. The distance is the light's, not its edges': it compares
+//! each BLOCK x BLOCK square's mean luminance, so antialiasing that differs by path and what noise is left in a
+//! reference count for little. Flicker is each pixel's.
use std::path::Path;
@@ -18,6 +20,8 @@ pub struct Luma {
const FLOOR: f32 = 0.0025;
/// The side of the squares the worst tile is found among, in pixels.
pub const TILE: usize = 64;
+/// The side of the squares the distance compares, in pixels.
+pub const BLOCK: usize = 8;
fn linear(c: u8) -> f32 {
let v = c as f32 / 255.0;
@@ -32,7 +36,25 @@ pub fn load(p: &Path) -> Result<Luma, String> {
Ok(Luma { w, h, y })
}
-/// A frame against its reference: the mean distance in stops, the mean signed (brighter is positive), and the worst
+impl Luma {
+ /// Each k x k square's mean (a square cut by the edge, of what it holds).
+ pub fn blocks(&self, k: usize) -> Luma {
+ let (w, h) = (self.w.div_ceil(k), self.h.div_ceil(k));
+ let mut sum = vec![(0.0f64, 0u32); w * h];
+ for (i, &v) in self.y.iter().enumerate() {
+ let b = &mut sum[(i / self.w / k) * w + (i % self.w) / k];
+ b.0 += v as f64;
+ b.1 += 1;
+ }
+ Luma { w, h, y: sum.into_iter().map(|(s, n)| (s / n.max(1) as f64) as f32).collect() }
+ }
+}
+
+fn stops(p: f32, r: f32) -> f64 {
+ (p.max(FLOOR) / r.max(FLOOR)).log2() as f64
+}
+
+/// A frame against its reference (block by block): the mean distance in stops, the mean signed (brighter is positive), and the worst
/// tile's mean distance with where that tile is (its column and row, in tiles).
#[derive(Debug, Clone, Copy)]
pub struct Distance {
@@ -46,14 +68,15 @@ pub fn distance(a: &Luma, reference: &Luma) -> Result<Distance, String> {
if (a.w, a.h) != (reference.w, reference.h) {
return Err(format!("sizes differ: {}x{} against the reference's {}x{}", a.w, a.h, reference.w, reference.h));
}
- let (tw, th) = (a.w.div_ceil(TILE), a.h.div_ceil(TILE));
+ let (a, reference, tile) = (a.blocks(BLOCK), reference.blocks(BLOCK), TILE / BLOCK);
+ let (tw, th) = (a.w.div_ceil(tile), a.h.div_ceil(tile));
let mut tiles = vec![(0.0f64, 0usize); tw * th];
let (mut sum, mut signed) = (0.0f64, 0.0f64);
for (i, (&p, &r)) in a.y.iter().zip(&reference.y).enumerate() {
- let d = (p.max(FLOOR) / r.max(FLOOR)).log2() as f64;
+ let d = stops(p, r);
sum += d.abs();
signed += d;
- let t = &mut tiles[(i / a.w / TILE) * tw + (i % a.w) / TILE];
+ let t = &mut tiles[(i / a.w / tile) * tw + (i % a.w) / tile];
t.0 += d.abs();
t.1 += 1;
}
@@ -62,6 +85,30 @@ pub fn distance(a: &Luma, reference: &Luma) -> Result<Distance, String> {
Ok(Distance { mean: (sum / n) as f32, bias: (signed / n) as f32, worst: worst as f32, worst_at: (k % tw, k / tw) })
}
+/// Flicker against the reference's own shot: each pixel's error in stops (the frame against its reference frame),
+/// and that error's second difference in time, averaged. Motion and fades are in the reference too, so they cancel;
+/// what's left is light that changes when the truth doesn't. The frames and their references in order, the same
+/// count; fewer than three measure nothing.
+pub fn error_flicker(frames: &[Luma], refs: &[Luma]) -> Result<Option<f32>, String> {
+ if frames.len() != refs.len() {
+ return Err(format!("{} frames against {} reference frames", frames.len(), refs.len()));
+ }
+ if frames.len() < 3 {
+ return Ok(None);
+ }
+ if let Some((a, r)) = frames.iter().zip(refs).find(|(a, r)| (a.w, a.h) != (r.w, r.h)) {
+ return Err(format!("sizes differ: {}x{} against the reference's {}x{}", a.w, a.h, r.w, r.h));
+ }
+ let err = |t: usize, i: usize| stops(frames[t].y[i], refs[t].y[i]);
+ let mut total = 0.0f64;
+ for t in 1..frames.len() - 1 {
+ let n = frames[t].y.len();
+ let s: f64 = (0..n).map(|i| (err(t, i) - 0.5 * (err(t - 1, i) + err(t + 1, i))).abs()).sum();
+ total += s / n.max(1) as f64;
+ }
+ Ok(Some((total / (frames.len() - 2) as f64) as f32))
+}
+
/// Flicker over a moving shot: each pixel's second difference in time (this frame against the mean of the frames
/// either side, so steady motion and steady fades count for nothing), averaged, in 8-bit sRGB steps of luminance.
/// The frames in order; fewer than three measure nothing.
@@ -113,4 +160,22 @@ mod tests {
assert!(flicker(&fade).unwrap() < 1.0);
assert!(flicker(&blink).unwrap() > 20.0);
}
+
+ #[test]
+ fn blocks_are_the_mean_of_what_they_hold() {
+ let mut a = flat(0.0);
+ a.y[0] = 0.64;
+ let b = a.blocks(8);
+ assert_eq!((b.w, b.h), (16, 8));
+ assert!((b.y[0] - 0.01).abs() < 1e-6 && b.y[1] == 0.0);
+ }
+
+ #[test]
+ fn a_shot_that_moves_with_its_reference_doesnt_flicker_and_one_that_blinks_against_it_does() {
+ let truth: Vec<Luma> = (0..5).map(|k| flat(if k % 2 == 0 { 0.1 } else { 0.2 })).collect();
+ let steady: Vec<Luma> = truth.iter().map(|l| Luma { w: l.w, h: l.h, y: l.y.iter().map(|v| v * 1.5).collect() }).collect();
+ assert!(error_flicker(&steady, &truth).unwrap().unwrap() < 1e-5);
+ let still: Vec<Luma> = (0..5).map(|_| flat(0.1)).collect();
+ assert!(error_flicker(&truth, &still).unwrap().unwrap() > 0.9);
+ }
}
diff --git a/engine/render/raytrace/src/force.rs b/engine/render/raytrace/src/force.rs
index cb72dd81..206f9e61 100644
--- a/engine/render/raytrace/src/force.rs
+++ b/engine/render/raytrace/src/force.rs
@@ -2,7 +2,9 @@
//! scene can be measured on each path without editing it. `raster` takes SolariLighting and Pathtracer off the
//! cameras; `solari` puts SolariLighting (Bevy's defaults) on each camera in place of a Pathtracer; `pathtracer`
//! puts Pathtracer on each in place of SolariLighting, for the reference frame (with RAEA_LIGHT_SPP, runtime/export
-//! bevy_frame.rs draws each frame that many times, so it converges). Unset, nothing changes.
+//! bevy_frame.rs draws each frame that many times, so it converges, and starts each frame's accumulation afresh,
+//! `restart_pathtracer`, so a thing that moves under a held camera isn't smeared across frames). Unset, nothing
+//! changes.
use bevy::prelude::*;
use bevy::solari::pathtracer::Pathtracer;
diff --git a/engine/render/raytrace/src/lib.rs b/engine/render/raytrace/src/lib.rs
index e4eafce5..86f2494a 100644
--- a/engine/render/raytrace/src/lib.rs
+++ b/engine/render/raytrace/src/lib.rs
@@ -31,6 +31,14 @@ pub fn add_denoiser(app: &mut App) {
let _ = app;
}
+/// The path tracer starts its accumulation again on the next draw (a reference frame of its own, RAEA_LIGHT_SPP,
+/// docs/realism.feature LT1; it starts again by itself only when the camera moves).
+pub fn restart_pathtracer(world: &mut World) {
+ for mut p in world.query::<&mut bevy::solari::pathtracer::Pathtracer>().iter_mut(world) {
+ p.reset = true;
+ }
+}
+
/// A cut to another camera (docs/rerender.feature RR2): Solari's and the path tracer's history start again, as on their
/// first frame, so the last shot's light isn't carried into this one (Bevy's `reset`, for "sudden camera cuts").
pub fn cut(world: &mut World) {
diff --git a/engine/render/src/lib.rs b/engine/render/src/lib.rs
index 132ea12f..60de1ff9 100644
--- a/engine/render/src/lib.rs
+++ b/engine/render/src/lib.rs
@@ -28,6 +28,10 @@ pub fn inserted_of(p: &Program) -> Vec<Tup> {
out
}
+// a path-traced camera's accumulation started again on the next draw (RAEA_LIGHT_SPP's frames, docs/realism.feature LT1)
+#[cfg(feature = "raytracing")]
+pub use raea_render_raytrace::restart_pathtracer;
+
pub fn dir_of(path: &str) -> PathBuf {
dunce::canonicalize(Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."))).unwrap_or_else(|_| PathBuf::from("."))
}
diff --git a/runtime/export/src/bevy_frame.rs b/runtime/export/src/bevy_frame.rs
index 259d7671..8afe9751 100644
--- a/runtime/export/src/bevy_frame.rs
+++ b/runtime/export/src/bevy_frame.rs
@@ -81,7 +81,11 @@ pub(crate) fn bevy_over_3d(world: &mut World, page: &mut raea_runtime_page::Bevy
e.set_view_box(view);
let mats = page.set_ui_materials(e.world_mut())?;
// one draw a frame, as the fed render draws it (drawn again, a frame's auto exposure and temporal passes move on);
- // RAEA_LIGHT_SPP=N draws it N times, the last kept, so a path-traced reference converges (docs/realism.feature LT1)
+ // RAEA_LIGHT_SPP=N draws it N times, the last kept, so a path-traced reference converges (docs/realism.feature LT1),
+ // its accumulation started afresh so the frame before isn't in it
+ if spp() > 1 {
+ raea_render::restart_pathtracer(e.world_mut());
+ }
for _ in 1..spp() {
e.draw(cx.now);
}
diff --git a/vendor/bevy_solari/src/pathtracer/extract.rs b/vendor/bevy_solari/src/pathtracer/extract.rs
index 19db4f33..5931cd45 100644
--- a/vendor/bevy_solari/src/pathtracer/extract.rs
+++ b/vendor/bevy_solari/src/pathtracer/extract.rs
@@ -2,33 +2,33 @@ use super::{prepare::PathtracerAccumulationTexture, Pathtracer};
use bevy_camera::Camera;
use bevy_ecs::{
change_detection::DetectChanges,
- system::{Commands, Query},
+ system::{Commands, ResMut},
world::Ref,
};
-use bevy_render::{sync_world::RenderEntity, Extract};
+use bevy_render::{sync_world::RenderEntity, MainWorld};
use bevy_transform::components::GlobalTransform;
-pub fn extract_pathtracer(
- cameras_3d: Extract<
- Query<(
- RenderEntity,
- &Camera,
- Ref<GlobalTransform>,
- Option<&Pathtracer>,
- )>,
- >,
- mut commands: Commands,
-) {
- for (entity, camera, global_transform, pathtracer) in &cameras_3d {
+// raea: `reset` is one-shot, as SolariLighting's is (realtime/extract.rs): cleared in the main world once it's
+// extracted. It stayed set, so a cut under the path tracer (raea-render-raytrace `cut`) restarted its accumulation
+// on every frame after it, and a reference never converged (docs/realism.feature LT1)
+pub fn extract_pathtracer(mut main_world: ResMut<MainWorld>, mut commands: Commands) {
+ let mut cameras_3d = main_world.query::<(
+ RenderEntity,
+ &Camera,
+ Ref<GlobalTransform>,
+ Option<&mut Pathtracer>,
+ )>();
+ for (entity, camera, global_transform, pathtracer) in cameras_3d.iter_mut(&mut main_world) {
let mut entity_commands = commands
.get_entity(entity)
.expect("Camera entity wasn't synced.");
- if let Some(pathtracer) = pathtracer
+ if let Some(mut pathtracer) = pathtracer
&& camera.is_active
{
- let mut pathtracer = pathtracer.clone();
- pathtracer.reset |= global_transform.is_changed();
- entity_commands.insert(pathtracer);
+ let mut extracted = pathtracer.clone();
+ extracted.reset |= global_transform.is_changed();
+ entity_commands.insert(extracted);
+ pathtracer.reset = false;
} else {
entity_commands.remove::<(Pathtracer, PathtracerAccumulationTexture)>();
}