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
RR1: every look changes per frame. Each frame's post-processing is its own (runtime/look post.rs), and a set that changes goes in a per-frame table (frame_sets) laid onto the camera's row frame by frame; the camera takes a group off and puts it on again when its columns change (raea-sys-post camera.rs, moved out of raea-runtime-scene3d; volumetric fog's group is raea-sys-fog-half's, which raea-runtime-scene3d hands to it, as a system can't use another sideways). Each light's colour, shadows and shafts change the same way. A draw across a cut (a sky, AO, anti-aliasing, a tonemapper, shadows or volumetric fog coming or going) warms up 8 updates as a load does, so the sky's light is there on a cut's first frame; a ramp is no cut. Play builds its rows the same way: a row with a table is never still (a play's first frame has its sky), depth of field comes and goes with the frames that have one, the page background is keyed, and a seek back that makes a new engine sets play's rows on it again. bench/rerender/rr1.sh: the film as one composition equals its six shot renders 900/900; a 60-frame grade, bloom and fog ramp equals 60 stills 60/60 at SSIM 1.000000; play draws the looks as the render does at 12 seeks and 2 seeks back (the HTML caption over the 3D still differs by up to 2 levels at its edges, as before RR1). The supersample downsample moves to raea-runtime-gpuframe, and light_sig and pass_column to raea-runtime-look, keeping raea-render and raea-runtime-scene under 2,000 lines.
shinyobjectz2e5f9d77554a
diff --git a/Cargo.lock b/Cargo.lockindex 45c02a2e..2bde493d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -15054,7 +15054,6 @@ dependencies = ["bevy","raea-core-program","raea-runtime-plugins",- "raea-sys-compose","raea-sys-compute","raea-sys-fog","raea-sys-fog-half",@@ -15298,6 +15297,9 @@ name = "raea-sys-fog-half"version = "0.1.0"dependencies = ["bevy",+ "raea-core-program",+ "raea-sys-compose",+ "raea-sys-fog","raea-sys-frame","wgpu",]@@ -15604,6 +15606,7 @@ version = "0.1.0"dependencies = ["bevy","raea-core-program",+ "raea-sys-compose","raea-sys-frame",]diff --git a/bench/rerender/ramp.tsx b/bench/rerender/ramp.tsxnew file mode 100644index 00000000..0bddb0d4--- /dev/null+++ b/bench/rerender/ramp.tsx@@ -0,0 +1,37 @@+// RR1: a grade ramp over 60 frames (saturation 0 to 2, temperature -0.3 to 0.3, bloom 0.1 to 1, fog colour from blue+// to orange), each frame's own. Rendered as one 60-frame piece and as 60 stills alone, the two must match.+import { AbsoluteFill, interpolate, registerRoot, Composition, useCurrentFrame } from "raea";+import { Bloom, Canvas3D, Fog, Grade, ToneMapping, manifold } from "raea/3d";+import { Camera3d } from "raea/camera";+import { AmbientLight, DirectionalLight } from "raea/light";+import { Mesh3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { Transform } from "raea/transform";++const GROUND = manifold.box(60, 1, 60).move(0, -0.5, 0);+const BOX = manifold.box(1.5, 1.5, 1.5);++function Ramp() {+ const f = useCurrentFrame();+ const t = (a: number, b: number) => interpolate(f, [0, 59], [a, b]);+ const hx = (v: number) => Math.round(v).toString(16).padStart(2, "0");+ const fog = `#${hx(t(60, 230))}${hx(t(110, 140))}${hx(t(220, 60))}`;+ return (+ <AbsoluteFill style={{ background: "#202830" }}>+ <Canvas3D>+ <Camera3d transform={Transform.fromXyz(6, 3, 8).lookingAt([0, 0.8, 0], [0, 1, 0])} projection={{ Perspective: { fov: 0.8, near: 0.1, far: 100 } }} />+ <DirectionalLight name="sun" transform={Transform.fromXyz(10, 20, 5).lookingAt([0, 0, 0], [0, 1, 0])} illuminance={20000} shadow_maps_enabled />+ <AmbientLight brightness={200} />+ <Mesh3d name="ground" shape={GROUND}><StandardMaterial base_color="#6a7a50" perceptual_roughness={0.9} /></Mesh3d>+ <Mesh3d name="red" shape={BOX} transform={Transform.fromXyz(-1.5, 0.75, 0)}><StandardMaterial base_color="#d03020" /></Mesh3d>+ <Mesh3d name="lamp" shape={BOX} transform={Transform.fromXyz(1.5, 0.75, -1)}><StandardMaterial base_color="#ffffff" emissive="#ffe0a0" emissive_intensity={8} /></Mesh3d>+ <ToneMapping mode="agx" exposure={0.5} />+ <Bloom intensity={t(0.1, 1)} threshold={0.8} />+ <Fog color={fog} near={4} far={30} />+ <Grade temperature={t(-0.3, 0.3)} saturation={t(0, 2)} midtones={{ contrast: t(0.8, 1.2) }} vignette={t(0, 0.6)} />+ </Canvas3D>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="ramp" component={Ramp} width={640} height={360} fps={30} durationInFrames={60} />);diff --git a/bench/rerender/rr1.sh b/bench/rerender/rr1.shnew file mode 100755index 00000000..5a6a12ab--- /dev/null+++ b/bench/rerender/rr1.sh@@ -0,0 +1,106 @@+#!/usr/bin/env bash+# RR1 (docs/rerender.feature): every look changes per frame. Three checks, each writing OUT/<check>.json; the frames are+# compared and deleted as they go (only the JSON, the logs and the list of differing frames stay):+# equal RR0's film as one composition against its six shot compositions, frame for frame (900 PNGs each way):+# every frame identical (cmp, else SSIM)+# ramp ramp.tsx's 60-frame grade, bloom and fog ramp as one piece against 60 stills each rendered alone: every+# frame SSIM 1.000000, and its first and last frames differ (the ramp is there)+# play raea play seeking (offscreen) to the first and middle frame of each shot, against the film's render of the+# same frames (--at), then seeking back (0 -> 400 -> 350 -> 0) against a fresh play's forward seeks. Each+# seek's SSIM and the box its differing pixels lie in: the 3D and its looks must be exact; the HTML caption+# drawn over them (text with a blurred shadow) differs in play by up to 2 levels at its edges, before RR1 as+# after (the page's composite over the 3D, not a look), and is said apart+# bench/rerender/rr1.sh [OUT] [CHECKS]+# RAEA_BIN the raea to run (target/release/raea)+# CHECKS "equal ramp play" by default+# Exits 1 when a check fails.+set -u+cd "$(dirname "$0")/../.." || exit 2+ROOT=$PWD+BIN=${RAEA_BIN:-$ROOT/target/release/raea}+OUT=${1:-${TMPDIR:-/tmp}/raea-rr1}+CHECKS=${2:-equal ramp play}+FILM=$ROOT/bench/rerender/film.tsx+export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0+mkdir -p "$OUT"+fail=0++ssim() { ffmpeg -hide_banner -nostats -i "$1" -i "$2" -lavfi ssim -f null - 2>&1 | sed -n 's/.*All:\([0-9.]*\).*/\1/p'; }+# the box the two pictures' differing pixels lie in, "x1 x2 y1 y2", or nothing when every pixel is the same+box() { ffmpeg -hide_banner -i "$1" -i "$2" -lavfi "[0][1]blend=all_mode=difference,format=gray,bbox=min_val=1" -f null - 2>&1 | grep -o "x1:[0-9]* x2:[0-9]* y1:[0-9]* y2:[0-9]*" | tail -1 | sed 's/[a-z0-9]*://g'; }+lower() { echo "$1 $2" | awk '{print ($2 < $1) ? $2 : $1}'; }++equal() {+ local id t0 t1 same=0 diff=0 worst=1 a b s+ for id in film shot-1 shot-2 shot-3 shot-4 shot-5 shot-6; do+ rm -rf "${OUT:?}/$id"+ t0=$(perl -MTime::HiRes=time -e 'printf "%.3f", time')+ "$BIN" render "$FILM" --composition "$id" -o "$OUT/$id" > "$OUT/$id.log" 2>&1 || { echo "equal: $id failed: $(grep -E 'REFUSED|error' "$OUT/$id.log" | head -2)"; return 1; }+ t1=$(perl -MTime::HiRes=time -e 'printf "%.3f", time')+ echo "equal: $id $(echo "$t0 $t1" | awk '{printf "%.1f", $2 - $1}') s"+ done+ : > "$OUT/equal-differ.txt"+ for k in 1 2 3 4 5 6; do+ for i in $(seq 0 149); do+ a=$OUT/film/frame-$(printf %05d $((150 * (k - 1) + i))).png+ b=$OUT/shot-$k/frame-$(printf %05d "$i").png+ if cmp -s "$a" "$b"; then same=$((same + 1)); continue; fi+ s=$(ssim "$a" "$b")+ diff=$((diff + 1)); echo "shot $k frame $i ssim $s" >> "$OUT/equal-differ.txt"+ worst=$(lower "$worst" "$s")+ done+ done+ rm -rf "${OUT:?}/film" "${OUT:?}"/shot-[1-6]+ echo "{\"frames\": 900, \"identical\": $same, \"differ\": $diff, \"worst_ssim\": $worst}" | tee "$OUT/equal.json"+ [ "$diff" = 0 ]+}++ramp() {+ local src=$ROOT/bench/rerender/ramp.tsx same=0 diff=0 worst=1 i s v end+ rm -rf "${OUT:?}/ramp"; mkdir -p "$OUT/ramp/stills"+ "$BIN" render "$src" --composition ramp -o "$OUT/ramp/piece" > "$OUT/ramp.log" 2>&1 || { echo "ramp: the piece failed: $(grep -E 'REFUSED|error' "$OUT/ramp.log" | head -2)"; return 1; }+ : > "$OUT/ramp-differ.txt"+ for i in $(seq 0 59); do+ s=$OUT/ramp/stills/$(printf %05d "$i").png+ "$BIN" render "$src" --composition ramp --frame "$i" -o "$s" > "$OUT/ramp-still.log" 2>&1 || { echo "ramp: still $i failed: $(grep -E 'REFUSED|error' "$OUT/ramp-still.log" | head -2)"; return 1; }+ v=$(ssim "$OUT/ramp/piece/frame-$(printf %05d "$i").png" "$s")+ if [ "$v" = "1.000000" ]; then same=$((same + 1)); else diff=$((diff + 1)); echo "frame $i ssim $v" >> "$OUT/ramp-differ.txt"; fi+ worst=$(lower "$worst" "$v")+ done+ end=$(ssim "$OUT/ramp/piece/frame-00000.png" "$OUT/ramp/piece/frame-00059.png")+ rm -rf "${OUT:?}/ramp"+ echo "{\"frames\": 60, \"ssim_1\": $same, \"below\": $diff, \"worst_ssim\": $worst, \"first_vs_last_ssim\": $end}" | tee "$OUT/ramp.json"+ [ "$diff" = 0 ] && [ "$end" != "1.000000" ]+}++# the caption's box on the film's 1920x1080 frame (shots.tsx: left 120, bottom 150, its shadow's 12 px blur around it)+in_caption() { [ -z "$1" ] || { set -- $1; [ "$1" -ge 100 ] && [ "$2" -le 400 ] && [ "$3" -ge 800 ] && [ "$4" -le 950 ]; }; }++play() {+ local d=$OUT/play frames=() args=() at n f r b v exact=0 caption=0 look=0 worst=1 back_ok=0+ rm -rf "${d:?}"; mkdir -p "$d/seek"+ for k in 0 1 2 3 4 5; do for i in 0 75; do f=$((150 * k + i)); frames+=("$f"); args+=(--seek "$f" "$d/seek/$(printf %05d $f).png"); done; done+ at=$(IFS=,; echo "${frames[*]}")+ "$BIN" render "$FILM" --composition film --at "$at" -o "$d/at" > "$OUT/play-at.log" 2>&1 || { echo "play: the render failed: $(tail -3 "$OUT/play-at.log")"; return 1; }+ RAEA_AUDIO_MUTE=1 RAEA_LIVE3D_CHECK=1 "$BIN" play "$FILM" --offscreen --size 1920x1080 "${args[@]}" > "$OUT/play.log" 2>&1 || { echo "play: failed: $(tail -3 "$OUT/play.log")"; return 1; }+ : > "$OUT/play-differ.txt"+ for n in "${!frames[@]}"; do+ f=$(printf %05d "${frames[$n]}"); r=$d/at/frame-$(printf %05d "$n").png+ v=$(ssim "$d/seek/$f.png" "$r"); b=$(box "$d/seek/$f.png" "$r")+ worst=$(lower "$worst" "$v")+ if [ -z "$b" ]; then exact=$((exact + 1)); elif in_caption "$b"; then caption=$((caption + 1)); else look=$((look + 1)); fi+ [ -n "$b" ] && echo "frame $f ssim $v box $b" >> "$OUT/play-differ.txt"+ done+ # a seek back (a plugin's clock makes it a new engine from the play's first rows) draws what a forward seek draws+ RAEA_AUDIO_MUTE=1 "$BIN" play "$FILM" --offscreen --size 1920x1080 --seek 0 "$d/a0.png" --seek 400 "$d/a400.png" --seek 350 "$d/a350.png" --seek 0 "$d/a0b.png" > "$OUT/play-back.log" 2>&1 &&+ RAEA_AUDIO_MUTE=1 "$BIN" play "$FILM" --offscreen --size 1920x1080 --seek 0 "$d/b0.png" --seek 350 "$d/b350.png" >> "$OUT/play-back.log" 2>&1 || { echo "play: a seek back failed: $(tail -3 "$OUT/play-back.log")"; return 1; }+ for p in "a350 b350" "a0b b0"; do set -- $p; [ "$(ssim "$d/$1.png" "$d/$2.png")" = "1.000000" ] && back_ok=$((back_ok + 1)); done+ rm -rf "${d:?}"+ echo "{\"seeks\": ${#frames[@]}, \"exact\": $exact, \"caption_only\": $caption, \"look_differs\": $look, \"worst_ssim\": $worst, \"seeks_back_exact\": \"$back_ok/2\"}" | tee "$OUT/play.json"+ [ "$look" = 0 ] && [ "$back_ok" = 2 ]+}++for c in $CHECKS; do+ "$c" || { echo "rr1: $c FAILED"; fail=1; }+done+exit $faildiff --git a/docs/rerender.feature b/docs/rerender.featureindex 0359de84..52fe0f89 100644--- a/docs/rerender.feature+++ b/docs/rerender.feature@@ -65,12 +65,45 @@ Feature: Re-render, don't stitch: one render changes anything per frame, redrawsRule: One render can change anything, every frame+ @doneScenario: RR1. Every look changes per frame+ # Status 11-10: done. A frame's post-processing is its own (post.rs frame_post: the sky, bloom, fog, grade,+ # vignette, AO, anti-aliasing, tonemapping, exposure, volumetric fog and depth of field's kind), and sets that+ # change go in a per-frame table (frame_sets, frame_set_i); each light's colour, shadows and shafts too+ # (light_sets). The camera takes a group off and puts it on again when its columns change (raea-sys-post, 12+ # groups). A draw across a cut (a set bringing or taking a sky, AO, anti-aliasing, a tonemapper, shadows or+ # volumetric fog: tables.rs Cuts) warms up 8 updates at its frame, as a load does, in frames() and in the page+ # path's draw: the sky's light (Bevy's generated environment map) takes three, and RR0's sunset opened 2 frames+ # dark without them. A ramp (a value moving within one set) is no cut. Play builds its rows the same way (live.rs:+ # tables, the page background keyed), and a seek back that makes a new engine sets play's rows on it again.+ # Measured on this Mac with bench/rerender/rr1.sh (the 13:00 build):+ # the film as one composition against its six shot renders: 900/900 frames identical (it held shot 1's look)+ # ramp.tsx's 60-frame grade, bloom and fog ramp against 60 stills each rendered alone: 60/60 SSIM 1.000000,+ # its first and last frames 0.645 apart+ # raea play seeking to the first and middle frame of each shot: the 3D and its looks as the render draws them+ # 12/12 (before: play held shot 1's sky, missed the page background on shots 3-5, opened without the sky's+ # light and never put depth of field on, SSIM 0.43-0.93); a seek back (0, 400, 350, 0) equal to the forward+ # seeks 2/2 (it drew the first frame's look: a plugin's clock makes a new engine from the load)+ # not exact: the HTML caption over the 3D (text with a 12 px blurred shadow) differs between play and render by+ # at most 2 levels at its edges, SSIM 0.999473-0.999999, as it did before RR1: the page's composite over the+ # 3D, not a look, handed to the issues lane+ # Cost, interleaved with the pre-RR1 binary under load 6-12: the film as one MP4 with its six looks in 20.4, 26.4,+ # 34.4 and 26.3 s; the old binary's one render (shot 1's look for all 900 frames) 30.1, 34.6, 31.8 and 34.7 s.+ # The five cuts cost 1.3-1.7 s together (0.4 s before RR1, the new shots' first frames), most of it their warm-up+ # updates. variants.rs isn't built: preparing every look's pipelines before frame 0 would move their compiles onto+ # the first frame, which RR10 makes 5x faster; RR10's cache takes compiles off every first use instead.Given the plan| crate | file | lines | job |- | raea-runtime-look | runtime/look/src/frame.rs | 240 | the look as per-frame columns: atmosphere, bloom, fog, depth of field, every Grade field, SSAO, anti-aliasing, shadows, volumetric fog and tonemapping, as aberration already is |- | raea-runtime-look | runtime/look/src/apply.rs | 260 | each frame's look applied to the camera's Bevy components; moved out of raea-runtime-scene3d (camera.rs, sync.rs), which is at its 2,000-line limit |- | raea-runtime-look | runtime/look/src/variants.rs | 140 | the pipeline variants a render's looks will need (tonemapper, AA mode, shadow filter, SSAO on or off), prepared before its first frame so a switch mid-render never stalls |+ | raea-runtime-look | runtime/look/src/post.rs | 370 | each frame's post-processing from its own parts (atmosphere, bloom, fog, every Grade field and the vignette, SSAO, anti-aliasing, shadows, volumetric fog, tonemapping and exposure, depth of field's kind); sets that change go in a per-frame table (frame_sets, and frame_set_i keyed), as depth of field's aperture and aberration are already keyed; each light's colour, shadows and shafts as its own table (light_sets) |+ | raea-sys-frame | systems/frame/src/tables.rs | 225 | the frame_looks table generalised: each frame's set laid onto its row (FrameRows::vals), for a frame look and for the post-processing; where a render's frames cut (Cuts: a set that brings or takes a mode) |+ | raea-sys-post | systems/post/src/camera.rs | 233 | the post-processing on the camera by group, moved out of raea-runtime-scene3d (camera.rs), which is at its 2,000-line limit; a frame whose row changes a group takes it off and puts it on again, and MSAA goes off with AO or SMAA/FXAA and back on without them |+ | raea-sys-post | systems/post/src/camera/on.rs | 199 | each group put on and taken off (scene3d's code, moved) |+ | raea-sys-fog-half | systems/fog-half/src/camera.rs | 91 | volumetric fog's group (VFOG), there because it puts on that crate's HalfFog and a system can't use another sideways: raea-runtime-scene3d hands it to raea-sys-post's apply and sync beside its own |+ | raea-runtime-scene| runtime/scene/src/live.rs | 405 | play's rows as a render's: each frame's post-processing and light sets as tables, the page background keyed (bg_r..bg_a) |+ | raea-render | engine/render/src/engine.rs | 474 | a draw across a cut warms up as a load does (Engine::draw and output.rs frames); a seek back that makes a new engine sets play's rows on it again |+ | raea-runtime-gpuframe | runtime/gpuframe/src/downsample.rs | 52 | a supersampled readback shrunk (RAEA_SS), moved out of raea-render to keep it under 2,000 lines |+ | - | bench/rerender/rr1.sh | 106 | the three checks below (equal, ramp, play), each writing its JSON, the frames deleted as they're compared |+ | - | bench/rerender/ramp.tsx | 37 | the 60-frame ramp: grade, bloom, fog colour and vignette moving every frame |Then runtime/look/src/camera.rs stops reading these "as the first frame that has each asks"And a value (a grade's saturation, bloom's strength, fog's colour, the focus distance) is keyframed like any propAnd RR0's film rendered as one composition equals its six chunk renders frame for frame (SSIM 1.000000)@@ -191,6 +224,9 @@ Feature: Re-render, don't stitch: one render changes anything per frame, redrawsAnd a cold first frame of RR0's film, and of an exported game's first play, is at least 5x faster on the Macand on the Windows PC, measured with the OS's own shader cache clearedAnd RR5's workers share it, so N workers don't compile N times+ And RR1's cuts are timed again with it: the film's five cost 1.3-1.7 s together on 11-10, against 0.4 s with+ one look (RR1 left preparing every look's pipelines before frame 0 to this cache, so the first frame isn't+ made to pay for all of them)@needs:RR0Scenario: RR11. A draft tier, rendered small and upscaleddiff --git a/engine/render/src/engine.rs b/engine/render/src/engine.rsindex 7235589c..b132cb73 100644--- a/engine/render/src/engine.rs+++ b/engine/render/src/engine.rs@@ -23,9 +23,9 @@ use raea_core_program::eval::Tup;use raea_sys_frame::store;use raea_core_program::ir::{Program, V};-// clips pooled on the GPU, the Blitz overlay and the NV12 readback (raea-runtime-gpuframe)+// clips pooled on the GPU, the Blitz overlay, the NV12 readback and a supersampled one shrunk (raea-runtime-gpuframe)#[cfg(feature = "native")]-use raea_runtime_gpuframe::{nv12::*, overlay::*, pool::*};+use raea_runtime_gpuframe::{downsample::downsample, nv12::*, overlay::*, pool::*};mod spawn;pub use spawn::*;pub use open::Opening;@@ -126,6 +126,13 @@ pub struct Engine {prestep: bool,/// its updates pipelined or not (raea_sys_frame::pipe)pipe: raea_sys_frame::pipe::Pipe,+ /// the frame `draw` last drew (None after a load)+ drawn: Option<i64>,+ /// a live scene's rows changed a set structurally (set_rows): the next draw warms up as at a cut+ warm_next: bool,+ /// with a load to replay, a live scene's rows as set so far (set_rows, less remove_rows), merged: what a seek back+ /// sets again on the new App, which starts from the load's (catch_up)+ kept: BTreeMap<(String, String), BTreeMap<String, V>>,}/// RAEA_MEM_MARKS: one line on stderr per start-up phase, "mem_mark <ms since the first mark> <phys_footprint MB>@@ -226,6 +233,19 @@ impl Engine {self.app.world_mut().resource_mut::<Error>().0 = Some(e);}self.app.world_mut().resource_mut::<Clock>().0 = f;+ // a frame across a cut from the one drawn last (another shot's sky, fog or grade: frame_sets) warms up as a load+ // does, 8 updates at it before its own: a new effect can take updates to come (the sky's light on the scene,+ // Bevy's generated environment map, took three, so RR0's sunset shot opened 2 frames dark, RR1). A plugin's+ // clock steps on the first and holds on the rest, as `frames` warms up a cut and a shot rendered alone its load+ let cut = std::mem::take(&mut self.warm_next) || self.drawn.is_some_and(|d| self.app.world().get_resource::<raea_sys_frame::tables::Cuts>().is_some_and(|c| c.between(d, f)));+ self.drawn = Some(f);+ if cut {+ self.pipe.flush(&mut self.app);+ for _ in 0..8 {+ plugins::arm(self.app.world_mut());+ self.app.update();+ }+ }self.pre_step();plugins::arm(self.app.world_mut());self.pipe.flush(&mut self.app);@@ -259,12 +279,20 @@ impl Engine {/// call on, every frame draws the rows' latest values instead of the timeline's. Nothing is rebuilt per frame: only/// the values given change, and the sync systems write only what changed onto the entities.pub fn set_rows(&mut self, rows: &[Tup]) -> Result<(), String> {+ if self.replay.is_some() {+ for t in rows {+ self.kept.entry((t.kind.clone(), t.id.clone())).or_default().extend(t.vals.iter().map(|(k, v)| (k.clone(), v.clone())));+ }+ }let spawned = apply_rows(self.app.world_mut(), &self.dir, rows)?;if spawned {scene3d::shade_rows(self.app.world_mut(), rows)?;}// a camera's frame looks, as the timeline's are each frame (relational), so a live game's look turns on too- self.app.world_mut().resource_mut::<FrameRows>().parse_looks();+ // a set that came, went or changed its kind (another shot's sky, AO coming on): the next frame warms up (draw)+ if self.app.world_mut().resource_mut::<FrameRows>().parse_looks() {+ self.warm_next = true;+ }// a glTF model, and a panorama a live frame showed first (#38), set up before the frame that shows it drawsif spawned { scene3d::await_models(&mut self.app)?; }raea_sys_post::msaa_for_3d(self.app.world_mut(), has_3d(rows) || raea_sys_sprite::has_2d(rows));@@ -273,6 +301,7 @@ impl Engine {/// A live scene's rows dropped, by kind and id: their entities go (and the meshes and surfaces only they held).pub fn remove_rows(&mut self, rows: &[(String, String)]) {+ rows.iter().for_each(|r| drop(self.kept.remove(r)));remove_rows_from(self.app.world_mut(), rows);}@@ -293,7 +322,13 @@ impl Engine {// the old App dropped it ("Buffer ... has been destroyed" from get_mapped_range, a panic)#[cfg(feature = "native")]raea_sys_frame::pipe::wait_gpu(&self.app);+ let kept = std::mem::take(&mut self.kept);*self = Engine::build(&prog, &rows, &dir, None, self.live)?;+ // a live scene's rows as the play left them (this frame's included): the load's are its first frame's, so+ // a seek back from another shot drew the first shot's look and anything moved since where it began (RR1)+ if !kept.is_empty() {+ self.set_rows(&kept.into_iter().map(|((kind, id), vals)| Tup { kind, id, vals }).collect::<Vec<_>>())?;+ }}loop {let s = self.app.world().resource::<plugins::PluginClock>().stepped;diff --git a/engine/render/src/engine/load.rs b/engine/render/src/engine/load.rsindex 72680013..2f2a7825 100644--- a/engine/render/src/engine/load.rs+++ b/engine/render/src/engine/load.rs@@ -15,6 +15,7 @@ impl Engine {}// kept (and the frames before a frame stepped through: catch_up) only when the rows need steps (#77)self.replay = (plugins::active(self.app.world()) && plugins::steps(inserted)).then(|| (prog.clone(), inserted.to_vec()));+ self.drawn = None;let world = self.app.world_mut();let g = world.resource::<Gen>().0;world.insert_resource(Gen(if g == 255 { 1 } else { g + 1 }));@@ -125,6 +126,7 @@ impl Engine {None => std::sync::Arc::new(raea_core_program::timeline::Timeline::from_cols(prog, base)?),};world.insert_resource(Edit { prog: prog.clone(), timeline, media });+ world.insert_resource(raea_sys_frame::tables::Cuts::of(prog));world.insert_resource(FrameRows::new(ix));let Some(cam) = camera else { return Err("the edit needs a camera: INSERT INTO camera (id, ...) VALUES (...)".into()) };let models = world.query::<&scene3d::Model3d>().iter(world).count();diff --git a/engine/render/src/engine/open.rs b/engine/render/src/engine/open.rsindex 5bd30cfc..2c12f9f1 100644--- a/engine/render/src/engine/open.rs+++ b/engine/render/src/engine/open.rs@@ -244,7 +244,7 @@ impl Engine {} else {app.world_mut().spawn(Readback::texture(target.clone())).observe(|ev: On<ReadbackComplete>, mut out: ResMut<Out>| out.0.push(ev.data.clone()));}- let mut e = Engine { app, target, w, h, ss, dir: dir.to_path_buf(), #[cfg(feature = "native")] warm: false, #[cfg(feature = "native")] serial: std::env::var_os("RAEA_SERIAL").is_some(), nv12, packed, replay: None, live, prestep: false, pipe: Default::default() };+ let mut e = Engine { app, target, w, h, ss, dir: dir.to_path_buf(), #[cfg(feature = "native")] warm: false, #[cfg(feature = "native")] serial: std::env::var_os("RAEA_SERIAL").is_some(), nv12, packed, replay: None, live, prestep: false, pipe: Default::default(), drawn: None, warm_next: false, kept: Default::default() };mem_mark("engine: target and readback made");e.load_shared(prog, inserted, timeline)?;mem_mark("engine: edit loaded into the World");@@ -252,6 +252,8 @@ impl Engine {e.app.update();mem_mark(&format!("engine: warm-up update {i}"));}+ // the warm-up drew the clock's frame: a first draw across a cut from it warms up again (Engine::draw)+ e.drawn = Some(e.app.world().resource::<Clock>().0);// updates pipelined from here on (raea_sys_frame::pipe), but for a live draw's owne.pipe = raea_sys_frame::pipe::Pipe::new();// a live game's frame on one thread (lightspeed F2): its scene is small, and the multi-threaded executor's taskdiff --git a/engine/render/src/engine/output.rs b/engine/render/src/engine/output.rsindex 251109e7..a7ab2cdf 100644--- a/engine/render/src/engine/output.rs+++ b/engine/render/src/engine/output.rs@@ -97,26 +97,6 @@ impl Engine {if self.ss > 1 { downsample(&px, w, h, self.ss as usize) } else { px }}- /// `list` cut where the frame's look changes (the camera's keyed `frame_look_i`), in order.- #[cfg(feature = "native")]- pub(crate) fn look_runs<'a>(&self, list: &'a [i64]) -> Vec<&'a [i64]> {- let edit = self.app.world().resource::<Edit>();- let Some(keys) = edit.prog.keys.iter().find(|((_, c), _)| c == "frame_look_i").map(|(_, k)| k) else { return vec![list] };- let at = |f: i64| keys.iter().take_while(|(k, ..)| *k <= f).last().or(keys.first()).map(|(_, v, _)| v.round() as i64);- let mut runs = Vec::new();- let mut from = 0;- for i in 1..list.len() {- if at(list[i]) != at(list[i - 1]) {- runs.push(&list[from..i]);- from = i;- }- }- if from < list.len() {- runs.push(&list[from..]);- }- runs- }-/// One frame, straight RGBA8 (opaque), the careful way: two tagged readbacks in a row that agree (the first frame/// after a load, when meshes, materials and the overlay are new to the GPU).#[cfg(feature = "native")]@@ -190,12 +170,19 @@ impl Engine {pub fn frames(&mut self, list: &[i64], mut sink: impl FnMut(i64, Vec<u8>) -> Result<(), String>) -> Result<(), String> {// a frame whose look comes on, changes or goes (frame_look_i, FrameRows::vals) has new materials and cells to// make, which a pipelined update can read back before they draw: each run of one look starts the careful way- let runs = self.look_runs(list);+ let runs = raea_sys_frame::tables::runs(&self.app.world().resource::<Edit>().prog, list);let many = runs.len() > 1;for r in runs {if many {self.warm = false;}+ // a run after a cut warms up as a load does (8 updates): a new effect can take more updates to come than the+ // careful way's 4 (the sky's light on the scene came 2 frames late at RR0's sunset cut, RR1)+ if many && r.first() != list.first() {+ self.catch_up(r[0])?;+ self.app.world_mut().resource_mut::<Clock>().0 = r[0];+ (0..8).for_each(|_| self.step());+ }// 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))??;}diff --git a/engine/render/src/engine/raea_plugins.rs b/engine/render/src/engine/raea_plugins.rsindex cabc25c6..a5e7cbb3 100644--- a/engine/render/src/engine/raea_plugins.rs+++ b/engine/render/src/engine/raea_plugins.rs@@ -112,7 +112,7 @@ pub fn scene3d_systems() -> ScheduleConfigs<ScheduleSystem> {super::scene3d::instance_models,super::scene3d::model_shadow_markers,super::scene3d::toon_models,- ((super::scene3d::sync_meshes, super::scene3d::sync_pictures, super::shader_ext::sync_shaded, raea_sys_sampler::arrays::sync_arrays, raea_sys_sampler::sync_samplers).chain(), super::toon::sync_toon, super::scene3d::sync_camera, super::motion_blur::sync_motion_blur, (super::environment::sync_environment, super::environment::sync_prefiltered, super::environment::sync_suns).chain(), super::scene3d::sync_lights, super::scene3d::sync_fog_volumes, super::scene3d::sync_fog_dither, super::scene3d::sync_models, super::scene3d::sync_morphs, super::scene3d::sync_attach, super::grid::grid_models, super::scene3d::sync_bones, super::look::sync_frame_look, super::look::sync_looks, super::compose::sync_passes, super::look::sync_flat, super::paint::sync_paint, super::decal::sync_decals, super::text3d::sync_texts).chain(),+ ((super::scene3d::sync_meshes, super::scene3d::sync_pictures, super::shader_ext::sync_shaded, raea_sys_sampler::arrays::sync_arrays, raea_sys_sampler::sync_samplers).chain(), super::toon::sync_toon, (super::scene3d::sync_camera, super::scene3d::sync_post).chain(), super::motion_blur::sync_motion_blur, (super::environment::sync_environment, super::environment::sync_prefiltered, super::environment::sync_suns).chain(), (super::scene3d::sync_light_sets, super::scene3d::sync_lights).chain(), super::scene3d::sync_fog_volumes, super::scene3d::sync_fog_dither, super::scene3d::sync_models, super::scene3d::sync_morphs, super::scene3d::sync_attach, super::grid::grid_models, super::scene3d::sync_bones, super::look::sync_frame_look, super::look::sync_looks, super::compose::sync_passes, super::look::sync_flat, super::paint::sync_paint, super::decal::sync_decals, super::text3d::sync_texts).chain(),// --clay and --review's clay half: every standard surface grey, after the rows set their colourssuper::scene3d::clay::clay_materials,)diff --git a/engine/render/src/engine/target.rs b/engine/render/src/engine/target.rsindex 18a0b98d..07bc9b7e 100644--- a/engine/render/src/engine/target.rs+++ b/engine/render/src/engine/target.rs@@ -1,4 +1,4 @@-//! The target's side of a frame: the view box a tagged row draws in, supersampling and its downsample, the render+//! The target's side of a frame: the view box a tagged row draws in, supersampling (its downsample: raea-runtime-gpuframe), the render//! world's diagnostics forwarded.use super::*;@@ -57,46 +57,3 @@ pub(crate) fn supersampling(live: bool) -> u32 {}ss}--#[cfg(feature = "native")]-/// sRGB bytes -> linear, as a table-pub(crate) fn srgb_to_linear_table() -> &'static [f32; 256] {- static T: std::sync::OnceLock<[f32; 256]> = std::sync::OnceLock::new();- T.get_or_init(|| std::array::from_fn(|i| {- let c = i as f32 / 255.0;- if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }- }))-}--#[cfg(feature = "native")]-/// an RGBA frame w x h shrunk by `s`: each s x s block's mean, in linear light (averaging the encoded bytes would darken-/// every edge between light and dark), encoded back to sRGB; alpha averaged as it is-pub(crate) fn downsample(px: &[u8], w: usize, h: usize, s: usize) -> Vec<u8> {- let lin = srgb_to_linear_table();- let (ow, oh) = (w / s, h / s);- let n = (s * s) as f32;- let mut out = vec![0u8; ow * oh * 4];- for y in 0..oh {- for x in 0..ow {- let mut acc = [0f32; 4];- for dy in 0..s {- let row = ((y * s + dy) * w + x * s) * 4;- for dx in 0..s {- let i = row + dx * 4;- acc[0] += lin[px[i] as usize];- acc[1] += lin[px[i + 1] as usize];- acc[2] += lin[px[i + 2] as usize];- acc[3] += px[i + 3] as f32;- }- }- let o = (y * ow + x) * 4;- for c in 0..3 {- let v = acc[c] / n;- let e = if v <= 0.0031308 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 };- out[o + c] = (e.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;- }- out[o + 3] = (acc[3] / n + 0.5) as u8;- }- }- out-}diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rsindex 44dd442e..c0d3ca32 100644--- a/runtime/export/src/fed.rs+++ b/runtime/export/src/fed.rs@@ -157,7 +157,9 @@ pub fn live_scene(world: &mut World, ls: &mut LiveScene, engine: &mut Option<rae*engine = Some(e);}Some(e) => {- let (rows, gone) = ls.frame(Shot { scene: &scene, clear: None });+ // the frame's own clear, keyed as a render keys a background that changes (RR1)+ let clear = scene_clear(world);+ let (rows, gone) = ls.frame(Shot { scene: &scene, clear: clear.as_deref() });if !gone.is_empty() {e.remove_rows(&gone);}diff --git a/runtime/export/src/program.rs b/runtime/export/src/program.rsindex 153d3112..d29d8524 100644--- a/runtime/export/src/program.rs+++ b/runtime/export/src/program.rs@@ -27,7 +27,7 @@ pub(crate) fn program(frames: &[(i64, Frame)], w: u32, h: u32, fps: f64) -> raea// as the page over it changes. Before, the first frame's clear held for the whole render.if has3d && !ALPHA.load(std::sync::atomic::Ordering::Relaxed) {let mut last = None;- let each: Vec<Option<[f64; 4]>> = frames.iter().map(|(_, f)| f.clear.as_deref().and_then(hex_of).and_then(|c| rgba_of(&c))).collect();+ let each: Vec<Option<[f64; 4]>> = frames.iter().map(|(_, f)| f.clear.as_deref().and_then(hex_of).and_then(|c| raea_runtime_scene::rgba_of(&c))).collect();if each.iter().flatten().any(|c| Some(c) != each[0].as_ref()) {let cols: Vec<[f64; 4]> = each.iter().map(|c| *last.insert((*c).or(last).unwrap_or([0.0, 0.0, 0.0, 1.0]))).collect();for (k, name) in ["bg_r", "bg_g", "bg_b", "bg_a"].iter().enumerate() {@@ -167,13 +167,3 @@ pub(crate) fn sound_lint(p: &raea_core_program::ir::Program, fps: f64) {}}-/// A `#rgb`, `#rrggbb` or `#rrggbbaa` colour as sRGB 0..1, alpha last-pub(crate) fn rgba_of(c: &str) -> Option<[f64; 4]> {- let h = c.strip_prefix('#')?;- let h: String = if h.len() == 3 { h.chars().flat_map(|c| [c, c]).collect() } else { h.to_string() };- if h.len() != 6 && h.len() != 8 {- return None;- }- let at = |i: usize| u8::from_str_radix(h.get(i..i + 2)?, 16).ok().map(|v| v as f64 / 255.0);- Some([at(0)?, at(2)?, at(4)?, if h.len() == 8 { at(6)? } else { 1.0 }])-}diff --git a/runtime/gpuframe/src/downsample.rs b/runtime/gpuframe/src/downsample.rsnew file mode 100644index 00000000..bd859bd3--- /dev/null+++ b/runtime/gpuframe/src/downsample.rs@@ -0,0 +1,52 @@+//! A supersampled frame's readback shrunk to the frame's size (RAEA_SS, raea-render's target.rs), on the CPU.++/// sRGB bytes -> linear, as a table+fn srgb_to_linear_table() -> &'static [f32; 256] {+ static T: std::sync::OnceLock<[f32; 256]> = std::sync::OnceLock::new();+ T.get_or_init(|| std::array::from_fn(|i| {+ let c = i as f32 / 255.0;+ if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }+ }))+}++/// an RGBA frame w x h shrunk by `s`: each s x s block's mean, in linear light (averaging the encoded bytes would darken+/// every edge between light and dark), encoded back to sRGB; alpha averaged as it is+pub fn downsample(px: &[u8], w: usize, h: usize, s: usize) -> Vec<u8> {+ let lin = srgb_to_linear_table();+ let (ow, oh) = (w / s, h / s);+ let n = (s * s) as f32;+ let mut out = vec![0u8; ow * oh * 4];+ for y in 0..oh {+ for x in 0..ow {+ let mut acc = [0f32; 4];+ for dy in 0..s {+ let row = ((y * s + dy) * w + x * s) * 4;+ for dx in 0..s {+ let i = row + dx * 4;+ acc[0] += lin[px[i] as usize];+ acc[1] += lin[px[i + 1] as usize];+ acc[2] += lin[px[i + 2] as usize];+ acc[3] += px[i + 3] as f32;+ }+ }+ let o = (y * ow + x) * 4;+ for c in 0..3 {+ let v = acc[c] / n;+ let e = if v <= 0.0031308 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 };+ out[o + c] = (e.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;+ }+ out[o + 3] = (acc[3] / n + 0.5) as u8;+ }+ }+ out+}++#[cfg(test)]+mod tests {+ #[test]+ fn a_block_averages_in_linear_light() {+ // black and white side by side, 2x down: linear mid-grey (188 in sRGB), not the bytes' mean (128)+ let px = [0, 0, 0, 255, 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255];+ assert_eq!(super::downsample(&px, 2, 2, 2), vec![188, 188, 188, 255]);+ }+}diff --git a/runtime/gpuframe/src/lib.rs b/runtime/gpuframe/src/lib.rsindex e06066a4..10652db7 100644--- a/runtime/gpuframe/src/lib.rs+++ b/runtime/gpuframe/src/lib.rs@@ -1,5 +1,5 @@//! A frame on the GPU path (G8): clips decoded once into a GPU pool and composited with the Blitz overlay (pool.rs,-//! overlay.rs), then packed to NV12 for the encoder and read back once (nv12.rs).+//! overlay.rs), then packed to NV12 for the encoder and read back once (nv12.rs); a supersampled frame shrunk (downsample.rs).use std::collections::HashMap;@@ -21,3 +21,4 @@ use crate::pool::*;pub mod overlay;pub mod pool;pub mod nv12;+pub mod downsample;diff --git a/runtime/look/src/camera.rs b/runtime/look/src/camera.rsindex ce9c2d8d..41463b46 100644--- a/runtime/look/src/camera.rs+++ b/runtime/look/src/camera.rs@@ -171,47 +171,13 @@ fn one(all: &[Vec<Item>], p: &mut Program, row: &mut BTreeMap<String, V>, k: usiif all.iter().flatten().any(|i| i.kind == "grade" && num(&i.props, "aberration").is_some()) {column(p, row, id, "aberration", &ab);}- // post-processing: as the first frame that has each asks- let first =|kind: &str| all.iter().flatten().find(|i| i.kind == kind).map(|i| i.props.clone());- // a procedural sky (<Atmosphere>): Earth's air, lighting the scene too when `light`- if let Some(a) = first("atmosphere") {- row.insert("atmosphere".into(), V::N(1.0));- if a.get("light") == Some(&Value::Bool(true)) {- row.insert("atmo_light".into(), V::N(1.0));- }- if let Some(x) = num(&a, "groundAlbedo") {- row.insert("atmo_albedo".into(), V::N(x));- }- }- if let Some(b) = first("bloom") {- row.insert("bloom".into(), V::N(r6(n(&b, "intensity", 1.0) * BLOOM)));- if let Some(t) = num(&b, "threshold") {- row.insert("bloom_threshold".into(), V::N(t));- }- if let Some(s) = shares(&b) {- row.insert("bloom_passes".into(), V::S(s));- }- }- if let Some(f) = first("fog") {- row.insert("fog_color".into(), V::S(hex(f.get("color")).unwrap_or("#808080".into())));- match num(&f, "density") {- Some(d) => {- row.insert("fog_density".into(), V::N(d));- }- None => {- row.insert("fog_start".into(), V::N(n(&f, "near", 5.0)));- row.insert("fog_end".into(), V::N(n(&f, "far", 20.0)));- }- }- }- if let Some(d) = first("dof") {- // keyed: a frame without a <DepthOfField> draws sharp (an f-stop past any blur), not the shot's first one+ // post-processing: each frame's own (post.rs, docs/rerender.feature RR1)+ post(all, p, row, id);+ if all.iter().flatten().any(|i| i.kind == "dof") {+ // keyed: a frame without a <DepthOfField> draws sharp (an f-stop past any blur), not the shot's first one; its+ // size and mode are each frame's post-processing (post.rs), which puts it on and takes it offlet ap: Vec<f64> = all.iter().map(|its| its.iter().find(|i| i.kind == "dof").map_or(NO_DOF, |i| n(&i.props, "aperture", 2.8))).collect();column(p, row, "cam", "dof_aperture", &ap);- row.insert("dof_max".into(), V::N(n(&d, "maxBlur", 64.0)));- if d.get("mode").and_then(Value::as_str) == Some("gaussian") {- row.insert("dof_mode".into(), V::S("gaussian".into()));- }}frame_looks(all, p, row);// the composition passes the parts name (engine/compose.rs)@@ -219,101 +185,6 @@ fn one(all: &[Vec<Item>], p: &mut Program, row: &mut BTreeMap<String, V>, k: usiif !passes.is_empty() {row.insert("passes".into(), V::S(passes.join(",")));}- if let Some(g) = first("grade") {- if let Some(s) = shares(&g) {- row.insert("grade_passes".into(), V::S(s));- }- for (k, col) in [("temperature", "grade_temperature"), ("tint", "grade_tint"), ("saturation", "grade_saturation")] {- if let Some(x) = num(&g, k) {- row.insert(col.into(), V::N(x));- }- }- for (sec, pre) in [("shadows", "grade_s_"), ("midtones", "grade_m_"), ("highlights", "grade_h_")] {- let Some(o) = g.get(sec).and_then(Value::as_object) else { continue };- for k in ["saturation", "contrast", "gamma", "gain", "lift"] {- if let Some(x) = o.get(k).and_then(Value::as_f64) {- row.insert(format!("{pre}{k}"), V::N(x));- }- }- }- match g.get("vignette") {- Some(Value::Number(x)) => {- row.insert("vignette".into(), V::N(x.as_f64().unwrap_or(0.0)));- }- Some(Value::Object(o)) => {- row.insert("vignette".into(), V::N(o.get("intensity").and_then(Value::as_f64).unwrap_or(1.0)));- for (k, col) in [("radius", "vignette_radius"), ("smoothness", "vignette_smooth")] {- if let Some(x) = o.get(k).and_then(Value::as_f64) {- row.insert(col.into(), V::N(x));- }- }- if let Some(c) = hex(o.get("color")) {- row.insert("vignette_color".into(), V::S(c));- }- }- _ => {}- }- }- // ambient occlusion (no multisampling with it: SMAA unless asked otherwise) and the anti-aliasing- let ssao = first("ssao");- if let Some(a) = &ssao {- row.insert("ssao".into(), V::S(a.get("quality").and_then(Value::as_str).unwrap_or("medium").to_string()));- if let Some(t) = num(a, "thickness") {- row.insert("ssao_thickness".into(), V::N(t));- }- }- let aa = first("aa").and_then(|a| a.get("mode").and_then(Value::as_str).map(str::to_string));- match (aa.as_deref(), ssao.is_some()) {- (Some("msaa") | None, true) => {- row.insert("aa".into(), V::S("smaa".into()));- }- (Some(m), _) if m != "msaa" => {- row.insert("aa".into(), V::S(m.to_string()));- }- _ => {}- }- // shadow quality: the map size and the filter on the camera; the cascades and biases go on each light's row- if let Some(sh) = first("shadows") {- if let Some(m) = num(&sh, "mapSize") {- row.insert("shadow_map".into(), V::N(m));- }- if let Some(f) = sh.get("filter").and_then(Value::as_str) {- row.insert("shadow_filter".into(), V::S(f.to_string()));- }- }- if let Some(v) = first("volfog") {- row.insert("vfog".into(), V::N(1.0));- row.insert("vfog_steps".into(), V::N(n(&v, "steps", 64.0)));- if v.get("dither").and_then(Value::as_bool) == Some(true) {- row.insert("vfog_dither".into(), V::N(1.0));- }- if let Some(r) = num(&v, "resolution") {- row.insert("vfog_resolution".into(), V::N(r));- }- if let Some(m) = v.get("mode").and_then(Value::as_str).filter(|m| matches!(*m, "froxel" | "march")) {- row.insert("vfog_mode".into(), V::S(m.into()));- }- if v.get("hero").and_then(Value::as_bool) == Some(false) {- row.insert("vfog_hero".into(), V::N(0.0));- }- for (prop, col) in [("slices", "vfog_slices"), ("tile", "vfog_tile"), ("samples", "vfog_samples")] {- if let Some(x) = num(&v, prop) {- row.insert(col.into(), V::N(x));- }- }- row.insert("vfog_ambient".into(), V::N(n(&v, "ambient", 0.0)));- if let Some(c) = hex(v.get("ambientColor")) {- row.insert("vfog_ambient_color".into(), V::S(c));- }- }- if let Some(t) = first("tonemapping") {- if let Some(m) = t.get("mode").and_then(Value::as_str) {- row.insert("tonemap".into(), V::S(m.to_lowercase()));- }- if let Some(e) = num(&t, "exposure") {- row.insert("exposure".into(), V::N(r6(EV100 - e)));- }- }lens(all, p, row);motion_blur(all, p, row);}@@ -385,3 +256,35 @@ fn quat_columns(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, name:exact(p, row, id, &format!("{name}_{axis}"), &qs.iter().map(|q| q[k]).collect::<Vec<_>>());}}++/// A `#rgb`, `#rrggbb` or `#rrggbbaa` colour as sRGB 0..1, alpha last (a holder's background as the camera's clear,+/// keyed bg_r..bg_a)+pub fn rgba_of(c: &str) -> Option<[f64; 4]> {+ let h = c.strip_prefix('#')?;+ let h: String = if h.len() == 3 { h.chars().flat_map(|c| [c, c]).collect() } else { h.to_string() };+ if h.len() != 6 && h.len() != 8 {+ return None;+ }+ let at = |i: usize| u8::from_str_radix(h.get(i..i + 2)?, 16).ok().map(|v| v as f64 / 255.0);+ Some([at(0)?, at(2)?, at(4)?, if h.len() == 8 { at(6)? } else { 1.0 }])+}++/// A part's composition pass on each frame (`pass`: 0 "scene", from 1 the piece's passes, pass_names), stepped.+pub fn pass_column(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item], names: &[String]) {+ if names.is_empty() || !its.iter().any(|i| i.props.contains_key("pass")) {+ return;+ }+ let ids: Vec<f64> = its.iter().map(|i| i.props.get("pass").and_then(Value::as_str).and_then(|n| names.iter().position(|x| x == n)).map_or(0.0, |k| (k + 1) as f64)).collect();+ row.insert("pass".into(), V::N(ids[0]));+ if !ids.iter().all(|v| *v == ids[0]) {+ p.keys.insert((id.to_string(), "pass".to_string()), ids.iter().enumerate().map(|(f, v)| (f as i64, *v, "step".to_string())).collect());+ }+}++/// The distance the camera focuses at: its `focus`, else how far its lookAt point is.+pub fn focus_of(c: &Item) -> f64 {+ num(&c.props, "focus").unwrap_or_else(|| {+ let (p, l) = (vec3(&c.props, "position", [0.0, 0.0, 5.0]), vec3(&c.props, "lookAt", [0.0, 0.0, 0.0]));+ ((p[0] - l[0]).powi(2) + (p[1] - l[1]).powi(2) + (p[2] - l[2]).powi(2)).sqrt().max(0.01)+ })+}diff --git a/runtime/look/src/lib.rs b/runtime/look/src/lib.rsindex 6c3442f9..9a7b6c09 100644--- a/runtime/look/src/lib.rs+++ b/runtime/look/src/lib.rs@@ -10,6 +10,8 @@ use serde_json::{Map, Value};mod camera;pub use camera::*;mod instances;+mod post;+pub use post::*;mod parts;pub use parts::*;pub use instances::*;@@ -167,14 +169,6 @@ pub fn look_of(props: &Map<String, Value>) -> f64 {}}-/// The distance the camera focuses at: its `focus`, else how far its lookAt point is.-pub fn focus_of(c: &Item) -> f64 {- num(&c.props, "focus").unwrap_or_else(|| {- let (p, l) = (vec3(&c.props, "position", [0.0, 0.0, 5.0]), vec3(&c.props, "lookAt", [0.0, 0.0, 0.0]));- ((p[0] - l[0]).powi(2) + (p[1] - l[1]).powi(2) + (p[2] - l[2]).powi(2)).sqrt().max(0.01)- })-}-/// The paint look's keyed values on one frame (raea-render's look.rs and paint.rs read them): its tone bands, paper grain,/// how far edges wander, the wander's seed (the SDK folds a boil's beat into it), and how far the wind has carried the/// cloud shadows and blown the grass.diff --git a/runtime/look/src/post.rs b/runtime/look/src/post.rsnew file mode 100644index 00000000..b7123d0c--- /dev/null+++ b/runtime/look/src/post.rs@@ -0,0 +1,370 @@+//! The camera's post-processing frame by frame (docs/rerender.feature RR1): the sky, bloom, fog, the grade and+//! vignette, AO and anti-aliasing, shadow quality, volumetric fog, tone mapping and exposure, each frame's as its own+//! parts ask, where every frame had the first frame's that asked for each. So a piece whose shots each have a look of+//! their own renders as one composition, and a frame is the same whichever others the render holds.++use super::*;++/// The camera row's post-processing (`sets`). A frame with no 3D parts holds the set of the 3D frame before it (the+/// first 3D frame's, before any), so a title card doesn't take the effects off the camera and put them back.+pub fn post(all: &[Vec<Item>], p: &mut Program, row: &mut BTreeMap<String, V>, id: &str) {+ let mut held: Option<BTreeMap<String, V>> = all.iter().find(|its| !its.is_empty()).map(|its| frame_post(its));+ let per: Vec<BTreeMap<String, V>> = all+ .iter()+ .map(|its| {+ if !its.is_empty() {+ held = Some(frame_post(its));+ }+ held.clone().unwrap_or_default()+ })+ .collect();+ sets(per, p, row, id);+}++/// A light's colour, shadows and shafts (a volumetric light), frame by frame (`sets`): the night shot's lamps glow in+/// the air and cast shadows, the day's don't, and each shot's sun has its own colour.+pub fn light_sets(its: &[Item], p: &mut Program, row: &mut BTreeMap<String, V>, id: &str) {+ let per = its+ .iter()+ .map(|i| {+ let mut set = BTreeMap::new();+ if let Some(c) = hex(i.props.get("color")).filter(|c| c != "#ffffff") {+ set.insert("color".into(), V::S(c));+ }+ if let Some(Value::Bool(s)) = i.props.get("castShadow") {+ set.insert("shadows".into(), V::N(*s as u8 as f64));+ }+ if i.props.get("volumetric") == Some(&Value::Bool(true)) {+ set.insert("volumetric".into(), V::N(1.0));+ }+ set+ })+ .collect();+ sets(per, p, row, id);+}++/// A row's columns that change as a set, one set a frame (RR1). One set for the whole piece: its columns on the row, as+/// always. Sets that change (a sky in one shot, fog in the next, a grade that ramps): each different one in+/// `frame_sets` (a JSON list of objects) and the frame's index into it in `frame_set_i` (keyed, stepped), which+/// raea-render lays onto the row each frame (raea-sys-frame tables.rs) for the systems that follow it (raea-sys-post's+/// sync for the camera, sync_light_sets for a light).+pub fn sets(per: Vec<BTreeMap<String, V>>, p: &mut Program, row: &mut BTreeMap<String, V>, id: &str) {+ let mut list: Vec<BTreeMap<String, V>> = Vec::new();+ let idx: Vec<f64> = per+ .into_iter()+ .map(|s| {+ (list.iter().position(|x| *x == s).unwrap_or_else(|| {+ list.push(s);+ list.len() - 1+ })) as f64+ })+ .collect();+ if list.len() <= 1 {+ row.extend(list.pop().unwrap_or_default());+ return;+ }+ let json: Vec<Value> = list.iter().map(|s| Value::Object(s.iter().map(|(c, v)| (c.clone(), json_of(v))).collect())).collect();+ row.insert("frame_sets".into(), V::S(Value::Array(json).to_string()));+ row.insert("frame_set_i".into(), V::N(idx[0]));+ p.keys.insert((id.to_string(), "frame_set_i".to_string()), step_keys(&idx));+}++/// Live play's sets (raea-runtime-scene live.rs, a frame at a time): the row's columns `set` names taken off it and put+/// back as a one-set table, so the next frame's set replaces this one whole. A live row keeps every column it was last+/// sent, so a sky, fog or light colour a later frame drops would otherwise stay on (RR1: render = play).+pub fn as_table(row: &mut BTreeMap<String, V>, set: impl Fn(&str) -> bool) {+ let cols: BTreeMap<String, V> = row.iter().filter(|(k, _)| set(k)).map(|(k, v)| (k.clone(), v.clone())).collect();+ row.retain(|k, _| !set(k));+ let json = Value::Array(vec![Value::Object(cols.iter().map(|(c, v)| (c.clone(), json_of(v))).collect())]);+ row.insert("frame_sets".into(), V::S(json.to_string()));+ row.insert("frame_set_i".into(), V::N(0.0));+}++/// A light row's columns that change as a set: its colour, shadows and shafts (light_sets) and its <Shadows>+/// (FrameShadows::light).+pub fn light_set_col(c: &str) -> bool {+ matches!(c, "color" | "shadows" | "volumetric") || c.starts_with("shadow_")+}++/// One value a frame as stepped keys: a key only where it changes (each held until the next key's own frame).+pub fn step_keys(vals: &[f64]) -> Vec<(i64, f64, String)> {+ vals.iter().enumerate().filter(|(f, v)| *f == 0 || **v != vals[f - 1]).map(|(f, v)| (f as i64, *v, "step".to_string())).collect()+}++fn json_of(v: &V) -> Value {+ match v {+ V::N(x) => serde_json::json!(x),+ V::S(s) => Value::String(s.clone()),+ }+}++/// One frame's post-processing columns, from its own parts (the first of each kind).+pub fn frame_post(its: &[Item]) -> BTreeMap<String, V> {+ let mut row = BTreeMap::new();+ let first = |kind: &str| its.iter().find(|i| i.kind == kind).map(|i| &*i.props);+ // depth of field's kind, on the frames that have one (its aperture and focus are keyed columns: camera.rs), so a shot+ // without it draws no blur pass, and each shot's has its own size and mode, not the first one's+ if let Some(d) = first("dof") {+ row.insert("dof_max".into(), V::N(n(d, "maxBlur", 64.0)));+ if d.get("mode").and_then(Value::as_str) == Some("gaussian") {+ row.insert("dof_mode".into(), V::S("gaussian".into()));+ }+ }+ // a procedural sky (<Atmosphere>): Earth's air, lighting the scene too when `light`+ if let Some(a) = first("atmosphere") {+ row.insert("atmosphere".into(), V::N(1.0));+ if a.get("light") == Some(&Value::Bool(true)) {+ row.insert("atmo_light".into(), V::N(1.0));+ }+ if let Some(x) = num(a, "groundAlbedo") {+ row.insert("atmo_albedo".into(), V::N(x));+ }+ }+ if let Some(b) = first("bloom") {+ row.insert("bloom".into(), V::N(r6(n(b, "intensity", 1.0) * BLOOM)));+ if let Some(t) = num(b, "threshold") {+ row.insert("bloom_threshold".into(), V::N(t));+ }+ if let Some(s) = shares(b) {+ row.insert("bloom_passes".into(), V::S(s));+ }+ }+ if let Some(f) = first("fog") {+ row.insert("fog_color".into(), V::S(hex(f.get("color")).unwrap_or("#808080".into())));+ match num(f, "density") {+ Some(d) => {+ row.insert("fog_density".into(), V::N(d));+ }+ None => {+ row.insert("fog_start".into(), V::N(n(f, "near", 5.0)));+ row.insert("fog_end".into(), V::N(n(f, "far", 20.0)));+ }+ }+ }+ if let Some(g) = first("grade") {+ grade(g, &mut row);+ }+ // ambient occlusion (no multisampling with it: SMAA unless asked otherwise) and the anti-aliasing+ let ssao = first("ssao");+ if let Some(a) = ssao {+ row.insert("ssao".into(), V::S(a.get("quality").and_then(Value::as_str).unwrap_or("medium").to_string()));+ if let Some(t) = num(a, "thickness") {+ row.insert("ssao_thickness".into(), V::N(t));+ }+ }+ let aa = first("aa").and_then(|a| a.get("mode")).and_then(Value::as_str);+ match (aa, ssao.is_some()) {+ (Some("msaa") | None, true) => {+ row.insert("aa".into(), V::S("smaa".into()));+ }+ (Some(m), _) if m != "msaa" => {+ row.insert("aa".into(), V::S(m.to_string()));+ }+ _ => {}+ }+ // shadow quality: the map size and the filter on the camera; the cascades and biases go on each light's row+ if let Some(sh) = first("shadows") {+ if let Some(m) = num(sh, "mapSize") {+ row.insert("shadow_map".into(), V::N(m));+ }+ if let Some(f) = sh.get("filter").and_then(Value::as_str) {+ row.insert("shadow_filter".into(), V::S(f.to_string()));+ }+ }+ if let Some(v) = first("volfog") {+ volfog(v, &mut row);+ }+ if let Some(t) = first("tonemapping") {+ if let Some(m) = t.get("mode").and_then(Value::as_str) {+ row.insert("tonemap".into(), V::S(m.to_lowercase()));+ }+ if let Some(e) = num(t, "exposure") {+ row.insert("exposure".into(), V::N(r6(EV100 - e)));+ }+ }+ row+}++/// A <Grade>'s columns: its passes, its colour grading by section and its vignette.+fn grade(g: &Map<String, Value>, row: &mut BTreeMap<String, V>) {+ if let Some(s) = shares(g) {+ row.insert("grade_passes".into(), V::S(s));+ }+ for (k, col) in [("temperature", "grade_temperature"), ("tint", "grade_tint"), ("saturation", "grade_saturation")] {+ if let Some(x) = num(g, k) {+ row.insert(col.into(), V::N(x));+ }+ }+ for (sec, pre) in [("shadows", "grade_s_"), ("midtones", "grade_m_"), ("highlights", "grade_h_")] {+ let Some(o) = g.get(sec).and_then(Value::as_object) else { continue };+ for k in ["saturation", "contrast", "gamma", "gain", "lift"] {+ if let Some(x) = o.get(k).and_then(Value::as_f64) {+ row.insert(format!("{pre}{k}"), V::N(x));+ }+ }+ }+ match g.get("vignette") {+ Some(Value::Number(x)) => {+ row.insert("vignette".into(), V::N(x.as_f64().unwrap_or(0.0)));+ }+ Some(Value::Object(o)) => {+ row.insert("vignette".into(), V::N(o.get("intensity").and_then(Value::as_f64).unwrap_or(1.0)));+ for (k, col) in [("radius", "vignette_radius"), ("smoothness", "vignette_smooth")] {+ if let Some(x) = o.get(k).and_then(Value::as_f64) {+ row.insert(col.into(), V::N(x));+ }+ }+ if let Some(c) = hex(o.get("color")) {+ row.insert("vignette_color".into(), V::S(c));+ }+ }+ _ => {}+ }+}++/// A <VolumetricFog>'s columns.+fn volfog(v: &Map<String, Value>, row: &mut BTreeMap<String, V>) {+ row.insert("vfog".into(), V::N(1.0));+ row.insert("vfog_steps".into(), V::N(n(v, "steps", 64.0)));+ if v.get("dither").and_then(Value::as_bool) == Some(true) {+ row.insert("vfog_dither".into(), V::N(1.0));+ }+ if let Some(r) = num(v, "resolution") {+ row.insert("vfog_resolution".into(), V::N(r));+ }+ if let Some(m) = v.get("mode").and_then(Value::as_str).filter(|m| matches!(*m, "froxel" | "march")) {+ row.insert("vfog_mode".into(), V::S(m.into()));+ }+ if v.get("hero").and_then(Value::as_bool) == Some(false) {+ row.insert("vfog_hero".into(), V::N(0.0));+ }+ for (prop, col) in [("slices", "vfog_slices"), ("tile", "vfog_tile"), ("samples", "vfog_samples")] {+ if let Some(x) = num(v, prop) {+ row.insert(col.into(), V::N(x));+ }+ }+ row.insert("vfog_ambient".into(), V::N(n(v, "ambient", 0.0)));+ if let Some(c) = hex(v.get("ambientColor")) {+ row.insert("vfog_ambient_color".into(), V::S(c));+ }+}++/// Each frame's <Shadows> (found once for every light): its props, and whether they change from frame to frame.+pub struct FrameShadows<'a> {+ per: Vec<Option<&'a Map<String, Value>>>,+ varies: bool,+}++impl<'a> FrameShadows<'a> {+ pub fn of(all: &'a [Vec<Item>]) -> FrameShadows<'a> {+ let per: Vec<Option<&Map<String, Value>>> = all.iter().map(|its| its.iter().find(|i| i.kind == "shadows").map(|i| &*i.props)).collect();+ let varies = per.windows(2).any(|w| w[0] != w[1]);+ FrameShadows { per, varies }+ }++ /// A light's shadow cascades (the sun's: light.rs reads them for it alone) and biases (every light's) from the+ /// frame's <Shadows> (RR1). One <Shadows> for the whole piece: its values on the row, as always. Ones that change:+ /// keyed, a frame without one at raea's cascades and Bevy's biases for the light's kind (0.02 / 1.8, a bulb's+ /// 0.08 / 0.6). A bias the light gives itself stays over them, unkeyed.+ pub fn light(&self, p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, kind: &str, own: &Map<String, Value>) {+ let bulb = kind == "point";+ let cols = [+ ("distance", "shadow_dist", 150.0, None),+ ("firstCascade", "shadow_first", 8.0, None),+ ("cascades", "shadow_cascades", 4.0, None),+ ("overlap", "shadow_overlap", 0.3, None),+ ("bias", "shadow_bias", if bulb { 0.08 } else { 0.02 }, Some("shadow_depth_bias")),+ ("normalBias", "shadow_nbias", if bulb { 0.6 } else { 1.8 }, Some("shadow_normal_bias")),+ ];+ for (prop, col, d, mine) in cols {+ if mine.is_some_and(|m| own.contains_key(m)) {+ continue;+ }+ if !self.varies {+ if let Some(x) = self.per.iter().flatten().next().and_then(|sh| num(sh, prop)) {+ row.insert(col.into(), V::N(x));+ }+ continue;+ }+ column(p, row, id, col, &self.per.iter().map(|sh| sh.and_then(|sh| num(sh, prop)).unwrap_or(d)).collect::<Vec<_>>());+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn item(kind: &'static str, props: Value) -> Item {+ Item { kind, props: std::sync::Arc::new(props.as_object().cloned().unwrap_or_default()), shape: None, material: None, world: Default::default() }+ }++ #[test]+ fn each_frame_takes_its_own_post_processing() {+ let sun = item("light", serde_json::json!({}));+ let sky = vec![sun.clone(), item("atmosphere", serde_json::json!({"light": true})), item("bloom", serde_json::json!({"intensity": 0.35}))];+ let fog = vec![sun.clone(), item("fog", serde_json::json!({"color": "#c9ced4", "near": 10, "far": 90}))];+ // shot 1 (sky, bloom) for 3 frames, a title card with no 3D, shot 2 (fog) for 2 frames+ let all = vec![sky.clone(), sky.clone(), sky, vec![], fog.clone(), fog];+ let (mut p, mut row) = (Program::default(), BTreeMap::new());+ post(&all, &mut p, &mut row, "cam");+ let list: Vec<Value> = match row.get("frame_sets") {+ Some(V::S(s)) => serde_json::from_str(s).unwrap(),+ _ => panic!("no frame_sets: {row:?}"),+ };+ assert_eq!(list.len(), 2);+ assert!(list[0].get("atmosphere").is_some() && list[0].get("fog_color").is_none());+ assert!(list[1].get("fog_color").is_some() && list[1].get("bloom").is_none());+ // the title card holds shot 1's set; the key steps to shot 2's on its first frame+ assert_eq!(p.keys[&("cam".to_string(), "frame_set_i".to_string())], vec![(0, 0.0, "step".to_string()), (4, 1.0, "step".to_string())]);+ assert!(!row.contains_key("bloom"), "a changing set's columns are in the list, not on the row");+ }++ #[test]+ fn a_light_takes_each_frames_shadow_cascades() {+ // the interior shot's 20 m cascades between two 120 m shots, and a frame with no <Shadows>+ let sh = |d: f64| vec![item("shadows", serde_json::json!({"distance": d, "bias": 0.01}))];+ let all = vec![sh(120.0), sh(20.0), sh(120.0), vec![]];+ let (mut p, mut row) = (Program::default(), BTreeMap::new());+ let own = serde_json::json!({"shadow_normal_bias": 1.0}).as_object().cloned().unwrap();+ FrameShadows::of(&all).light(&mut p, &mut row, "sun0", "directional", &own);+ let keys = |c: &str| p.keys.get(&("sun0".to_string(), c.to_string())).map(|k| k.iter().map(|(f, v, _)| (*f, *v)).collect::<Vec<_>>());+ assert_eq!(keys("shadow_dist"), Some(vec![(0, 120.0), (1, 20.0), (2, 120.0), (3, 150.0)]));+ assert_eq!(keys("shadow_bias").map(|k| k.last().copied()), Some(Some((3, 0.02))));+ // the light's own normal bias is its own on every frame+ assert!(keys("shadow_nbias").is_none() && !row.contains_key("shadow_nbias"));+ // one <Shadows> throughout: on the row, unkeyed+ let (mut p, mut row) = (Program::default(), BTreeMap::new());+ FrameShadows::of(&[sh(20.0), sh(20.0)]).light(&mut p, &mut row, "sun0", "directional", &Map::new());+ assert_eq!(row.get("shadow_dist"), Some(&V::N(20.0)));+ assert!(p.keys.is_empty());+ }++ #[test]+ fn one_set_for_the_whole_piece_stays_on_the_row() {+ let shot = vec![item("bloom", serde_json::json!({"intensity": 0.5})), item("tonemapping", serde_json::json!({"mode": "AgX"}))];+ let (mut p, mut row) = (Program::default(), BTreeMap::new());+ post(&[shot.clone(), vec![], shot], &mut p, &mut row, "cam");+ assert!(row.contains_key("bloom") && row.get("tonemap") == Some(&V::S("agx".into())));+ assert!(!row.contains_key("frame_sets") && p.keys.is_empty());+ }+}++/// What a live frame's light sets (as_table) are made from: each light's colour, shadows, shafts and own biases, and the+/// frame's <Shadows>.+pub fn light_sig(its: &[Item]) -> String {+ let mut s = String::new();+ for it in its.iter().filter(|i| matches!(i.kind, "directional" | "point" | "spot" | "rect" | "shadows")) {+ s.push_str(it.kind);+ for k in ["color", "castShadow", "volumetric", "shadow_depth_bias", "shadow_normal_bias"] {+ if let Some(v) = it.props.get(k) {+ s.push_str(&format!("|{k}={v}"));+ }+ }+ if it.kind == "shadows" {+ s.push_str(&Value::Object((*it.props).clone()).to_string());+ }+ s.push(';');+ }+ s+}diff --git a/runtime/scene/src/fast.rs b/runtime/scene/src/fast.rsindex 5fe39b5c..faa2abc5 100644--- a/runtime/scene/src/fast.rs+++ b/runtime/scene/src/fast.rs@@ -25,6 +25,10 @@ impl LiveScene {return None;}let its = items_of(f.scene);+ // a light's colour, shadows or shafts changed (its set, as_table): the full path, which makes them+ if light_sig(&its) != self.light_sig {+ return None;+ }// pass 1: every part's id (as tracks_of names it on one frame), or None before anything changeslet mut parts: Vec<(usize, &String)> = Vec::with_capacity(its.len());// each group's (kind, name) counts and the key, borrowed and written in place (ZeroHeap)diff --git a/runtime/scene/src/lib.rs b/runtime/scene/src/lib.rsindex e53da61b..a764c284 100644--- a/runtime/scene/src/lib.rs+++ b/runtime/scene/src/lib.rs@@ -12,7 +12,7 @@ use raea_core_program::ir::{Program, V};use serde_json::{Map, Value};use raea_core_scene::*;-pub use raea_runtime_look::{camera, column};+pub use raea_runtime_look::{camera, column, rgba_of};use raea_runtime_look::*;mod parts;@@ -224,18 +224,6 @@ pub fn items_of(scene: &[Node3]) -> Vec<Item> {}-/// A part's composition pass on each frame (`pass`: 0 "scene", from 1 the piece's passes), stepped.-fn pass_column(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item], names: &[String]) {- if names.is_empty() || !its.iter().any(|i| i.props.contains_key("pass")) {- return;- }- let ids: Vec<f64> = its.iter().map(|i| i.props.get("pass").and_then(Value::as_str).and_then(|n| names.iter().position(|x| x == n)).map_or(0.0, |k| (k + 1) as f64)).collect();- row.insert("pass".into(), V::N(ids[0]));- if !ids.iter().all(|v| *v == ids[0]) {- p.keys.insert((id.to_string(), "pass".to_string()), ids.iter().enumerate().map(|(f, v)| (f as i64, *v, "step".to_string())).collect());- }-}-/// World position, rotation (Bevy's quaternion, q_x q_y q_z q_w: no Euler round trip, docs/control.feature FC1d) and/// scale of each frame; each frame's quaternion takes the sign nearer the frame before's, so keys turn the short way.fn placement(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item]) {diff --git a/runtime/scene/src/live.rs b/runtime/scene/src/live.rsindex 5cbbdef4..6166ea52 100644--- a/runtime/scene/src/live.rs+++ b/runtime/scene/src/live.rs@@ -27,6 +27,9 @@ pub struct LiveScene {pub warm: bool,/// identity -> a panel's `src` as written when the full path last made its row (the fast path leaves it a new one)pub(crate) panel_srcs: std::collections::HashMap<String, String>,+ /// what the lights' sets were made from when the full path last made them (light_sig): the fast path, which+ /// doesn't make them, goes the full way when it differs+ pub(crate) light_sig: String,}#[derive(Clone)]@@ -57,7 +60,7 @@ pub(crate) const MORPH_COLS: [&str; 64] = ["morph0", "morph1", "morph2", "morph3/// The columns a frame may change, per kind (what `rows_into` and `camera` key); everything else is the first frame's.pub(crate) fn live_dynamic(kind: &str) -> &'static [&'static str] {match kind {- "light" => &["lux", "lumens", "x", "y", "z", "dir_x", "dir_y", "dir_z", "rot_qx", "rot_qy", "rot_qz", "rot_qw", "inner", "outer"],+ "light" => &["lux", "lumens", "x", "y", "z", "dir_x", "dir_y", "dir_z", "rot_qx", "rot_qy", "rot_qz", "rot_qw", "inner", "outer", "frame_sets", "frame_set_i"],"mesh" => &["x", "y", "z", "q_x", "q_y", "q_z", "q_w", "scale_x", "scale_y", "scale_z", "visible", "col_r", "col_g", "col_b", "rough", "metal", "emissive_k", "opacity", "sh_r", "sh_g", "sh_b", "rim_k", "spec_k", "outline_w", "pass"],"model" => &["x", "y", "z", "q_x", "q_y", "q_z", "q_w", "scale_x", "scale_y", "scale_z", "visible", "anim_t", "mix0_t", "mix0_w", "mix1_t", "mix1_w", "mix2_t", "mix2_w", "mix3_t", "mix3_w", "morph0", "morph1", "morph2", "morph3", "morph4", "morph5", "morph6", "morph7", "morph8", "morph9", "morph10", "morph11", "morph12", "morph13", "morph14", "morph15", "morph16", "morph17", "morph18", "morph19", "morph20", "morph21", "morph22", "morph23", "morph24", "morph25", "morph26", "morph27", "morph28", "morph29", "morph30", "morph31", "morph32", "morph33", "morph34", "morph35", "morph36", "morph37", "morph38", "morph39", "morph40", "morph41", "morph42", "morph43", "morph44", "morph45", "morph46", "morph47", "morph48", "morph49", "morph50", "morph51", "morph52", "morph53", "morph54", "morph55", "morph56", "morph57", "morph58", "morph59", "morph60", "morph61", "morph62", "morph63", "g0_w", "g0_t", "g1_w", "g1_t", "g2_w", "g2_t", "g3_w", "g3_t", "g4_w", "g4_t", "g5_w", "g5_t", "g6_w", "g6_t", "g7_w", "g7_t", "g8_w", "g8_t", "g9_w", "g9_t", "g10_w", "g10_t", "g11_w", "g11_t", "g12_w", "g12_t", "g13_w", "g13_t", "g14_w", "g14_t", "g15_w", "g15_t", "look", "glitch_explode", "glitch_scramble", "glitch_jitter", "glitch_snap", "glitch_smear_x", "glitch_smear_y", "glitch_smear_z", "glitch_seed", "cloth_frame", "screen_power", "pass"],"panel" => &["x", "y", "z", "q_x", "q_y", "q_z", "q_w", "scale_x", "scale_y", "scale_z", "visible", "screen_power", "screen_bright", "pass", "sheet_frame", "sheet_cols", "sheet_rows", "src"],@@ -89,9 +92,20 @@ impl LiveScene {// the holder's background as the clear colour; with none, Bevy's ClearColor resource (srgb 43, 44, 47 unless a// <BevyResource type="bevy_camera::clear_color::ClearColor"> sets it), not black (docs/control conventions C17)if let Some(bg) = clear.and_then(hex_of) {+ // and keyed frame by frame (bg_r..bg_a, sRGB), as a render keys a holder's background that changes: each+ // frame's own, where play held the first frame's (RR1: render = play)+ if let Some(c) = rgba_of(&bg) {+ for (k, name) in ["bg_r", "bg_g", "bg_b", "bg_a"].into_iter().enumerate() {+ cam.insert(name.into(), V::N(r6(c[k])));+ }+ }cam.insert("bg".into(), V::S(bg));}camera(all, p, &mut cam);+ // its post-processing as a table, so a frame's sky, fog, grade or depth of field replaces the last whole+ // (as_table; depth of field's aperture and focus stay keyed columns, so a pull doesn't change the set)+ let set = frame_post(&all[0]);+ as_table(&mut cam, |k| set.contains_key(k));// an <Environment>'s panoramas: every one shown so far, as a render's row lists them all (#38)env_shown(self.cam.get("env_srcs"), &mut cam);if !all[0].iter().any(|i| i.kind == "camera") {@@ -108,7 +122,9 @@ impl LiveScene {/// What the camera row changes, of the columns a render keys (cam_keyed): the camera's tuple, or None.pub(crate) fn camera_diff(sent: &mut BTreeMap<String, V>, cam: &BTreeMap<String, V>) -> Option<raea_core_program::eval::Tup> {let mut vals = BTreeMap::new();- for k in cam.keys().map(String::as_str).filter(|k| cam_keyed(k)).chain(["ambient"]) {+ // and each frame's post-processing table and page background (RR1: render = play)+ let keyed = |k: &str| cam_keyed(k) || matches!(k, "frame_sets" | "frame_set_i" | "bg_r" | "bg_g" | "bg_b" | "bg_a");+ for k in cam.keys().map(String::as_str).filter(|k| keyed(k)).chain(["ambient"]) {let v = cam.get(k).cloned().or_else(|| (k == "ambient" && sent.contains_key("ambient")).then_some(V::N(0.0)));if let Some(v) = v {if sent.get(k) != Some(&v) {@@ -124,6 +140,7 @@ impl LiveScene {/// by identity, with the row ids this scene keeps.pub(crate) fn current(&mut self, f: Shot) -> (BTreeMap<String, V>, Vec<(String, String, BTreeMap<String, V>)>) {let all = vec![items_of(f.scene)];+ self.light_sig = light_sig(&all[0]);// the camera's own spawns (its fog, sky...) in the frame's program with the restlet mut p = Program::default();let cam = self.camera_row(&all, f.clear, &mut p);@@ -176,6 +193,10 @@ impl LiveScene {};live_id.insert(lid.clone(), id.clone());row.insert("id".into(), V::S(id.clone()));+ // a light's colour, shadows and shafts as a table, so a frame's replaces the last whole (as_table)+ if kind == "light" {+ as_table(&mut row, light_set_col);+ }out.push((kind.clone(), id, row));}}diff --git a/runtime/scene/src/parts.rs b/runtime/scene/src/parts.rsindex 16829b57..f33c1cf9 100644--- a/runtime/scene/src/parts.rs+++ b/runtime/scene/src/parts.rs@@ -36,9 +36,9 @@ fn shader_row(id: String, it: &Item) -> BTreeMap<String, V> {/// lights: directional (towards its target, the origin by default), point, spotpub(crate) fn lights_rows(all: &[Vec<Item>], tr: &Tracks, p: &mut Program) {let mut li = 0;- // a <Shadows>, found once: every light takes its cascades and biases (looking for it per light scanned every- // frame's items once a light, 100 000 lights by 100 000 items)- let shadows = all.iter().flatten().find(|i| i.kind == "shadows");+ // each frame's <Shadows>, found once: every light takes its cascades and biases (looking for it per light scanned+ // every frame's items once a light, 100 000 lights by 100 000 items)+ let shadows = FrameShadows::of(all);for (_, track) in &tr.lights {let its = filled(&track);let kind = its[0].kind;@@ -77,15 +77,8 @@ pub(crate) fn lights_rows(all: &[Vec<Item>], tr: &Tracks, p: &mut Program) {}}let first = &its[0].props;- if let Some(c) = hex(first.get("color")).filter(|c| c != "#ffffff") {- row.insert("color".into(), V::S(c));- }- if let Some(Value::Bool(s)) = first.get("castShadow") {- row.insert("shadows".into(), V::N(*s as u8 as f64));- }- if first.get("volumetric") == Some(&Value::Bool(true)) {- row.insert("volumetric".into(), V::N(1.0));- }+ // its colour, shadows and shafts, each frame's (RR1)+ light_sets(&its, p, &mut row, &id);// a point or spot light the paint look draws (paint.rs)if kind != "directional" && first.get("paint") == Some(&Value::Bool(true)) {row.insert("paint".into(), V::N(1.0));@@ -99,14 +92,8 @@ pub(crate) fn lights_rows(all: &[Vec<Item>], tr: &Tracks, p: &mut Program) {if let Some(r) = soft.filter(|r| *r > 0.0) {row.insert("soft".into(), V::N(r));}- // a <Shadows>' cascades (the sun's) and biases (every light's)- if let Some(sh) = shadows {- for (prop, col) in [("distance", "shadow_dist"), ("firstCascade", "shadow_first"), ("cascades", "shadow_cascades"), ("overlap", "shadow_overlap"), ("bias", "shadow_bias"), ("normalBias", "shadow_nbias")] {- if let Some(x) = num(&sh.props, prop) {- row.insert(col.into(), V::N(x));- }- }- }+ // each frame's <Shadows>' cascades (the sun's) and biases (every light's), RR1+ shadows.light(p, &mut row, &id, kind, first);// the light's own biases (Bevy's shadow_depth_bias, shadow_normal_bias), over a <Shadows>'for (prop, col) in [("shadow_depth_bias", "shadow_bias"), ("shadow_normal_bias", "shadow_nbias")] {if let Some(x) = num(first, prop) {diff --git a/runtime/scene3d/Cargo.toml b/runtime/scene3d/Cargo.tomlindex ab8be656..17eb01d0 100644--- a/runtime/scene3d/Cargo.toml+++ b/runtime/scene3d/Cargo.toml@@ -16,7 +16,6 @@ raea-sys-shader = { path = "../../systems/shader" }raea-sys-fog = { path = "../../systems/fog" }raea-sys-fog-half = { path = "../../systems/fog-half" }raea-sys-post = { path = "../../systems/post" }-raea-sys-compose = { path = "../../systems/compose" }raea-sys-look = { path = "../../systems/look" }raea-runtime-plugins = { path = "../plugins" }raea-core-program = { path = "../../core/program" }diff --git a/runtime/scene3d/src/camera.rs b/runtime/scene3d/src/camera.rsindex 9a68b7a4..2cad2d9a 100644--- a/runtime/scene3d/src/camera.rs+++ b/runtime/scene3d/src/camera.rs@@ -1,4 +1,10 @@use super::*;+pub use raea_sys_fog_half::camera::{FogDither, VFOG, fog_reference, sync_fog_dither};++/// Each camera's post-processing as this frame's row has it (raea-sys-post camera.rs), volumetric fog's group with it.+pub fn sync_post(world: &mut World) {+ raea_sys_post::camera::sync(world, &[VFOG]);+}/// A sprite sheet's cell `frame` of `cols` x `rows` (0 the top left, read along each row) as a card's UV transform.pub fn sheet_uv(frame: f32, cols: f32, rows: f32) -> bevy::math::Affine2 {@@ -13,208 +19,18 @@ pub fn up_for(dir: Vec3) -> Vec3 {if dir.normalize_or_zero().cross(Vec3::Y).length_squared() < 1e-6 { Vec3::Z } else { Vec3::Y }}-/// The camera row's lens and post-processing.+/// The camera row's layers, order, clear and projection, and its post-processing (raea-sys-post camera.rs).pub fn camera(world: &mut World, e: Entity, vals: &BTreeMap<String, V>) {let g = |k: &str, d: f32| num(vals, k, d);layers(world, e, vals);// its order, clear and viewport among the cameras on its target (<Camera3d order clear_color viewport>)raea_sys_frame::camera::camera_pass(world, e, vals);- // shadow quality (a <Shadows>): the sun's and spots' maps are 4096 texels a side unless it says otherwise (Bevy's- // 2048 speckles and blurs a film's shadows; smaller on a GPU with little memory of its own, raea_sys_frame::shadow);- // point lights' cube maps half that, 1024 by default as Bevy's- if !preview() {- let size = match vals.get("shadow_map") { Some(V::N(n)) => *n as usize, _ => raea_sys_frame::shadow::shadow_map_default(world) };- if let Some(mut m) = world.get_resource_mut::<bevy::light::DirectionalLightShadowMap>() {- m.size = size;- }- if let Some(mut m) = world.get_resource_mut::<bevy::light::PointLightShadowMap>() {- m.size = if vals.contains_key("shadow_map") { size / 2 } else { 1024 };- }- }- let filter = match vals.get("shadow_filter") { Some(V::S(s)) if s == "hardware" => bevy::light::ShadowFilteringMethod::Hardware2x2, _ => bevy::light::ShadowFilteringMethod::Gaussian };- world.entity_mut(e).insert(filter);if vals.contains_key("near") || vals.contains_key("far") {let fov = g("fov", 45.0).to_radians();world.entity_mut(e).insert(Projection::Perspective(PerspectiveProjection { fov, near: g("near", 0.1), far: g("far", 1000.0), ..default() }));}- // a procedural sky (<Atmosphere>): Bevy 0.20's scattering atmosphere, Earth's air round a planet whose- // ground is at y 0, lit by the suns; its sky drawn behind everything, and with `atmo_light` it lights the scene too- // (AtmosphereEnvironmentMapLight). AtmosphereSettings needs Hdr, which it brings- if vals.get("atmosphere").is_some_and(V::truthy) {- use bevy::light::{atmosphere::ScatteringMedium, Atmosphere};- let medium = world.resource_mut::<Assets<ScatteringMedium>>().add(ScatteringMedium::earth(256, 256));- let mut atmo = Atmosphere::earth(medium);- if let Some(a) = vals.get("atmo_albedo").map(V::num) {- atmo.ground_albedo = Vec3::splat(a as f32);- }- world.spawn((atmo, super::Mirror));- world.entity_mut(e).insert(bevy::pbr::AtmosphereSettings::default());- if vals.get("atmo_light").is_some_and(V::truthy) {- world.entity_mut(e).insert(bevy::light::AtmosphereEnvironmentMapLight::default());- }- }- let bloom = g("bloom", 0.0);- if bloom > 0.0 {- let mut b = bevy::post_process::bloom::Bloom::NATURAL;- b.intensity = bloom;- if let Some(th) = vals.get("bloom_threshold").map(V::num) {- b.prefilter.threshold = th as f32;- b.prefilter.threshold_softness = 0.2;- }- world.entity_mut(e).insert(b);- }- if vals.contains_key("fog_color") || vals.contains_key("fog_end") || vals.contains_key("fog_density") {- let falloff = match vals.get("fog_density") {- Some(d) => FogFalloff::Exponential { density: d.num() as f32 },- None => FogFalloff::Linear { start: g("fog_start", 5.0), end: g("fog_end", 20.0) },- };- world.entity_mut(e).insert(DistanceFog { color: colour(vals.get("fog_color"), [0.5, 0.5, 0.55, 1.0]), falloff, ..default() });- }- if let Some(f) = vals.get("dof_aperture").map(V::num) {- use bevy::post_process::dof::{DepthOfField, DepthOfFieldMode};- let mode = if matches!(vals.get("dof_mode"), Some(V::S(m)) if m == "gaussian") { DepthOfFieldMode::Gaussian } else { DepthOfFieldMode::Bokeh };- // the background counts as far as the camera sees, not infinitely far (its blur would be the largest)- world.entity_mut(e).insert(DepthOfField { mode, focal_distance: g("focus", 5.0), aperture_f_stops: f as f32, max_circle_of_confusion_diameter: g("dof_max", 64.0), max_depth: g("far", 100.0), ..default() });- }- if let Some(V::S(tm)) = vals.get("tonemap") {- use bevy::core_pipeline::tonemapping::Tonemapping as T;- let t = match tm.as_str() {- "none" => T::None,- "reinhard" => T::Reinhard,- "aces" => T::AcesFitted,- "agx" => T::AgX,- "neutral" | "blender" => T::BlenderFilmic,- _ => T::TonyMcMapface,- };- // "none" draws as Bevy 0.19's None did (bevy_api::Untonemapped)- if t == T::None {- world.entity_mut(e).insert((t, super::bevy_api::Untonemapped));- } else {- world.entity_mut(e).insert(t).remove::<super::bevy_api::Untonemapped>();- }- }- if let Some(ev) = vals.get("exposure") {- world.entity_mut(e).insert(bevy::camera::Exposure { ev100: ev.num() as f32 });- }- // a <Grade>: Bevy's colour grading (before tone mapping, but for the global saturation), vignette and fringes- if vals.keys().any(|k| k.starts_with("grade_")) {- use bevy::render::view::{ColorGrading, ColorGradingSection};- let mut cg = ColorGrading::default();- cg.global.temperature = g("grade_temperature", 0.0);- cg.global.tint = g("grade_tint", 0.0);- cg.global.post_saturation = g("grade_saturation", 1.0);- for (pre, sec) in [("grade_s_", &mut cg.shadows), ("grade_m_", &mut cg.midtones), ("grade_h_", &mut cg.highlights)] {- let d = ColorGradingSection::default();- *sec = ColorGradingSection {- saturation: g(&format!("{pre}saturation"), d.saturation),- contrast: g(&format!("{pre}contrast"), d.contrast),- gamma: g(&format!("{pre}gamma"), d.gamma),- gain: g(&format!("{pre}gain"), d.gain),- lift: g(&format!("{pre}lift"), d.lift),- };- }- world.entity_mut(e).insert(cg);- }- if let Some(v) = vals.get("vignette").map(V::num) {- use bevy::post_process::effect_stack::Vignette;- let d = Vignette::default();- world.entity_mut(e).insert(Vignette {- intensity: v as f32,- radius: g("vignette_radius", d.radius),- smoothness: g("vignette_smooth", d.smoothness),- color: colour(vals.get("vignette_color"), [0.0, 0.0, 0.0, 1.0]),- ..d- });- }- // ink outlines from the depth and normal prepasses (Msaa::Off, set where the camera is made)- if vals.contains_key("outline") {- let line = colour(vals.get("outline"), [0.0, 0.0, 0.0, 1.0]).to_linear().to_f32_array();- world.entity_mut(e).insert((- super::outline::InkOutline { color: Vec4::from_array(line), depth: g("outline_depth", 0.04), normal: g("outline_normal", 0.3), width: g("outline_width", 1.0).max(1.0), far: g("outline_far", 0.0) / g("near", 0.1), skip: super::compose::bits(vals, "outline_skip") },- bevy::core_pipeline::prepass::DepthPrepass,- bevy::core_pipeline::prepass::NormalPrepass,- ));- }- // ambient occlusion (Msaa::Off, set where the camera is made; its noise is a fixed pattern without TAA's jitter, so- // a frame's occlusion is a function of its rows) and the anti-aliasing that replaces multisampling- if let Some(V::S(q)) = vals.get("ssao").filter(|_| !preview()) {- use bevy::pbr::{ScreenSpaceAmbientOcclusion, ScreenSpaceAmbientOcclusionQualityLevel as Q};- let quality_level = match q.as_str() { "low" => Q::Low, "high" => Q::High, "ultra" => Q::Ultra, _ => Q::Medium };- world.entity_mut(e).insert(ScreenSpaceAmbientOcclusion {- quality_level,- constant_object_thickness: g("ssao_thickness", 0.25),- // the radius is Bevy's default (0.20's is 0.19's hard-coded 0.5 x 1.457)- ..default()- });- }- match vals.get("aa") {- Some(V::S(m)) if m == "smaa" && !preview() => {- world.entity_mut(e).insert(bevy::anti_alias::smaa::Smaa { preset: bevy::anti_alias::smaa::SmaaPreset::High });- }- Some(V::S(m)) if m == "fxaa" && !preview() => {- world.entity_mut(e).insert(bevy::anti_alias::fxaa::Fxaa::default());- }- _ => {}- }- // volumetric fog: light in the air inside each fog volume. Its jitter is raea's dither (install_fog_shader): 0- // here, and with `vfog_dither` set each frame by sync_fog_dither from the film frame, so a frame's fog is a- // function of the frame either way- // (none when drawing a pass: passes.rs)- if vals.get("vfog").is_some_and(V::truthy) && super::passes::wanted().is_none() {- // RAEA_FOG_REFERENCE=1: the fog's ground truth (sdk/raea/bench/bevy/fog-score.py scores against it): Bevy's- // march at 512 steps (RAEA_FOG_REFERENCE_STEPS), undithered, at full resolution, whatever the composition asks- // for. Converged by then (the rome curia: 256 against 512 SSIM 0.99988); 1024 at 1080p runs past what Metal- // lets one pass take and the fog pass is dropped without an error, the frame drawn with no fog at all- let reference = fog_reference();- let fog = bevy::light::VolumetricFog {- step_count: if reference { std::env::var("RAEA_FOG_REFERENCE_STEPS").ok().and_then(|v| v.parse().ok()).unwrap_or(512) } else { g("vfog_steps", 64.0).round().max(1.0) as u32 },- ambient_intensity: g("vfog_ambient", 0.0),- ambient_color: colour(vals.get("vfog_ambient_color"), [1.0, 1.0, 1.0, 1.0]),- jitter: 0.0,- };- // every volume in one grid along the view (froxel.rs), unless vfog_mode is march (or RAEA_FOG_MODE=march, for- // comparing): Bevy's march, where vfog_resolution below 1 marches at that fraction of the frame, upsampled by- // depth (fog_half.rs). The grid scored at or above the march on every scene fog-score.py judges (the- // fixtures, the rome film's plot and curia, Mean Streets), in SSIM, PSNR, ms a frame and bitrate, so it's the- // default; RAEA_FOG_MODE=froxel forces it over a march row- let env_mode = std::env::var("RAEA_FOG_MODE");- let march = vals.get("vfog_mode").is_some_and(|m| matches!(m, V::S(s) if s == "march")) && env_mode.as_deref() != Ok("froxel");- let froxel = !reference && !march && env_mode.as_deref() != Ok("march");- if froxel {- let lin = fog.ambient_color.to_linear();- super::froxel::insert(- world,- e,- super::froxel::FroxelFog {- ambient: Vec3::new(lin.red, lin.green, lin.blue) * fog.ambient_intensity,- slices: g("vfog_slices", 64.0).round().clamp(32.0, 256.0) as u32,- tile: g("vfog_tile", 16.0).round().clamp(4.0, 16.0) as u32,- samples: g("vfog_samples", 1.0).round().clamp(1.0, 8.0) as u32,- // (the ground truth integrates every light itself)- hero: g("vfog_hero", 1.0) != 0.0 && std::env::var("RAEA_FOG_HERO").as_deref() != Ok("0") && super::froxel::reference_steps().is_none(),- },- );- } else {- super::fog_half::insert(world, e, fog, if reference { 1.0 } else { g("vfog_resolution", 1.0) });- if !reference && vals.get("vfog_dither").is_some_and(V::truthy) {- world.entity_mut(e).insert(FogDither);- }- }- }- if let Some(a) = vals.get("aberration").map(V::num) {- use bevy::post_process::effect_stack::ChromaticAberration;- // its intensity is each frame's (sync_camera)- world.entity_mut(e).insert(ChromaticAberration { intensity: a as f32, ..default() });- }- if super::lens::has_lens(vals) {- // Fisheye / LensDistortion: its values come from each frame's row (sync_camera)- world.entity_mut(e).insert(super::lens::Lens::default());- }-}--/// Whether RAEA_FOG_REFERENCE asks for the fog's ground truth instead of what the composition asks for.-pub fn fog_reference() -> bool {- std::env::var("RAEA_FOG_REFERENCE").is_ok_and(|v| v == "1")+ // the post-processing, put on again on any frame whose row changes it (raea-sys-post camera.rs, RR1)+ raea_sys_post::camera::apply(world, e, vals, &[VFOG]);}/// raea's volumetric fog shader (volumetric_fog.wesl: Bevy 0.20.0's, its dither seeded from the film frame) over@@ -235,28 +51,3 @@ pub fn install_fog_shader(app: &mut App) {});assert!(swapped, "raea: Bevy no longer embeds bevy_pbr/volumetric_fog/volumetric_fog.wesl (docs/bevy-upgrade.md)");}--/// A camera whose volumetric fog is dithered (`<VolumetricFog dither>`).-#[derive(Component)]-pub struct FogDither;--/// The dither's seed for this frame: Bevy's `jitter`, which raea's shader reads as 1 + the film frame mod 64 (0 is no-/// dither). The film frame, not the engine's update count, so a frame rendered alone and the same frame reached in-/// play march the same samples.-pub fn sync_fog_dither(- clock: Res<super::Clock>,- mut q: Query<&mut bevy::light::VolumetricFog, With<FogDither>>,- mut half: Query<&mut super::fog_half::HalfFog, With<FogDither>>,-) {- let seed = 1.0 + clock.0.rem_euclid(64) as f32;- for mut f in &mut q {- if f.jitter != seed {- f.jitter = seed;- }- }- for mut f in &mut half {- if f.fog.jitter != seed {- f.fog.jitter = seed;- }- }-}diff --git a/runtime/scene3d/src/lib.rs b/runtime/scene3d/src/lib.rsindex 75a71384..7a4ddc59 100644--- a/runtime/scene3d/src/lib.rs+++ b/runtime/scene3d/src/lib.rs@@ -38,9 +38,7 @@ use raea_sys_frame::*;use raea_sys_frame::bevy_api;use raea_sys_material::{decal, surface, toon};use raea_sys_fog::{froxel, froxel_glass};-use raea_sys_fog_half as fog_half;-use raea_sys_post::{lens, outline};-use raea_sys_compose::{compose, passes};+use raea_sys_post::lens;use raea_sys_look::paint;use raea_runtime_plugins as plugins;use bevy::animation::{AnimationPlayer, graph::{AnimationGraph, AnimationGraphHandle, AnimationNodeIndex}};diff --git a/runtime/scene3d/src/light.rs b/runtime/scene3d/src/light.rsindex 3fae9f18..16987f7a 100644--- a/runtime/scene3d/src/light.rs+++ b/runtime/scene3d/src/light.rs@@ -65,16 +65,7 @@ pub fn light(world: &mut World, e: Entity, vals: &BTreeMap<String, V>) {));}_ => {- // cascades fitted to a film's scale, not Bevy's kilometre: the first ends at 8 m, the last at 150 m, and- // neighbours overlap by 0.3 so the seam between them doesn't show (a <Shadows> changes them)- let cascades = bevy::light::CascadeShadowConfigBuilder {- num_cascades: g("shadow_cascades", 4.0).clamp(1.0, 4.0) as usize,- minimum_distance: 0.1,- maximum_distance: g("shadow_dist", 150.0),- first_cascade_far_bound: g("shadow_first", 8.0).min(g("shadow_dist", 150.0)),- overlap_proportion: g("shadow_overlap", 0.3),- }- .build();+ let cascades = cascades(vals);world.entity_mut(e).insert((DirectionalLight {color,@@ -132,6 +123,68 @@ pub fn light(world: &mut World, e: Entity, vals: &BTreeMap<String, V>) {}/// A fog volume row: a unit box of air (Bevy's FogVolume), placed and sized by its transform.+/// A light's colour, shadows and shafts as the frame's row has them, for a light whose row changes them (its+/// `frame_sets`, RR1; light.rs set them once from its first frame): before sync_lights, which turns the shadow maps on+/// and off by CastsShadows.+#[allow(clippy::type_complexity)]+pub fn sync_light_sets(+ frame: Res<FrameRows>,+ mut commands: Commands,+ mut q: Query<(Entity, Option<&mut DirectionalLight>, Option<&mut PointLight>, Option<&mut SpotLight>, Option<&mut bevy::light::RectLight>, &mut CastsShadows, Has<bevy::light::VolumetricLight>)>,+) {+ if frame.looks.is_empty() {+ return;+ }+ for (e, d, p, s, rect, mut casts, shafts) in &mut q {+ if !frame.ix.get(&e).and_then(|r| frame.looks.get(r)).is_some_and(|t| t[1].is_some()) {+ continue;+ }+ let Some(v) = frame.vals(e) else { continue };+ let color = colour(v.get("color"), [1.0, 1.0, 1.0, 1.0]);+ // the light's colour, whichever kind it is, written only when it changes (so it isn't marked changed every frame)+ macro_rules! set_colour {+ ($($l:ident),*) => {$(+ if let Some(mut l) = $l.filter(|l| l.color != color) {+ l.color = color;+ }+ )*};+ }+ set_colour!(d, p, s, rect);+ let volumetric = flag(&v, "volumetric", false) && !preview();+ if volumetric != shafts {+ if volumetric { commands.entity(e).insert(bevy::light::VolumetricLight); } else { commands.entity(e).remove::<bevy::light::VolumetricLight>(); }+ }+ let directional = !matches!(v.get("type"), Some(V::S(t)) if matches!(t.as_str(), "point" | "spot" | "rect"));+ let want = (flag(&v, "shadows", directional) || volumetric) && !preview();+ if casts.0 != want {+ casts.0 = want;+ }+ }+}++/// A sun's shadow cascades, fitted to a film's scale, not Bevy's kilometre: the first ends at 8 m, the last at 150 m, and+/// neighbours overlap by 0.3 so the seam between them doesn't show (a frame's <Shadows> changes them; sync_lights puts+/// a frame's on).+pub fn cascades(vals: &BTreeMap<String, V>) -> bevy::light::CascadeShadowConfig {+ let g = |k: &str, d: f32| num(vals, k, d);+ bevy::light::CascadeShadowConfigBuilder {+ num_cascades: g("shadow_cascades", 4.0).clamp(1.0, 4.0) as usize,+ minimum_distance: 0.1,+ maximum_distance: g("shadow_dist", 150.0),+ first_cascade_far_bound: g("shadow_first", 8.0).min(g("shadow_dist", 150.0)),+ overlap_proportion: g("shadow_overlap", 0.3),+ }+ .build()+}++/// A frame's shadow biases onto a light's, where its row has them (a <Shadows>' or the light's own).+pub fn biases(vals: &BTreeMap<String, V>, depth: &mut f32, normal: &mut f32) -> bool {+ let (b, nb) = (vals.get("shadow_bias").map_or(*depth, |v| v.num() as f32), vals.get("shadow_nbias").map_or(*normal, |v| v.num() as f32));+ let changed = (b, nb) != (*depth, *normal);+ (*depth, *normal) = (b, nb);+ changed+}+pub fn fog_volume(world: &mut World, e: Entity, id: &str, vals: &BTreeMap<String, V>) {let mut fv = bevy::light::FogVolume::default();fog_values(&mut fv, vals);diff --git a/runtime/scene3d/src/sync.rs b/runtime/scene3d/src/sync.rsindex 829fb0de..c3978afc 100644--- a/runtime/scene3d/src/sync.rs+++ b/runtime/scene3d/src/sync.rs@@ -298,13 +298,13 @@ pub fn sync_camera(frame: Res<FrameRows>, edit: Option<Res<Edit>>, mut placed: L/// Lights where the frame's rows put them, as bright as they say.#[allow(clippy::type_complexity)]-pub fn sync_lights(frame: Res<FrameRows>, mut commands: Commands, mut q: Query<(Entity, &mut Transform, Option<&mut DirectionalLight>, Option<&mut PointLight>, Option<&mut SpotLight>, Option<&CastsShadows>, Option<&mut bevy::light::RectLight>, Has<StillSynced>)>) {+pub fn sync_lights(frame: Res<FrameRows>, mut commands: Commands, mut q: Query<(Entity, &mut Transform, Option<&mut DirectionalLight>, Option<&mut PointLight>, Option<&mut SpotLight>, Option<&CastsShadows>, Option<&mut bevy::light::RectLight>, Has<StillSynced>, Option<&mut bevy::light::CascadeShadowConfig>)>) {// a dark light (a frame it isn't in: its power is 0) has its shadow maps off, so no shadow pass is drawn for it. Lit or dark,// every light stays shown: hiding the dark ones (so Bevy doesn't extract them) put the lit volumetric spots' shafts// out, as Bevy 0.19's prepare_lights indexes its spot lights past a count of point lights that the hidden ones// threw off. Dark with its maps on, a film's every shadow-casting light drew them on every frame of every scene// (the rome film: 20 lights, 4096-texel maps; 2026-10-20)- for (e, mut t, d, p, s, casts, rect, synced) in &mut q {+ for (e, mut t, d, p, s, casts, rect, synced, config) in &mut q {if d.is_none() && p.is_none() && s.is_none() && rect.is_none() {continue;}@@ -344,6 +344,11 @@ pub fn sync_lights(frame: Res<FrameRows>, mut commands: Commands, mut q: Query<(if d.shadow_maps_enabled != sh {d.shadow_maps_enabled = sh;}+ // the frame's <Shadows>: its cascades and biases (RR1)+ let (mut b, mut nb) = (d.shadow_depth_bias, d.shadow_normal_bias);+ if biases(v, &mut b, &mut nb) { (d.shadow_depth_bias, d.shadow_normal_bias) = (b, nb); }+ let c = cascades(v);+ if let Some(mut was) = config.filter(|was| was.bounds != c.bounds || was.overlap_proportion != c.overlap_proportion) { *was = c; }}if let Some(mut p) = p {let lm = num(v, "lumens", 1.0e6);@@ -354,6 +359,8 @@ pub fn sync_lights(frame: Res<FrameRows>, mut commands: Commands, mut q: Query<(if p.shadow_maps_enabled != sh {p.shadow_maps_enabled = sh;}+ let (mut b, mut nb) = (p.shadow_depth_bias, p.shadow_normal_bias);+ if biases(v, &mut b, &mut nb) { (p.shadow_depth_bias, p.shadow_normal_bias) = (b, nb); }}if let Some(mut r) = rect {let lm = num(v, "lumens", 1.0e6);@@ -374,6 +381,8 @@ pub fn sync_lights(frame: Res<FrameRows>, mut commands: Commands, mut q: Query<(if s.shadow_maps_enabled != sh {s.shadow_maps_enabled = sh;}+ let (mut b, mut nb) = (s.shadow_depth_bias, s.shadow_normal_bias);+ if biases(v, &mut b, &mut nb) { (s.shadow_depth_bias, s.shadow_normal_bias) = (b, nb); }}}}diff --git a/systems/fog-half/Cargo.toml b/systems/fog-half/Cargo.tomlindex 2357fe26..9349fc98 100644--- a/systems/fog-half/Cargo.toml+++ b/systems/fog-half/Cargo.toml@@ -8,5 +8,8 @@ description = "Volumetric fog marched at a fraction of the frame's resolution an[dependencies]raea-sys-frame = { path = "../frame" }+raea-sys-fog = { path = "../fog" }+raea-sys-compose = { path = "../compose" }+raea-core-program = { path = "../../core/program" }bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }wgpu = "=30.0.1"diff --git a/systems/fog-half/src/camera.rs b/systems/fog-half/src/camera.rsnew file mode 100644index 00000000..4d01f483--- /dev/null+++ b/systems/fog-half/src/camera.rs@@ -0,0 +1,91 @@+//! Volumetric fog on the camera as its row has it, a group of the camera's post-processing (raea_sys_frame::camera::+//! Group): on with the frames whose set has it, taken off and put on again when they change (docs/rerender.feature+//! RR1). Here rather than in raea-sys-post's GROUPS because it puts on this crate's HalfFog, and a system can't use+//! another sideways (tools/layers.toml): raea-runtime-scene3d hands it to raea-sys-post's apply and sync beside them.++use std::collections::BTreeMap;++use bevy::prelude::*;+use raea_core_program::ir::V;+use raea_sys_fog::froxel;+use raea_sys_frame::camera::{Group, remove};+use raea_sys_frame::{colour, num, Clock};++type Vals = BTreeMap<String, V>;++/// The volumetric fog group: every `vfog` column.+pub const VFOG: Group = Group { keys: |k| k.starts_with("vfog"), on: vfog, off: remove::<(froxel::FroxelFog, crate::HalfFog, bevy::light::VolumetricFog, FogDither)> };++/// Volumetric fog: light in the air inside each fog volume. Its jitter is raea's dither (install_fog_shader): 0 here,+/// and with `vfog_dither` set each frame by sync_fog_dither from the film frame, so a frame's fog is a function of the+/// frame either way (none when drawing a pass: passes.rs).+pub fn vfog(world: &mut World, e: Entity, vals: &Vals) {+ if !vals.get("vfog").is_some_and(V::truthy) || raea_sys_compose::passes::wanted().is_some() {+ return;+ }+ // RAEA_FOG_REFERENCE=1: the fog's ground truth (sdk/raea/bench/bevy/fog-score.py scores against it): Bevy's march at+ // 512 steps (RAEA_FOG_REFERENCE_STEPS), undithered, at full resolution, whatever the composition asks for. Converged+ // by then (the rome curia: 256 against 512 SSIM 0.99988); 1024 at 1080p runs past what Metal lets one pass take and+ // the fog pass is dropped without an error, the frame drawn with no fog at all+ let reference = fog_reference();+ let fog = bevy::light::VolumetricFog {+ step_count: if reference { std::env::var("RAEA_FOG_REFERENCE_STEPS").ok().and_then(|v| v.parse().ok()).unwrap_or(512) } else { num(vals, "vfog_steps", 64.0).round().max(1.0) as u32 },+ ambient_intensity: num(vals, "vfog_ambient", 0.0),+ ambient_color: colour(vals.get("vfog_ambient_color"), [1.0, 1.0, 1.0, 1.0]),+ jitter: 0.0,+ };+ // every volume in one grid along the view (froxel.rs), unless vfog_mode is march (or RAEA_FOG_MODE=march, for+ // comparing): Bevy's march, where vfog_resolution below 1 marches at that fraction of the frame, upsampled by depth+ // (fog_half.rs). The grid scored at or above the march on every scene fog-score.py judges (the fixtures, the rome+ // film's plot and curia, Mean Streets), in SSIM, PSNR, ms a frame and bitrate, so it's the default;+ // RAEA_FOG_MODE=froxel forces it over a march row+ let env_mode = std::env::var("RAEA_FOG_MODE");+ let march = vals.get("vfog_mode").is_some_and(|m| matches!(m, V::S(s) if s == "march")) && env_mode.as_deref() != Ok("froxel");+ let grid = !reference && !march && env_mode.as_deref() != Ok("march");+ if grid {+ let lin = fog.ambient_color.to_linear();+ froxel::insert(+ world,+ e,+ froxel::FroxelFog {+ ambient: Vec3::new(lin.red, lin.green, lin.blue) * fog.ambient_intensity,+ slices: num(vals, "vfog_slices", 64.0).round().clamp(32.0, 256.0) as u32,+ tile: num(vals, "vfog_tile", 16.0).round().clamp(4.0, 16.0) as u32,+ samples: num(vals, "vfog_samples", 1.0).round().clamp(1.0, 8.0) as u32,+ // (the ground truth integrates every light itself)+ hero: num(vals, "vfog_hero", 1.0) != 0.0 && std::env::var("RAEA_FOG_HERO").as_deref() != Ok("0") && froxel::reference_steps().is_none(),+ },+ );+ } else {+ crate::insert(world, e, fog, if reference { 1.0 } else { num(vals, "vfog_resolution", 1.0) });+ if !reference && vals.get("vfog_dither").is_some_and(V::truthy) {+ world.entity_mut(e).insert(FogDither);+ }+ }+}++/// Whether RAEA_FOG_REFERENCE asks for the fog's ground truth instead of what the composition asks for.+pub fn fog_reference() -> bool {+ std::env::var("RAEA_FOG_REFERENCE").is_ok_and(|v| v == "1")+}++/// A camera whose volumetric fog is dithered (`<VolumetricFog dither>`).+#[derive(Component)]+pub struct FogDither;++/// The dither's seed for this frame: Bevy's `jitter`, which raea's shader reads as 1 + the film frame mod 64 (0 is no+/// dither). The film frame, not the engine's update count, so a frame rendered alone and the same frame reached in play+/// march the same samples.+pub fn sync_fog_dither(clock: Res<Clock>, mut q: Query<&mut bevy::light::VolumetricFog, With<FogDither>>, mut half: Query<&mut crate::HalfFog, With<FogDither>>) {+ let seed = 1.0 + clock.0.rem_euclid(64) as f32;+ for mut f in &mut q {+ if f.jitter != seed {+ f.jitter = seed;+ }+ }+ for mut f in &mut half {+ if f.fog.jitter != seed {+ f.fog.jitter = seed;+ }+ }+}diff --git a/systems/fog-half/src/lib.rs b/systems/fog-half/src/lib.rsindex f9f21b1d..72c920df 100644--- a/systems/fog-half/src/lib.rs+++ b/systems/fog-half/src/lib.rs@@ -41,6 +41,8 @@ use bevy::{use raea_sys_frame::bevy_api;+/// the volumetric fog group of the camera's post-processing (VFOG), on and off as each frame's row has it+pub mod camera;mod draw;pub use draw::*;diff --git a/systems/frame/src/camera.rs b/systems/frame/src/camera.rsindex 29356f08..fd09e205 100644--- a/systems/frame/src/camera.rs+++ b/systems/frame/src/camera.rs@@ -30,3 +30,17 @@ pub fn camera_pass(world: &mut World, e: Entity, vals: &BTreeMap<String, V>) {c.clear_color = clear;c.viewport = viewport;}++/// A group of the camera row's columns and what it puts on the camera (raea-sys-post camera.rs's GROUPS, and a+/// system's own given beside them, as raea-sys-fog-half's volumetric fog): `on` puts it on as the row has it (nothing,+/// or Bevy's default, where the row has none of its columns), `off` takes off what `on` put on.+pub struct Group {+ pub keys: fn(&str) -> bool,+ pub on: fn(&mut World, Entity, &BTreeMap<String, V>),+ pub off: fn(&mut World, Entity),+}++/// A group's `off` that takes the components `B` off the camera.+pub fn remove<B: Bundle>(world: &mut World, e: Entity) {+ world.entity_mut(e).remove::<B>();+}diff --git a/systems/frame/src/lib.rs b/systems/frame/src/lib.rsindex b208bcf1..9f04ea84 100644--- a/systems/frame/src/lib.rs+++ b/systems/frame/src/lib.rs@@ -29,6 +29,8 @@ pub mod store;// the frame loop's own state (Stages, the frame tag, the overlay and output resources)mod state;pub use state::*;+/// a row's per-frame tables (a frame's look, the camera's post-processing), laid onto it frame by frame+pub mod tables;/// A model row's entity (a glTF under it), whatever its loading stage.#[derive(Component, Default)]@@ -58,8 +60,8 @@ pub struct FrameRows {/// so each row's latest values are kept here (in the store's order), changed in place where a frame changes them,/// and lent to the systems as they are (no columns made, nothing copied per frame)pub live: Option<Vec<BTreeMap<String, V>>>,- /// rows whose frame look changes (the camera's `frame_looks`): that list as written, and each look's columns- pub looks: HashMap<usize, (String, Vec<BTreeMap<String, V>>)>,+ /// rows with per-frame tables (tables.rs: the camera's `frame_looks`, and `frame_sets` on any row), each as parsed+ pub looks: HashMap<usize, tables::Tables>,/// the edit's timeline the columns came from (which rows never change: `still`)pub timeline: Option<std::sync::Arc<raea_core_program::timeline::Timeline>>,/// each row's values this frame as `vals` makes them, made on its first ask: six of the 3D's systems read every@@ -81,9 +83,11 @@ impl FrameRows {}/// Whether a row's values are the same on every frame of the edit, so a system applying them to its entity each- /// frame can apply them once (a live scene's rows: never, since a play changes any of them).+ /// frame can apply them once (a live scene's rows: never, since a play changes any of them). Nor a row with a table+ /// (tables.rs): its set is laid on by `vals`, not in the row its entity was made from, so a one-frame edit (a play's+ /// first rows) put its sky on only at the first frame drawn, after the warm-up, and opened 2 frames dark (RR1).pub fn still(&self, e: Entity) -> bool {- self.live.is_none() && self.timeline.as_ref().zip(self.ix.get(&e)).is_some_and(|(t, r)| t.still(*r))+ self.live.is_none() && self.timeline.as_ref().zip(self.ix.get(&e)).is_some_and(|(t, r)| !self.looks.contains_key(r) && t.still(*r))}/// Whether any row may have column `c` this frame (a live scene's or a frame look's rows: always), so a system@@ -135,13 +139,13 @@ impl FrameRows {pub fn vals(&self, e: Entity) -> Option<std::borrow::Cow<'_, BTreeMap<String, V>>> {let r = *self.ix.get(&e)?;match &self.live {- // a live row as it is, unless its frame look changes: then a copy with this frame's look laid on+ // a live row as it is, unless it has per-frame tables: then a copy with this frame's sets laid onSome(rows) => {let row = rows.get(r)?;Some(match self.looks.get(&r) {- Some((_, looks)) => {+ Some(t) => {let mut v = row.clone();- frame_look_onto(&mut v, looks);+ tables::onto(&mut v, t);std::borrow::Cow::Owned(v)}None => std::borrow::Cow::Borrowed(row),@@ -150,8 +154,8 @@ impl FrameRows {None => {let make = || {let mut v = self.cols.tup(r).vals;- if let Some((_, looks)) = self.looks.get(&r) {- frame_look_onto(&mut v, looks);+ if let Some(t) = self.looks.get(&r) {+ tables::onto(&mut v, t);}v};@@ -163,92 +167,53 @@ impl FrameRows {}}- /// The rows with a `frame_looks` list (the timeline's at the clock, or a live scene's rows), parsed again only- /// where it changed.- pub fn parse_looks(&mut self) {- // a row's frame look is laid on as `vals` makes it+ /// The rows with per-frame tables (the timeline's at the clock, or a live scene's rows), each list parsed again only+ /// where it changed. True when a table came or went, a look changed, or a live row's set changed `structural`ly+ /// (its one set, raea-runtime-look as_table): a live engine warms its next frame up as at a cut (Engine::draw).+ pub fn parse_looks(&mut self) -> bool {+ // a row's sets are laid on as `vals` makes itself.made.iter_mut().for_each(|m| drop(m.take()));- let found: Vec<(usize, String)> = match &self.live {- Some(rows) => rows.iter().enumerate().filter_map(|(r, v)| match v.get("frame_looks") {- Some(V::S(s)) => Some((r, s.clone())),- _ => None,- }).collect(),- None => {- let Some(col) = self.cols.cols.get("frame_looks") else {- self.looks.clear();- return;- };- (0..self.cols.len()).filter_map(|r| match col.get(r) {- Some(V::S(s)) => Some((r, s)),- _ => None,- }).collect()- }- };- let mut seen = Vec::new();- for (r, s) in found {- seen.push(r);- if self.looks.get(&r).is_some_and(|(x, _)| *x == s) {- continue;+ let mut found: HashMap<usize, [Option<String>; 2]> = HashMap::new();+ for (i, (list, _)) in tables::TABLES.iter().enumerate() {+ match &self.live {+ Some(rows) => {+ for (r, v) in rows.iter().enumerate() {+ if let Some(V::S(s)) = v.get(*list) {+ found.entry(r).or_default()[i] = Some(s.clone());+ }+ }+ }+ None => {+ let Some(col) = self.cols.cols.get(*list) else { continue };+ for r in 0..self.cols.len() {+ if let Some(V::S(s)) = col.get(r) {+ found.entry(r).or_default()[i] = Some(s);+ }+ }+ }}- self.looks.insert(r, (s.clone(), parse_frame_looks(&s)));- }- self.looks.retain(|r, _| seen.contains(r));- }-}--/// `frame_looks` (scene3d's writer: a JSON list of objects, each a look's columns) as rows of columns.-pub fn parse_frame_looks(s: &str) -> Vec<BTreeMap<String, V>> {- let Ok(serde_json::Value::Array(list)) = serde_json::from_str::<serde_json::Value>(s) else { return Vec::new() };- list.iter()- .map(|o| {- o.as_object()- .map(|o| {- o.iter()- .filter_map(|(k, v)| match v {- serde_json::Value::Number(n) => Some((k.clone(), V::N(n.as_f64().unwrap_or(0.0)))),- serde_json::Value::String(x) => Some((k.clone(), V::S(x.clone()))),- _ => None,- })- .collect()- })- .unwrap_or_default()- })- .collect()-}--/// This frame's look laid onto a row: every look's columns off it, then the one `frame_look_i` names (none below 0).-pub fn frame_look_onto(v: &mut BTreeMap<String, V>, looks: &[BTreeMap<String, V>]) {- let i = v.get("frame_look_i").map(V::num).unwrap_or(-1.0).round();- v.remove("frame_looks");- for l in looks {- for k in l.keys() {- v.remove(k);}- }- if i >= 0.0 {- if let Some(l) = looks.get(i as usize) {- v.extend(l.iter().map(|(k, x)| (k.clone(), x.clone())));+ let mut old = std::mem::take(&mut self.looks);+ let mut changed = false;+ for (r, srcs) in found {+ let mut t = old.remove(&r).unwrap_or_default();+ for (i, src) in srcs.into_iter().enumerate() {+ t[i] = match src {+ Some(s) if t[i].as_ref().is_some_and(|x| x.src == s) => t[i].take(),+ Some(s) => {+ let new = tables::Table::parse(&s);+ changed |= i == 0 || t[i].as_ref().map_or(true, |o| tables::structural(o.sets.first(), new.sets.first()));+ Some(new)+ }+ None => {+ changed |= t[i].is_some();+ None+ }+ };+ }+ self.looks.insert(r, t);}- }-}--#[cfg(test)]-mod frame_look_tests {- use super::*;-- #[test]- fn a_frame_takes_its_own_look_and_none_goes_plain() {- let looks = parse_frame_looks(r##"[{"frame_look":"paint","paint_sky_top":"#5b9497"},{"frame_look":"paint","outline":"#2b1d14"}]"##);- assert_eq!(looks.len(), 2);- let row = |i: f64| BTreeMap::from([("frame_looks".to_string(), V::S("..".into())), ("frame_look_i".to_string(), V::N(i)), ("x".to_string(), V::N(1.0))]);- let mut v = row(1.0);- frame_look_onto(&mut v, &looks);- assert_eq!(v.get("outline"), Some(&V::S("#2b1d14".into())));- assert!(!v.contains_key("paint_sky_top") && !v.contains_key("frame_looks"));- let mut v = row(-1.0);- frame_look_onto(&mut v, &looks);- assert!(!v.contains_key("frame_look") && !v.contains_key("outline"));- assert_eq!(v.get("x"), Some(&V::N(1.0)));+ changed || old.values().any(|t| t.iter().any(Option::is_some))}}diff --git a/systems/frame/src/tables.rs b/systems/frame/src/tables.rsnew file mode 100644index 00000000..e8ebbdc7--- /dev/null+++ b/systems/frame/src/tables.rs@@ -0,0 +1,225 @@+//! A row's per-frame tables: columns that change from one frame to the next as a set, written by raea-runtime-look as a+//! JSON list of the distinct sets (the list column) and the frame's index into it (the index column: keyed, stepped,+//! -1 for none). raea-render lays the frame's set onto the row (FrameRows::vals), so every system reads a frame's own+//! values: a <Look> and <Outline> on the camera row (frame_looks), and any row's other sets (frame_sets,+//! docs/rerender.feature RR1): the camera's post-processing (the sky, bloom, fog, tone mapping, exposure, the grade, AO+//! and anti-aliasing, shadows, volumetric fog) and a light's colour, shadows and shafts.++use std::collections::{BTreeMap, BTreeSet};++use raea_core_program::ir::V;++/// Each table's list column and index column.+pub const TABLES: [(&str, &str); 2] = [("frame_looks", "frame_look_i"), ("frame_sets", "frame_set_i")];++/// A row's tables, in TABLES' order (None where the row has no such list).+pub type Tables = [Option<Table>; 2];++/// One table: its list as written (parsed again only when that changes), its sets, and every column any set has.+#[derive(Default)]+pub struct Table {+ pub src: String,+ pub sets: Vec<BTreeMap<String, V>>,+ cols: BTreeSet<String>,+}++impl Table {+ /// A list column's JSON (a list of objects, each a set's columns) as sets of columns.+ pub fn parse(s: &str) -> Table {+ let sets: Vec<BTreeMap<String, V>> = match serde_json::from_str::<serde_json::Value>(s) {+ Ok(serde_json::Value::Array(list)) => list+ .iter()+ .map(|o| {+ o.as_object()+ .map(|o| {+ o.iter()+ .filter_map(|(k, v)| match v {+ serde_json::Value::Number(n) => Some((k.clone(), V::N(n.as_f64().unwrap_or(0.0)))),+ serde_json::Value::String(x) => Some((k.clone(), V::S(x.clone()))),+ _ => None,+ })+ .collect()+ })+ .unwrap_or_default()+ })+ .collect(),+ _ => Vec::new(),+ };+ let cols = sets.iter().flat_map(|s| s.keys().cloned()).collect();+ Table { src: s.to_string(), sets, cols }+ }++ /// The frame's set laid onto a row: the list and every set's columns off it, then the set its index names (none+ /// below 0).+ pub fn onto(&self, v: &mut BTreeMap<String, V>, (list, index): (&str, &str)) {+ let i = v.get(index).map(V::num).unwrap_or(-1.0).round();+ v.remove(list);+ for k in &self.cols {+ v.remove(k);+ }+ if i >= 0.0 {+ if let Some(set) = self.sets.get(i as usize) {+ v.extend(set.iter().map(|(k, x)| (k.clone(), x.clone())));+ }+ }+ }+}++/// Every table a row has laid onto it.+pub fn onto(v: &mut BTreeMap<String, V>, tables: &Tables) {+ for (t, names) in tables.iter().zip(TABLES) {+ if let Some(t) = t {+ t.onto(v, names);+ }+ }+}++/// `list` (frames, in order) cut where a row's look or effects change (Cuts), in order: each run starts with a frame+/// whose look or effects are new, which raea-render draws the careful way after a warm-up.+pub fn runs<'a>(prog: &raea_core_program::ir::Program, list: &'a [i64]) -> Vec<&'a [i64]> {+ let cuts = Cuts::of(prog);+ let mut runs = Vec::new();+ let mut from = 0;+ for i in 1..list.len() {+ if cuts.between(list[i - 1], list[i]) {+ runs.push(&list[from..i]);+ from = i;+ }+ }+ if from < list.len() {+ runs.push(&list[from..]);+ }+ runs+}++/// A set's columns whose change is more than a value moving: an effect's mode (the anti-aliasing, AO's quality, the+/// tone mapper), a light's shadows or shafts, the sky and its light.+const MODES: [&str; 7] = ["aa", "ssao", "tonemap", "shadows", "volumetric", "atmosphere", "atmo_light"];++/// Whether going from set `a` to set `b` turns an effect on or off or changes its mode, which can take updates to come+/// (the sky's light on the scene, Bevy's generated environment map, takes three), rather than moving a value (a grade+/// or fog colour ramp), which a frame takes as it takes any keyed value.+pub fn structural(a: Option<&BTreeMap<String, V>>, b: Option<&BTreeMap<String, V>>) -> bool {+ let none = BTreeMap::new();+ let (a, b) = (a.unwrap_or(&none), b.unwrap_or(&none));+ if !a.keys().eq(b.keys()) {+ return true;+ }+ for k in MODES {+ if a.get(k) != b.get(k) {+ return true;+ }+ }+ false+}++/// The frames at which a row's look changes (a keyed `frame_look_i` steps) or its effects change (a keyed `frame_set_i`+/// steps to a set that's `structural`ly another), sorted, found once a load: a live engine drawing a frame across one+/// from the frame it drew last warms up as a load does (Engine::draw), and `frames` starts a run there.+#[derive(bevy::prelude::Resource, Default)]+pub struct Cuts(pub Vec<i64>);++impl Cuts {+ pub fn of(prog: &raea_core_program::ir::Program) -> Cuts {+ // each row's sets, by its id (a key names its row by id)+ let sets: std::collections::HashMap<&str, Table> = prog+ .spawns+ .iter()+ .flat_map(|(_, rows)| rows)+ .filter_map(|r| match (r.get("id"), r.get(TABLES[1].0)) {+ (Some(V::S(id)), Some(V::S(list))) => Some((id.as_str(), Table::parse(list))),+ _ => None,+ })+ .collect();+ let mut at: Vec<i64> = Vec::new();+ for ((id, col), k) in &prog.keys {+ let Some(t) = TABLES.iter().position(|(_, i)| i == col) else { continue };+ let set = |i: f64| (i >= 0.0).then(|| sets.get(id.as_str()).and_then(|s| s.sets.get(i.round() as usize))).flatten();+ // a look's change is always a cut; a set's when it's structural (or its list isn't the row's own)+ at.extend(k.windows(2).filter(|w| w[0].1.round() != w[1].1.round() && (t == 0 || !sets.contains_key(id.as_str()) || structural(set(w[0].1), set(w[1].1)))).map(|w| w[1].0));+ }+ at.sort_unstable();+ at.dedup();+ Cuts(at)+ }++ /// Whether a cut lies after the earlier of frames a and b, up to the later.+ pub fn between(&self, a: i64, b: i64) -> bool {+ let (lo, hi) = (a.min(b), a.max(b));+ let i = self.0.partition_point(|&c| c <= lo);+ self.0.get(i).is_some_and(|&c| c <= hi)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_draw_across_a_set_change_is_a_cut() {+ let mut p = raea_core_program::ir::Program::default();+ p.keys.insert(("cam".into(), "frame_set_i".into()), vec![(0, 0.0, "step".into()), (150, 1.0, "step".into())]);+ p.keys.insert(("sun".into(), "frame_set_i".into()), vec![(0, 0.0, "step".into()), (150, 1.0, "step".into()), (300, 0.0, "step".into())]);+ p.keys.insert(("cam".into(), "x".into()), vec![(0, 0.0, "linear".into()), (10, 1.0, "linear".into())]);+ let c = Cuts::of(&p);+ assert_eq!(c.0, vec![150, 300]);+ assert!(c.between(149, 150) && c.between(150, 149) && c.between(0, 899));+ assert!(!c.between(150, 151) && !c.between(150, 150) && !c.between(0, 149) && !c.between(301, 899));+ }++ #[test]+ fn a_ramp_is_no_cut_and_a_sky_coming_on_is() {+ // frames 0-2 a grade ramp (one value moving), frame 3 the sky on: only frame 3 is a cut+ let mut p = raea_core_program::ir::Program::default();+ let list = r##"[{"grade_saturation":1.0},{"grade_saturation":0.9},{"grade_saturation":0.8},{"grade_saturation":0.8,"atmosphere":1,"atmo_light":1}]"##;+ p.spawns.push(("camera".into(), vec![BTreeMap::from([("id".to_string(), V::S("cam".into())), ("frame_sets".to_string(), V::S(list.into()))])]));+ p.keys.insert(("cam".into(), "frame_set_i".into()), vec![(0, 0.0, "step".into()), (1, 1.0, "step".into()), (2, 2.0, "step".into()), (3, 3.0, "step".into())]);+ assert_eq!(Cuts::of(&p).0, vec![3]);+ let frames: Vec<i64> = (0..5).collect();+ assert_eq!(runs(&p, &frames), vec![&frames[0..3], &frames[3..5]]);+ // anti-aliasing's mode is a cut; a fog colour moving isn't+ let a = BTreeMap::from([("aa".to_string(), V::S("smaa".into())), ("fog_color".to_string(), V::S("#808080".into()))]);+ let mut b = a.clone();+ b.insert("fog_color".into(), V::S("#909090".into()));+ assert!(!structural(Some(&a), Some(&b)));+ b.insert("aa".into(), V::S("fxaa".into()));+ assert!(structural(Some(&a), Some(&b)) && structural(None, Some(&a)) && !structural(None, None));+ }++ #[test]+ fn a_frame_takes_its_own_look_and_none_goes_plain() {+ let looks = Table::parse(r##"[{"frame_look":"paint","paint_sky_top":"#5b9497"},{"frame_look":"paint","outline":"#2b1d14"}]"##);+ assert_eq!(looks.sets.len(), 2);+ let row = |i: f64| BTreeMap::from([("frame_looks".to_string(), V::S("..".into())), ("frame_look_i".to_string(), V::N(i)), ("x".to_string(), V::N(1.0))]);+ let mut v = row(1.0);+ onto(&mut v, &[Some(looks), None]);+ assert_eq!(v.get("outline"), Some(&V::S("#2b1d14".into())));+ assert!(!v.contains_key("paint_sky_top") && !v.contains_key("frame_looks"));+ let looks = Table::parse(r##"[{"frame_look":"paint","paint_sky_top":"#5b9497"},{"frame_look":"paint","outline":"#2b1d14"}]"##);+ let mut v = row(-1.0);+ onto(&mut v, &[Some(looks), None]);+ assert!(!v.contains_key("frame_look") && !v.contains_key("outline"));+ assert_eq!(v.get("x"), Some(&V::N(1.0)));+ }++ #[test]+ fn a_render_is_cut_where_a_set_changes() {+ let mut p = raea_core_program::ir::Program::default();+ p.keys.insert(("cam".into(), "frame_set_i".into()), vec![(0, 0.0, "step".into()), (3, 1.0, "step".into())]);+ p.keys.insert(("sun0".into(), "frame_set_i".into()), vec![(0, 0.0, "step".into()), (5, 1.0, "step".into())]);+ let list: Vec<i64> = (0..8).collect();+ assert_eq!(runs(&p, &list), vec![&list[0..3], &list[3..5], &list[5..8]]);+ assert_eq!(runs(&raea_core_program::ir::Program::default(), &list), vec![&list[..]]);+ }++ #[test]+ fn a_frame_takes_its_own_post_processing_beside_its_look() {+ // shot 1's bloom and sky, shot 2's fog: shot 2's frame has no bloom or sky, whatever the row held+ let post = Table::parse(r##"[{"bloom":0.35,"atmosphere":1},{"fog_color":"#c9ced4","fog_start":10}]"##);+ let mut v = BTreeMap::from([("frame_sets".to_string(), V::S("..".into())), ("frame_set_i".to_string(), V::N(1.0)), ("bloom".to_string(), V::N(9.0)), ("x".to_string(), V::N(1.0))]);+ onto(&mut v, &[None, Some(post)]);+ assert_eq!(v.get("fog_start"), Some(&V::N(10.0)));+ assert!(!v.contains_key("bloom") && !v.contains_key("atmosphere") && !v.contains_key("frame_sets"));+ assert_eq!(v.get("x"), Some(&V::N(1.0)));+ }+}diff --git a/systems/post/Cargo.toml b/systems/post/Cargo.tomlindex e0c5a781..e96f4a54 100644--- a/systems/post/Cargo.toml+++ b/systems/post/Cargo.toml@@ -4,9 +4,10 @@ version = "0.1.0"edition = "2024"license = "FSL-1.1-ALv2"publish = false-description = "The camera's post passes: lens distortion, motion blur, depth of field and the effect stack keeping alpha, and ink outlines"+description = "The camera's post passes (lens distortion, motion blur, depth of field and the effect stack keeping alpha, ink outlines) and the camera row's post-processing put on the camera frame by frame"[dependencies]raea-sys-frame = { path = "../frame" }+raea-sys-compose = { path = "../compose" }raea-core-program = { path = "../../core/program" }bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }diff --git a/systems/post/src/camera.rs b/systems/post/src/camera.rsnew file mode 100644index 00000000..90fd5568--- /dev/null+++ b/systems/post/src/camera.rs@@ -0,0 +1,233 @@+//! The camera row's post-processing as Bevy's components on the camera: put on where the camera is made (`apply`), and+//! on any frame whose row changes them taken off and put on again (`sync`, docs/rerender.feature RR1), so a piece whose+//! shots each have their own sky, fog, grade or anti-aliasing renders as one composition, each frame as it would alone.++use std::collections::BTreeMap;++use bevy::prelude::*;+use raea_core_program::ir::V;+use raea_sys_frame::*;++mod on;+use raea_sys_frame::camera::{Group, remove};++type Vals = BTreeMap<String, V>;++/// The camera row's post-processing by group (raea_sys_frame::camera::Group), in the order `apply` puts them on.+const GROUPS: [Group; 11] = [+ Group { keys: |k| k.starts_with("shadow_"), on: on::shadows, off: |_, _| {} },+ Group { keys: |k| k == "atmosphere" || k.starts_with("atmo_"), on: on::atmosphere, off: on::atmosphere_off },+ Group { keys: |k| k.starts_with("bloom"), on: on::bloom, off: remove::<bevy::post_process::bloom::Bloom> },+ Group { keys: |k| k.starts_with("fog_"), on: on::fog, off: remove::<DistanceFog> },+ Group { keys: |k| k == "tonemap", on: on::tonemap, off: on::tonemap_off },+ Group { keys: |k| k == "exposure", on: on::exposure, off: |w, e| { w.entity_mut(e).insert(bevy::camera::Exposure::default()); } },+ Group { keys: |k| k.starts_with("grade_"), on: on::grading, off: |w, e| { w.entity_mut(e).insert(bevy::render::view::ColorGrading::default()); } },+ Group { keys: |k| k.starts_with("vignette"), on: on::vignette, off: remove::<bevy::post_process::effect_stack::Vignette> },+ Group { keys: |k| k.starts_with("ssao") || k == "aa", on: on::aa, off: remove::<(bevy::pbr::ScreenSpaceAmbientOcclusion, bevy::anti_alias::smaa::Smaa, bevy::anti_alias::fxaa::Fxaa)> },+ // depth of field: on with the frames that have one (their post set has dof_max), its aperture and focus following+ // the frame in sync_camera (RR1: it went on once, with the camera, so a play opening on a shot without it had none)+ Group { keys: |k| k == "dof_max" || k == "dof_mode", on: on::dof, off: remove::<bevy::post_process::dof::DepthOfField> },+ // put on once: their values follow the frame elsewhere (the fringes and the lens in sync_camera, the outline in+ // sync_frame_look)+ Group { keys: |_| false, on: on::once, off: |_, _| {} },+];++/// What each group last put on a camera (its columns as they were), the multisampling the camera was made with, which a+/// frame without AO or another anti-aliasing goes back to, and what the groups' components brought with them.+#[derive(Component)]+pub struct Applied {+ sets: Vec<Vals>,+ msaa: Msaa,+ brought: [bool; 3],+}++/// What Bevy puts on with a group's components (their required components: Bloom and the sky need Hdr, AO the depth+/// and normal prepasses) and never takes off. Brought by a group (the camera hadn't them before), each comes off with+/// the last component that needs it, so a frame after the night shot's bloom isn't drawn through HDR when it would+/// alone (RR0's noir after the night: SSIM 0.989).+fn brought(world: &World, e: Entity) -> [bool; 3] {+ use bevy::core_pipeline::prepass::{DepthPrepass, NormalPrepass};+ let has = |f: fn(&World, Entity) -> bool| f(world, e);+ [has(|w, e| w.get::<bevy::camera::Hdr>(e).is_some()), has(|w, e| w.get::<DepthPrepass>(e).is_some()), has(|w, e| w.get::<NormalPrepass>(e).is_some())]+}++/// Each brought component the camera no longer needs taken off.+fn take_off_brought(world: &mut World, e: Entity, by: &mut [bool; 3]) {+ use bevy::core_pipeline::prepass::{DeferredPrepass, DepthPrepass, NormalPrepass};+ let w = world.entity(e);+ let ao = w.contains::<bevy::pbr::ScreenSpaceAmbientOcclusion>() || w.contains::<crate::outline::InkOutline>();+ let need = [+ w.contains::<bevy::post_process::bloom::Bloom>() || w.contains::<bevy::pbr::AtmosphereSettings>() || w.contains::<DeferredPrepass>(),+ ao || w.contains::<bevy::post_process::motion_blur::MotionBlur>() || w.contains::<DeferredPrepass>(),+ ao,+ ];+ let mut em = world.entity_mut(e);+ for (i, b) in by.iter_mut().enumerate() {+ if *b && !need[i] {+ *b = false;+ match i {+ 0 => { em.remove::<bevy::camera::Hdr>(); }+ 1 => { em.remove::<DepthPrepass>(); }+ _ => { em.remove::<NormalPrepass>(); }+ }+ }+ }+}++fn sets(vals: &Vals, extra: &[Group]) -> Vec<Vals> {+ GROUPS.iter().chain(extra).map(|g| vals.iter().filter(|(k, _)| (g.keys)(k)).map(|(k, v)| (k.clone(), v.clone())).collect()).collect()+}++/// The camera row's post-processing put on the camera `e`, as `vals` has it (the camera's first row): GROUPS, then+/// `extra`, a system's own groups that this crate can't name (raea-sys-fog-half's VFOG, which raea-runtime-scene3d gives).+pub fn apply(world: &mut World, e: Entity, vals: &Vals, extra: &[Group]) {+ let had = brought(world, e);+ for g in GROUPS.iter().chain(extra) {+ (g.on)(world, e, vals);+ }+ let now = brought(world, e);+ let msaa = world.get::<Msaa>(e).copied().unwrap_or_default();+ world.entity_mut(e).insert(Applied { sets: sets(vals, extra), msaa, brought: [0, 1, 2].map(|i| now[i] && !had[i]) });+}++/// Each camera's post-processing as this frame's row has it: a group whose columns changed since the camera last took+/// them is taken off and put on again (a frame's own sky, fog or anti-aliasing: frame_sets, raea-sys-frame tables.rs).+/// Multisampling goes off with AO or SMAA/FXAA and back to the camera's own without, except on a deferred camera (Solari),+/// which can't multisample. `extra` as `apply` had it.+pub fn sync(world: &mut World, extra: &[Group]) {+ let groups: Vec<&Group> = GROUPS.iter().chain(extra).collect();+ let cams: Vec<Entity> = world.query_filtered::<Entity, With<Applied>>().iter(world).collect();+ for e in cams {+ let frame = world.resource::<FrameRows>();+ if frame.still(e) {+ continue;+ }+ let Some(vals) = frame.vals(e).map(std::borrow::Cow::into_owned) else { continue };+ let sets_now = sets(&vals, extra);+ let Some(was) = world.get::<Applied>(e) else { continue };+ let changed: Vec<usize> = (0..groups.len()).filter(|&i| sets_now[i] != was.sets[i]).collect();+ if changed.is_empty() {+ continue;+ }+ let (own, mut by) = (was.msaa, was.brought);+ let had = brought(world, e);+ for &i in &changed {+ (groups[i].off)(world, e);+ (groups[i].on)(world, e, &vals);+ }+ let now = brought(world, e);+ for i in 0..3 {+ by[i] |= now[i] && !had[i];+ }+ take_off_brought(world, e, &mut by);+ let single = vals.contains_key("ssao") || vals.contains_key("aa");+ let want = if single { Msaa::Off } else { own };+ let deferred = world.get::<bevy::core_pipeline::prepass::DeferredPrepass>(e).is_some();+ if world.get::<Msaa>(e) != Some(&want) && (want == Msaa::Off || !deferred) {+ world.entity_mut(e).insert(want);+ }+ if let Some(mut a) = world.get_mut::<Applied>(e) {+ (a.sets, a.brought) = (sets_now, by);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A world with one camera whose row is a live row (`rows`' first), as raea-render's FrameRows lends it.+ fn world(row: Vals) -> (World, Entity) {+ let mut w = World::new();+ w.init_resource::<Assets<bevy::light::atmosphere::ScatteringMedium>>();+ let e = w.spawn((Camera3d::default(), Msaa::Sample4)).id();+ let mut frame = FrameRows::new([(e, 0)].into_iter().collect());+ frame.live = Some(vec![row.clone()]);+ w.insert_resource(frame);+ apply(&mut w, e, &row, &[]);+ (w, e)+ }++ fn set(w: &mut World, row: Vals) {+ w.resource_mut::<FrameRows>().live = Some(vec![row]);+ }++ fn row(cols: &[(&str, V)]) -> Vals {+ cols.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()+ }++ #[test]+ fn a_frame_puts_on_and_takes_off_its_own_effects() {+ let (mut w, e) = world(row(&[("bloom", V::N(0.05)), ("tonemap", V::S("agx".into()))]));+ assert!(w.get::<bevy::post_process::bloom::Bloom>(e).is_some());+ // the next shot: fog and AO, no bloom, Bevy's tone mapping+ set(&mut w, row(&[("fog_color", V::S("#c9ced4".into())), ("fog_start", V::N(10.0)), ("ssao", V::S("ultra".into())), ("aa", V::S("smaa".into()))]));+ sync(&mut w, &[]);+ assert!(w.get::<bevy::post_process::bloom::Bloom>(e).is_none());+ assert!(w.get::<DistanceFog>(e).is_some() && w.get::<bevy::pbr::ScreenSpaceAmbientOcclusion>(e).is_some());+ assert_eq!(w.get::<Msaa>(e), Some(&Msaa::Off));+ // the bloom's Hdr went with it; AO brought its prepasses+ assert!(w.get::<bevy::camera::Hdr>(e).is_none() && w.get::<bevy::core_pipeline::prepass::NormalPrepass>(e).is_some());+ assert_eq!(w.get::<bevy::core_pipeline::tonemapping::Tonemapping>(e), Some(&bevy::core_pipeline::tonemapping::Tonemapping::default()));+ // a sky shot: the atmosphere on, the fog and AO off, multisampling back+ set(&mut w, row(&[("atmosphere", V::N(1.0)), ("atmo_light", V::N(1.0))]));+ sync(&mut w, &[]);+ assert!(w.get::<DistanceFog>(e).is_none() && w.get::<bevy::pbr::ScreenSpaceAmbientOcclusion>(e).is_none() && w.get::<bevy::anti_alias::smaa::Smaa>(e).is_none());+ assert_eq!(w.get::<Msaa>(e), Some(&Msaa::Sample4));+ assert!(w.get::<bevy::pbr::AtmosphereSettings>(e).is_some() && w.get::<bevy::camera::Hdr>(e).is_some());+ assert!(w.get::<bevy::core_pipeline::prepass::DepthPrepass>(e).is_none() && w.get::<bevy::core_pipeline::prepass::NormalPrepass>(e).is_none());+ assert_eq!(w.query::<&bevy::light::Atmosphere>().iter(&w).count(), 1);+ // and off again: the sky's own entity goes with it+ set(&mut w, row(&[]));+ sync(&mut w, &[]);+ assert!(w.get::<bevy::pbr::AtmosphereSettings>(e).is_none() && w.get::<bevy::light::AtmosphereEnvironmentMapLight>(e).is_none());+ assert_eq!(w.query::<&bevy::light::Atmosphere>().iter(&w).count(), 0);+ assert!(w.get::<bevy::camera::Hdr>(e).is_none());+ }++ #[test]+ fn what_the_camera_had_before_stays() {+ // a camera made HDR (its own, not a group's) keeps it when the bloom goes+ let mut w = World::new();+ w.init_resource::<Assets<bevy::light::atmosphere::ScatteringMedium>>();+ let e = w.spawn((Camera3d::default(), bevy::camera::Hdr)).id();+ let mut frame = FrameRows::new([(e, 0)].into_iter().collect());+ frame.live = Some(vec![row(&[("bloom", V::N(0.05))])]);+ w.insert_resource(frame);+ apply(&mut w, e, &row(&[("bloom", V::N(0.05))]), &[]);+ set(&mut w, row(&[]));+ sync(&mut w, &[]);+ assert!(w.get::<bevy::post_process::bloom::Bloom>(e).is_none() && w.get::<bevy::camera::Hdr>(e).is_some());+ }++ #[test]+ fn an_unchanged_frame_puts_nothing_on_again() {+ let (mut w, e) = world(row(&[("bloom", V::N(0.05))]));+ w.get_mut::<bevy::post_process::bloom::Bloom>(e).unwrap().intensity = 0.5;+ // a frame whose other columns change (the camera moves) leaves the bloom as it is+ set(&mut w, row(&[("bloom", V::N(0.05)), ("x", V::N(3.0))]));+ sync(&mut w, &[]);+ assert_eq!(w.get::<bevy::post_process::bloom::Bloom>(e).unwrap().intensity, 0.5);+ }++ #[test]+ fn depth_of_field_comes_with_the_shot_that_has_it() {+ use bevy::post_process::dof::DepthOfField;+ // a play opening on a shot without it, then one with it, then one without (RR0's film: shots 3 and 6)+ let (mut w, e) = world(row(&[("bloom", V::N(0.05))]));+ assert!(w.get::<DepthOfField>(e).is_none());+ set(&mut w, row(&[("dof_aperture", V::N(1.8)), ("dof_max", V::N(64.0)), ("focus", V::N(3.0))]));+ sync(&mut w, &[]);+ let d = w.get::<DepthOfField>(e).expect("on with the shot");+ assert_eq!((d.aperture_f_stops, d.focal_distance), (1.8, 3.0));+ // its aperture changing alone doesn't put it on again (sync_camera follows it)+ w.get_mut::<DepthOfField>(e).unwrap().focal_distance = 7.0;+ set(&mut w, row(&[("dof_aperture", V::N(2.8)), ("dof_max", V::N(64.0)), ("focus", V::N(3.0))]));+ sync(&mut w, &[]);+ assert_eq!(w.get::<DepthOfField>(e).unwrap().focal_distance, 7.0);+ // a play's merged row keeps the last aperture; dof_max gone takes it off+ set(&mut w, row(&[("dof_aperture", V::N(2.8))]));+ sync(&mut w, &[]);+ assert!(w.get::<DepthOfField>(e).is_none());+ }+}diff --git a/systems/post/src/camera/on.rs b/systems/post/src/camera/on.rsnew file mode 100644index 00000000..30eb1292--- /dev/null+++ b/systems/post/src/camera/on.rs@@ -0,0 +1,199 @@+//! Each group of the camera row's post-processing put on the camera, and taken off (camera.rs's GROUPS).++use super::*;++/// Shadow quality (a <Shadows>): the sun's and spots' maps are 4096 texels a side unless it says otherwise (Bevy's 2048+/// speckles and blurs a film's shadows; smaller on a GPU with little memory of its own, raea_sys_frame::shadow); point+/// lights' cube maps half that, 1024 by default as Bevy's. The filter on the camera.+pub fn shadows(world: &mut World, e: Entity, vals: &Vals) {+ if !preview() {+ let size = match vals.get("shadow_map") { Some(V::N(n)) => *n as usize, _ => raea_sys_frame::shadow::shadow_map_default(world) };+ if let Some(mut m) = world.get_resource_mut::<bevy::light::DirectionalLightShadowMap>() {+ m.size = size;+ }+ if let Some(mut m) = world.get_resource_mut::<bevy::light::PointLightShadowMap>() {+ m.size = if vals.contains_key("shadow_map") { size / 2 } else { 1024 };+ }+ }+ let filter = match vals.get("shadow_filter") { Some(V::S(s)) if s == "hardware" => bevy::light::ShadowFilteringMethod::Hardware2x2, _ => bevy::light::ShadowFilteringMethod::Gaussian };+ world.entity_mut(e).insert(filter);+}++/// The sky a camera's <Atmosphere> spawned (its own entity, despawned when a frame has none).+#[derive(Component)]+pub struct AtmosphereOf(Entity);++/// A procedural sky (<Atmosphere>): Bevy 0.20's scattering atmosphere, Earth's air round a planet whose ground is at y 0,+/// lit by the suns; its sky drawn behind everything, and with `atmo_light` it lights the scene too+/// (AtmosphereEnvironmentMapLight). AtmosphereSettings needs Hdr, which it brings.+pub fn atmosphere(world: &mut World, e: Entity, vals: &Vals) {+ if !vals.get("atmosphere").is_some_and(V::truthy) {+ return;+ }+ use bevy::light::{Atmosphere, atmosphere::ScatteringMedium};+ let medium = world.resource_mut::<Assets<ScatteringMedium>>().add(ScatteringMedium::earth(256, 256));+ let mut atmo = Atmosphere::earth(medium);+ if let Some(a) = vals.get("atmo_albedo").map(V::num) {+ atmo.ground_albedo = Vec3::splat(a as f32);+ }+ let sky = world.spawn((atmo, Mirror)).id();+ world.entity_mut(e).insert((bevy::pbr::AtmosphereSettings::default(), AtmosphereOf(sky)));+ if vals.get("atmo_light").is_some_and(V::truthy) {+ world.entity_mut(e).insert(bevy::light::AtmosphereEnvironmentMapLight::default());+ }+}++pub fn atmosphere_off(world: &mut World, e: Entity) {+ if let Some(AtmosphereOf(sky)) = world.entity_mut(e).take::<AtmosphereOf>() {+ world.despawn(sky);+ }+ world.entity_mut(e).remove::<(bevy::pbr::AtmosphereSettings, bevy::light::AtmosphereEnvironmentMapLight)>();+}++pub fn bloom(world: &mut World, e: Entity, vals: &Vals) {+ let bloom = num(vals, "bloom", 0.0);+ if bloom > 0.0 {+ let mut b = bevy::post_process::bloom::Bloom::NATURAL;+ b.intensity = bloom;+ if let Some(th) = vals.get("bloom_threshold").map(V::num) {+ b.prefilter.threshold = th as f32;+ b.prefilter.threshold_softness = 0.2;+ }+ world.entity_mut(e).insert(b);+ }+}++pub fn fog(world: &mut World, e: Entity, vals: &Vals) {+ if vals.contains_key("fog_color") || vals.contains_key("fog_end") || vals.contains_key("fog_density") {+ let falloff = match vals.get("fog_density") {+ Some(d) => FogFalloff::Exponential { density: d.num() as f32 },+ None => FogFalloff::Linear { start: num(vals, "fog_start", 5.0), end: num(vals, "fog_end", 20.0) },+ };+ world.entity_mut(e).insert(DistanceFog { color: colour(vals.get("fog_color"), [0.5, 0.5, 0.55, 1.0]), falloff, ..default() });+ }+}++pub fn tonemap(world: &mut World, e: Entity, vals: &Vals) {+ let Some(V::S(tm)) = vals.get("tonemap") else { return };+ use bevy::core_pipeline::tonemapping::Tonemapping as T;+ let t = match tm.as_str() {+ "none" => T::None,+ "reinhard" => T::Reinhard,+ "aces" => T::AcesFitted,+ "agx" => T::AgX,+ "neutral" | "blender" => T::BlenderFilmic,+ _ => T::TonyMcMapface,+ };+ // "none" draws as Bevy 0.19's None did (bevy_api::Untonemapped)+ if t == T::None {+ world.entity_mut(e).insert((t, bevy_api::Untonemapped));+ } else {+ world.entity_mut(e).insert(t).remove::<bevy_api::Untonemapped>();+ }+}++pub fn tonemap_off(world: &mut World, e: Entity) {+ world.entity_mut(e).insert(bevy::core_pipeline::tonemapping::Tonemapping::default()).remove::<bevy_api::Untonemapped>();+}++pub fn exposure(world: &mut World, e: Entity, vals: &Vals) {+ if let Some(ev) = vals.get("exposure") {+ world.entity_mut(e).insert(bevy::camera::Exposure { ev100: ev.num() as f32 });+ }+}++/// A <Grade>: Bevy's colour grading (before tone mapping, but for the global saturation).+pub fn grading(world: &mut World, e: Entity, vals: &Vals) {+ if !vals.keys().any(|k| k.starts_with("grade_")) {+ return;+ }+ use bevy::render::view::{ColorGrading, ColorGradingSection};+ let mut cg = ColorGrading::default();+ cg.global.temperature = num(vals, "grade_temperature", 0.0);+ cg.global.tint = num(vals, "grade_tint", 0.0);+ cg.global.post_saturation = num(vals, "grade_saturation", 1.0);+ for (pre, sec) in [("grade_s_", &mut cg.shadows), ("grade_m_", &mut cg.midtones), ("grade_h_", &mut cg.highlights)] {+ let d = ColorGradingSection::default();+ *sec = ColorGradingSection {+ saturation: num(vals, &format!("{pre}saturation"), d.saturation),+ contrast: num(vals, &format!("{pre}contrast"), d.contrast),+ gamma: num(vals, &format!("{pre}gamma"), d.gamma),+ gain: num(vals, &format!("{pre}gain"), d.gain),+ lift: num(vals, &format!("{pre}lift"), d.lift),+ };+ }+ world.entity_mut(e).insert(cg);+}++/// A <Grade>'s vignette (sync_frame_look moves it to the composite camera under a frame look).+pub fn vignette(world: &mut World, e: Entity, vals: &Vals) {+ if let Some(v) = vals.get("vignette").map(V::num) {+ use bevy::post_process::effect_stack::Vignette;+ let d = Vignette::default();+ world.entity_mut(e).insert(Vignette {+ intensity: v as f32,+ radius: num(vals, "vignette_radius", d.radius),+ smoothness: num(vals, "vignette_smooth", d.smoothness),+ color: colour(vals.get("vignette_color"), [0.0, 0.0, 0.0, 1.0]),+ ..d+ });+ }+}++/// Ambient occlusion (no multisampling with it: its noise is a fixed pattern without TAA's jitter, so a frame's+/// occlusion is a function of its rows) and the anti-aliasing that replaces multisampling (sync sets Msaa).+pub fn aa(world: &mut World, e: Entity, vals: &Vals) {+ if let Some(V::S(q)) = vals.get("ssao").filter(|_| !preview()) {+ use bevy::pbr::{ScreenSpaceAmbientOcclusion, ScreenSpaceAmbientOcclusionQualityLevel as Q};+ let quality_level = match q.as_str() { "low" => Q::Low, "high" => Q::High, "ultra" => Q::Ultra, _ => Q::Medium };+ world.entity_mut(e).insert(ScreenSpaceAmbientOcclusion {+ quality_level,+ constant_object_thickness: num(vals, "ssao_thickness", 0.25),+ // the radius is Bevy's default (0.20's is 0.19's hard-coded 0.5 x 1.457)+ ..default()+ });+ }+ match vals.get("aa") {+ Some(V::S(m)) if m == "smaa" && !preview() => {+ world.entity_mut(e).insert(bevy::anti_alias::smaa::Smaa { preset: bevy::anti_alias::smaa::SmaaPreset::High });+ }+ Some(V::S(m)) if m == "fxaa" && !preview() => {+ world.entity_mut(e).insert(bevy::anti_alias::fxaa::Fxaa::default());+ }+ _ => {}+ }+}++/// Depth of field, its aperture and focus then following the frame (sync_camera). A frame without dof_max has none: a+/// play's row keeps the last aperture it was sent.+pub fn dof(world: &mut World, e: Entity, vals: &Vals) {+ if let Some(f) = vals.get("dof_aperture").map(V::num).filter(|_| vals.contains_key("dof_max")) {+ use bevy::post_process::dof::{DepthOfField, DepthOfFieldMode};+ let mode = if matches!(vals.get("dof_mode"), Some(V::S(m)) if m == "gaussian") { DepthOfFieldMode::Gaussian } else { DepthOfFieldMode::Bokeh };+ // the background counts as far as the camera sees, not infinitely far (its blur would be the largest)+ world.entity_mut(e).insert(DepthOfField { mode, focal_distance: num(vals, "focus", 5.0), aperture_f_stops: f as f32, max_circle_of_confusion_diameter: num(vals, "dof_max", 64.0), max_depth: num(vals, "far", 100.0), ..default() });+ }+}++/// What goes on once, its values then following the frame elsewhere: ink outlines (sync_frame_look), the colour+/// fringes and the lens (sync_camera).+pub fn once(world: &mut World, e: Entity, vals: &Vals) {+ // ink outlines from the depth and normal prepasses (Msaa::Off, set where the camera is made)+ if vals.contains_key("outline") {+ let line = colour(vals.get("outline"), [0.0, 0.0, 0.0, 1.0]).to_linear().to_f32_array();+ world.entity_mut(e).insert((+ crate::outline::InkOutline { color: Vec4::from_array(line), depth: num(vals, "outline_depth", 0.04), normal: num(vals, "outline_normal", 0.3), width: num(vals, "outline_width", 1.0).max(1.0), far: num(vals, "outline_far", 0.0) / num(vals, "near", 0.1), skip: raea_sys_compose::compose::bits(vals, "outline_skip") },+ bevy::core_pipeline::prepass::DepthPrepass,+ bevy::core_pipeline::prepass::NormalPrepass,+ ));+ }+ if let Some(a) = vals.get("aberration").map(V::num) {+ use bevy::post_process::effect_stack::ChromaticAberration;+ // its intensity is each frame's (sync_camera)+ world.entity_mut(e).insert(ChromaticAberration { intensity: a as f32, ..default() });+ }+ if crate::lens::has_lens(vals) {+ // Fisheye / LensDistortion: its values come from each frame's row (sync_camera)+ world.entity_mut(e).insert(crate::lens::Lens::default());+ }+}diff --git a/systems/post/src/lib.rs b/systems/post/src/lib.rsindex 1eef6d46..7c460464 100644--- a/systems/post/src/lib.rs+++ b/systems/post/src/lib.rs@@ -1,5 +1,6 @@//! The camera's passes after the scene is drawn, each a function of the frame: the lens (Fisheye, LensDistortion), motion-//! blur, Bevy's depth of field and effect stack patched to keep the frame's alpha, and ink outlines.+//! blur, Bevy's depth of field and effect stack patched to keep the frame's alpha, and ink outlines; and the camera row's+//! post-processing (the sky, bloom, fog, the grade, AO and anti-aliasing, volumetric fog) put on the camera frame by frame.use std::collections::BTreeMap;@@ -8,6 +9,7 @@ use raea_core_program::ir::V;use raea_sys_frame::*;use raea_sys_frame::bevy_api;+pub mod camera;pub mod lens;pub mod views;pub mod motion_blur;