Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

Solari: what a surface emits goes round MetalFX's denoiser and is gathered over frames with no clamp

shinyobjectza058f870481a
diff --git a/engine/render/raytrace/src/emit_taa.rs b/engine/render/raytrace/src/emit_taa.rs
new file mode 100644
index 00000000..2b818a2c
--- /dev/null
+++ b/engine/render/raytrace/src/emit_taa.rs
@@ -0,0 +1,98 @@
+//! What a surface emits, kept out of MetalFX's denoiser and gathered over frames on its own (the default;
+//! RAEA_SOLARI_EMISSIVE=mask gives it to the denoiser as before, =split puts back each frame's alone).
+//!
+//! MetalFX's denoiser clamps its history to the neighbourhood it sees each frame, which is what keeps Solari's rare
+//! bright paths from flaring, but a bright detail smaller than a pixel (sky through a spruce's twigs, a lit wire) shows
+//! in only some of the jittered frames, and the clamp throws it away: photo 3's canopy came out at 0.47 of the path
+//! tracer's light (raw Solari, 1.02). Emission has no noise to suppress, so it needs no clamp. metalfx.rs's guide pass
+//! takes it out of the colour (as `split` does), and `restore_taa` here gathers it at the output's size: each frame's
+//! jittered samples near an output pixel, weighted by their distance to its centre, added to the pixel's history
+//! reprojected by the motion of the nearest surface about it, read through a Catmull-Rom filter. Where the pixel moved
+//! and the history's depth isn't among those about it (a disocclusion), the history counts as one frame's; a cut
+//! drops it; it holds at most 16 frames' weight. Measured against the path tracer, drawn at half size: the forest's
+//! canopy 0.99 of its light (MetalFX alone 0.52), and as a person sees it, tone mapped, 1.03 (0.47); photo 2's sunlit
+//! room and photo 1's lamp unchanged (0.87, 0.79-0.82); photo 2's window edges 2 pixels a frame jumping 80 levels
+//! (MetalFX alone 0, each frame's alone 1088); a screen's fine detail 0.44 of the tracer's (MetalFX 0.52); about 1 ms
+//! at 1080 x 1920. Through MetalFX's own temporal scaler instead, its clamp dropped the canopy again (0.50).
+
+use bevy::prelude::*;
+
+pub(crate) const WGSL: &str = include_str!("emit_taa.wgsl");
+
+/// On unless RAEA_SOLARI_EMISSIVE is mask or split.
+pub(crate) fn on() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| !matches!(std::env::var("RAEA_SOLARI_EMISSIVE").as_deref(), Ok("mask") | Ok("split")))
+}
+
+/// RAEA_EMIT_TAA_DEBUG=1: the pass paints its weights instead; 2 never takes the history, 3 always does (emit_taa.wgsl)
+pub(crate) fn debug() -> f32 {
+ static ON: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("RAEA_EMIT_TAA_DEBUG").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0))
+}
+
+/// RAEA_EMIT_TAA_SHARP: how fast a sample's weight falls with its distance from a pixel's centre, exp(-k d^2) in output
+/// pixels, 6 by default: at Blackman-Harris's 2.29 the forest's canopy came out 1.28 times the tracer's as seen (tone
+/// mapped), its sky through the twigs spread wider than a pixel, and a screen's detail 0.38 of the tracer's
+pub(crate) fn sharp() -> f32 {
+ static ON: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("RAEA_EMIT_TAA_SHARP").ok().and_then(|v| v.parse().ok()).unwrap_or(6.0))
+}
+
+/// A view's emission history at the output's size: the gathered emission and its weight, and the depth it was gathered
+/// at, two of each, one read as the other is written.
+pub(crate) struct History {
+ color: [wgpu::Texture; 2],
+ depth: [wgpu::Texture; 2],
+ /// which of the two this frame writes
+ next: usize,
+}
+
+impl History {
+ pub(crate) fn new(dev: &wgpu::Device, out_size: UVec2) -> History {
+ use wgpu::TextureUsages as U;
+ let make = |format, label| super::metalfx::texture(dev, out_size, format, U::STORAGE_BINDING | U::TEXTURE_BINDING, label);
+ History {
+ color: [make(wgpu::TextureFormat::Rgba16Float, "emission history"), make(wgpu::TextureFormat::Rgba16Float, "emission history")],
+ depth: [make(wgpu::TextureFormat::R32Float, "emission history depth"), make(wgpu::TextureFormat::R32Float, "emission history depth")],
+ next: 0,
+ }
+ }
+
+ /// The pass's own bindings (9 to 15): the view's depth and motion, last frame's history to read and this frame's to
+ /// write. Call `advance` once the pass is recorded.
+ pub(crate) fn views(&self, depth: &wgpu::Texture, motion: &wgpu::Texture) -> [wgpu::TextureView; 6] {
+ let v = |t: &wgpu::Texture| t.create_view(&Default::default());
+ let (r, w) = (1 - self.next, self.next);
+ let depth = depth.create_view(&wgpu::TextureViewDescriptor { aspect: wgpu::TextureAspect::DepthOnly, ..Default::default() });
+ [depth, v(motion), v(&self.color[r]), v(&self.color[w]), v(&self.depth[r]), v(&self.depth[w])]
+ }
+
+ pub(crate) fn advance(&mut self) {
+ self.next = 1 - self.next;
+ }
+}
+
+/// The bilinear clamp sampler the history is read with.
+pub(crate) fn sampler(dev: &wgpu::Device) -> wgpu::Sampler {
+ dev.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("emission history"),
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ ..Default::default()
+ })
+}
+
+/// The bind group entries 9 to 15 from `views` and the sampler.
+pub(crate) fn entries<'a>(views: &'a [wgpu::TextureView; 6], sampler: &'a wgpu::Sampler) -> [wgpu::BindGroupEntry<'a>; 7] {
+ let tv = |b: u32, v: &'a wgpu::TextureView| wgpu::BindGroupEntry { binding: b, resource: wgpu::BindingResource::TextureView(v) };
+ [
+ tv(9, &views[0]),
+ tv(10, &views[1]),
+ tv(11, &views[2]),
+ wgpu::BindGroupEntry { binding: 12, resource: wgpu::BindingResource::Sampler(sampler) },
+ tv(13, &views[3]),
+ tv(14, &views[4]),
+ tv(15, &views[5]),
+ ]
+}
diff --git a/engine/render/raytrace/src/emit_taa.wgsl b/engine/render/raytrace/src/emit_taa.wgsl
new file mode 100644
index 00000000..fb0b6664
--- /dev/null
+++ b/engine/render/raytrace/src/emit_taa.wgsl
@@ -0,0 +1,119 @@
+// the split emission gathered over frames at the output's size, with no clamp (RAEA_SOLARI_EMISSIVE=taa): each frame's
+// jittered samples weighted by their distance to this output pixel's centre, added to its history reprojected by the
+// motion, which is dropped where the depth there changed (a disocclusion) or the camera cut
+@group(0) @binding(9) var depth: texture_depth_2d;
+@group(0) @binding(10) var motion: texture_2d<f32>;
+@group(0) @binding(11) var hist_in: texture_2d<f32>;
+@group(0) @binding(12) var hist_sampler: sampler;
+@group(0) @binding(13) var hist_out: texture_storage_2d<rgba16float, write>;
+@group(0) @binding(14) var hist_depth_in: texture_storage_2d<r32float, read>;
+@group(0) @binding(15) var hist_depth_out: texture_storage_2d<r32float, write>;
+// the most frames' weight the history holds: past it, it fades as 1 / HISTORY_CAP a frame
+const HISTORY_CAP: f32 = 16.0;
+// the history at `uv` through a Catmull-Rom filter in five bilinear taps (Jimenez's), so a moving view isn't blurred a
+// little more each frame as a bilinear read would; never below zero (its lobes ring on a hard edge)
+fn history_at(uv: vec2<f32>, size: vec2<f32>) -> vec4<f32> {
+ let at = uv * size;
+ let t1 = floor(at - 0.5) + 0.5;
+ let f = at - t1;
+ let w0 = f * (-0.5 + f * (1.0 - 0.5 * f));
+ let w1 = 1.0 + f * f * (-2.5 + 1.5 * f);
+ let w2 = f * (0.5 + f * (2.0 - 1.5 * f));
+ let w3 = f * f * (-0.5 + 0.5 * f);
+ let w12 = w1 + w2;
+ let t0 = (t1 - 1.0) / size;
+ let t3 = (t1 + 2.0) / size;
+ let t12 = (t1 + w2 / w12) / size;
+ var r = textureSampleLevel(hist_in, hist_sampler, vec2<f32>(t12.x, t0.y), 0.0) * (w12.x * w0.y);
+ r += textureSampleLevel(hist_in, hist_sampler, vec2<f32>(t0.x, t12.y), 0.0) * (w0.x * w12.y);
+ r += textureSampleLevel(hist_in, hist_sampler, t12, 0.0) * (w12.x * w12.y);
+ r += textureSampleLevel(hist_in, hist_sampler, vec2<f32>(t3.x, t12.y), 0.0) * (w3.x * w12.y);
+ r += textureSampleLevel(hist_in, hist_sampler, vec2<f32>(t12.x, t3.y), 0.0) * (w12.x * w3.y);
+ let sum = w12.x * w0.y + w0.x * w12.y + w12.x * w12.y + w3.x * w12.y + w12.x * w3.y;
+ return max(r / sum, vec4<f32>(0.0));
+}
+@compute @workgroup_size(8, 8, 1)
+fn restore_taa(@builtin(global_invocation_id) id: vec3<u32>) {
+ let size = vec2<u32>(params[1].xy);
+ if (id.x >= size.x || id.y >= size.y) { return; }
+ let p = vec2<i32>(id.xy);
+ let out_size = params[1].xy;
+ let in_size = params[1].zw;
+ // this output pixel in the jittered input, where the input's sample centres are whole numbers
+ let q = (vec2<f32>(id.xy) + 0.5) * in_size / out_size - params[3].xy - 0.5;
+ let near = vec2<i32>(round(q));
+ var sum = vec3<f32>(0.0);
+ var weight = 0.0;
+ // the depths about this pixel: its history is kept if its depth lies among them, so a twig's pixel that showed
+ // sky through it last frame keeps what it gathered, and a surface that moved off what it was showing loses it
+ var zlo = 1e9;
+ var zhi = 0.0;
+ // the nearest surface about this pixel, whose motion it takes: at a silhouette the sample nearest the pixel may be
+ // the surface behind, and the history read from where that one was crawled along the edge (photo 2's window)
+ var front = clamp(near, vec2<i32>(0), vec2<i32>(in_size) - 1);
+ for (var dy = -1; dy <= 1; dy++) {
+ for (var dx = -1; dx <= 1; dx++) {
+ let i = near + vec2<i32>(dx, dy);
+ if (any(i < vec2<i32>(0)) || any(i >= vec2<i32>(in_size))) { continue; }
+ let zi = textureLoad(depth, i, 0);
+ zlo = min(zlo, zi);
+ zhi = max(zhi, zi);
+ if (zi >= zhi) { front = i; }
+ // the distance in output pixels, a Blackman-Harris-like falloff, nothing past one pixel
+ let d = (vec2<f32>(i) - q) * out_size / in_size;
+ let d2 = dot(d, d);
+ if (d2 >= 1.0) { continue; }
+ // params[2].w: how fast a sample's weight falls with its distance (RAEA_EMIT_TAA_SHARP)
+ let w = exp(-params[2].w * d2);
+ sum += w * textureLoad(emit, i).rgb;
+ weight += w;
+ }
+ }
+ let here = clamp(near, vec2<i32>(0), vec2<i32>(in_size) - 1);
+ let z = textureLoad(depth, here, 0);
+ // where this pixel was last frame (Bevy's motion is this frame's uv less last frame's)
+ let uv = (vec2<f32>(id.xy) + 0.5) / out_size;
+ let moved = textureLoad(motion, front, 0).xy;
+ let was = uv - moved;
+ var hist = vec4<f32>(0.0);
+ let inside = all(was >= vec2<f32>(0.0)) && all(was <= vec2<f32>(1.0));
+ if (params[0].z < 0.5 && inside) {
+ let h = history_at(was, out_size);
+ let hz = textureLoad(hist_depth_in, min(vec2<i32>(was * out_size), vec2<i32>(out_size) - 1)).r;
+ // reverse depth is 1 / distance up to a constant: within 5% of the depths about it. Only where the pixel moved:
+ // nothing is uncovered where nothing moves, and where a twig hides sky in some of the jittered frames, a test
+ // of depth drops whichever is rarer about it (sky, mostly), which lost a forest's canopy a quarter of its light
+ // RAEA_EMIT_TAA_DEBUG=2 never takes the history, 3 always does (a test of what the depth test costs)
+ let still = all(abs(moved * in_size) < vec2<f32>(0.01));
+ let among = hz >= zlo * 0.95 && hz <= zhi * 1.05;
+ let same = (still || among || params[0].w == 3.0) && params[0].w != 2.0;
+ // a history that fails the test still counts as one frame's: dropped outright, a pixel on a moving silhouette's
+ // trailing side was drawn from its frame's samples alone, and crawled (photo 2's window, 300 pixels a frame
+ // jumping 80 levels); kept at full weight, whatever moved off it would trail behind
+ var cap = select(1.0, HISTORY_CAP, same);
+ if (params[0].w == 2.0) { cap = 0.0; }
+ hist = vec4<f32>(h.rgb, min(h.a, cap));
+ }
+ var e: vec3<f32>;
+ var held: f32;
+ if (hist.a + weight > 1e-4) {
+ e = (hist.rgb * hist.a + sum) / (hist.a + weight);
+ held = hist.a + weight;
+ } else {
+ // no sample near and no history: the frame's emission between its samples, as `restore` puts it back
+ let i = vec2<i32>(floor(q));
+ let t = q - floor(q);
+ e = mix(mix(emitted(i), emitted(i + vec2<i32>(1, 0)), t.x), mix(emitted(i + vec2<i32>(0, 1)), emitted(i + vec2<i32>(1, 1)), t.x), t.y);
+ held = 0.0;
+ }
+ textureStore(hist_out, p, vec4<f32>(e, held));
+ textureStore(hist_depth_out, p, vec4<f32>(z, 0.0, 0.0, 0.0));
+ let c = textureLoad(color, p);
+ // RAEA_EMIT_TAA_DEBUG=1: this frame's sample weight, the history's weight (of HISTORY_CAP) and whether the history
+ // was taken, as red, green and blue
+ if (params[0].w == 1.0) {
+ textureStore(color, p, vec4<f32>(weight, hist.a / HISTORY_CAP, f32(hist.a > 0.0), c.a));
+ return;
+ }
+ textureStore(color, p, vec4<f32>(c.rgb + e, c.a));
+}
diff --git a/engine/render/raytrace/src/lib.rs b/engine/render/raytrace/src/lib.rs
index b6da5869..47bd127f 100644
--- a/engine/render/raytrace/src/lib.rs
+++ b/engine/render/raytrace/src/lib.rs
@@ -10,6 +10,8 @@ mod solari;
#[cfg(target_os = "macos")]
mod metalfx;
#[cfg(target_os = "macos")]
+mod emit_taa;
+#[cfg(target_os = "macos")]
mod upscale;
// RAEA_LIGHT: one light path for every camera (docs/realism.feature LT1)
pub mod force;
diff --git a/engine/render/raytrace/src/metalfx.rs b/engine/render/raytrace/src/metalfx.rs
index 2e1b9182..17a0d7d1 100644
--- a/engine/render/raytrace/src/metalfx.rs
+++ b/engine/render/raytrace/src/metalfx.rs
@@ -62,10 +62,11 @@ pub(crate) fn add(app: &mut App) {
core.add_systems(denoise_up.before(super::upscale::upscale).in_set(Core3dSystems::EarlyPostProcess));
}
-/// RAEA_SOLARI_EMISSIVE=split: the emission taken out before the denoiser and put back after (see DECODE_WGSL).
+/// The emission taken out before the denoiser and put back after (see DECODE_WGSL): gathered over frames by default
+/// (emit_taa.rs), each frame's alone with RAEA_SOLARI_EMISSIVE=split; =mask leaves it in, for the denoiser.
fn split() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- *ON.get_or_init(|| std::env::var("RAEA_SOLARI_EMISSIVE").as_deref() == Ok("split"))
+ *ON.get_or_init(|| std::env::var("RAEA_SOLARI_EMISSIVE").as_deref() == Ok("split") || super::emit_taa::on())
}
/// A view drawn small is denoised and brought up in one pass (unless RAEA_SOLARI_UPSCALE=two).
@@ -191,13 +192,16 @@ struct View {
emit: wgpu::Texture,
mask: wgpu::Texture,
out: wgpu::Texture,
+ /// the split emission's history (RAEA_SOLARI_EMISSIVE=taa, emit_taa.rs)
+ taa: Option<super::emit_taa::History>,
fresh: bool,
}
#[derive(Default)]
struct Kit {
- /// the guides (and the emissive out), and the emissive back in
- pipeline: Option<(wgpu::ComputePipeline, wgpu::ComputePipeline)>,
+ /// the guides (and the emissive out), the emissive back in, from this frame or gathered over frames (emit_taa.rs),
+ /// and the sampler that reads the gathered emission's history
+ pipeline: Option<(wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::Sampler)>,
views: HashMap<Entity, View>,
off: bool,
}
@@ -205,7 +209,7 @@ struct Kit {
unsafe impl Send for Kit {}
unsafe impl Sync for Kit {}
-fn texture(dev: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat, usage: wgpu::TextureUsages, label: &str) -> wgpu::Texture {
+pub(super) fn texture(dev: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat, usage: wgpu::TextureUsages, label: &str) -> wgpu::Texture {
dev.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: size.x, height: size.y, depth_or_array_layers: 1 },
@@ -262,6 +266,7 @@ impl View {
emit: texture(dev, size, wgpu::TextureFormat::Rgba16Float, guide, "metalfx split emission"),
mask: texture(dev, size, wgpu::TextureFormat::R32Float, guide, "metalfx denoise strength"),
out: texture(dev, out_size, wgpu::TextureFormat::Rgba16Float, guide | U::RENDER_ATTACHMENT | U::COPY_SRC, "metalfx output"),
+ taa: super::emit_taa::on().then(|| super::emit_taa::History::new(dev, out_size)),
fresh: true,
})
}
@@ -385,17 +390,19 @@ fn run(entity: Entity, item: Item, device: &RenderDevice, kit: &mut Kit, ctx: &m
}
}
}
- let (pipeline, restore) = kit
+ let (pipeline, restore, restore_taa, hist_sampler) = kit
.pipeline
.get_or_insert_with(|| {
- let module = dev.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("metalfx guides"), source: wgpu::ShaderSource::Wgsl(DECODE_WGSL.into()) });
+ let source = format!("{DECODE_WGSL}{}", super::emit_taa::WGSL);
+ let module = dev.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("metalfx guides"), source: wgpu::ShaderSource::Wgsl(source.into()) });
let make = |entry: &str| dev.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("metalfx guides"), layout: None, module: &module, entry_point: Some(entry), compilation_options: Default::default(), cache: None });
- (make("main"), make("restore"))
+ (make("main"), make("restore"), make("restore_taa"), super::emit_taa::sampler(&dev))
})
.clone();
let color_view = color.create_view(&Default::default());
let back = ext.world_from_view.back();
- let words: [f32; 16] = [cam.exposure, if split() { 1.0 } else { 0.0 }, 0.0, 0.0, out_size.x as f32, out_size.y as f32, size.x as f32, size.y as f32, back.x, back.y, back.z, 0.0, jitter.x, jitter.y, 0.0, 0.0];
+ let reset = solari.reset || kit.views.get(&entity).is_none_or(|v| v.fresh);
+ let words: [f32; 16] = [cam.exposure, if split() { 1.0 } else { 0.0 }, if reset { 1.0 } else { 0.0 }, super::emit_taa::debug(), out_size.x as f32, out_size.y as f32, size.x as f32, size.y as f32, back.x, back.y, back.z, super::emit_taa::sharp(), jitter.x, jitter.y, 0.0, 0.0];
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_ne_bytes()).collect();
let params = wgpu::util::DeviceExt::create_buffer_init(&dev, &wgpu::util::BufferInitDescriptor { label: Some("metalfx params"), contents: &bytes, usage: wgpu::BufferUsages::UNIFORM });
let v = kit.views.get_mut(&entity).unwrap();
@@ -428,18 +435,23 @@ fn run(entity: Entity, item: Item, device: &RenderDevice, kit: &mut Kit, ctx: &m
ctx.add_command_buffer(raw.finish());
// the emissive back in, after the denoiser's command buffer (add_command_buffer flushed the encoder before it)
if split() {
- let back = dev.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("metalfx emissive back"),
- layout: &restore.get_bind_group_layout(0),
- entries: &[
- wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&color_view) },
- wgpu::BindGroupEntry { binding: 6, resource: params.as_entire_binding() },
- wgpu::BindGroupEntry { binding: 7, resource: wgpu::BindingResource::TextureView(&emit) },
- ],
- });
+ let mut entries = vec![
+ wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&color_view) },
+ wgpu::BindGroupEntry { binding: 6, resource: params.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 7, resource: wgpu::BindingResource::TextureView(&emit) },
+ ];
+ let taa_views = v.taa.as_ref().map(|h| h.views(&depth.texture.texture, &motion.texture.texture));
+ if let Some(views) = &taa_views {
+ entries.extend(super::emit_taa::entries(views, &hist_sampler));
+ }
+ let put = if taa_views.is_some() { &restore_taa } else { &restore };
+ let back = dev.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("metalfx emissive back"), layout: &put.get_bind_group_layout(0), entries: &entries });
+ if let Some(h) = v.taa.as_mut() {
+ h.advance();
+ }
{
let mut pass = ctx.command_encoder().begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("metalfx emissive back"), timestamp_writes: None });
- pass.set_pipeline(&restore);
+ pass.set_pipeline(put);
pass.set_bind_group(0, &back, &[]);
pass.dispatch_workgroups(out_size.x.div_ceil(8), out_size.y.div_ceil(8), 1);
}