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
Solari's guides for MetalFX: a mirror is denoised as what it shows
shinyobjectz87f8ac9a851d
diff --git a/engine/render/raytrace/src/metalfx.rs b/engine/render/raytrace/src/metalfx.rsindex 17a0d7d1..3847ed50 100644--- a/engine/render/raytrace/src/metalfx.rs+++ b/engine/render/raytrace/src/metalfx.rs@@ -29,6 +29,7 @@ use bevy::render::renderer::{RenderContext, RenderDevice, ViewQuery};use bevy::render::camera::{ExtractedCamera, TemporalJitter};use bevy::render::view::{ExtractedView, ViewTarget};use bevy::solari::prelude::SolariLighting;+use bevy::solari::realtime::SolariGuideTextures;use objc2::rc::Retained;use objc2::runtime::ProtocolObject;use objc2::Message;@@ -60,6 +61,11 @@ pub(crate) fn add(app: &mut App) {};core.add_systems(denoise.after(solari).before(main_opaque_pass_3d).in_set(Core3dSystems::MainPass));core.add_systems(denoise_up.before(super::upscale::upscale).in_set(Core3dSystems::EarlyPostProcess));+ // Solari's own guides (primary surface replacement: a mirror's pixel takes what it reflects), unless+ // RAEA_SOLARI_PSR=0, which guides from the G-buffer as before+ if std::env::var("RAEA_SOLARI_PSR").as_deref() != Ok("0") {+ r.world_mut().insert_resource(bevy::solari::realtime::SolariGuideBuffers);+ }}/// The emission taken out before the denoiser and put back after (see DECODE_WGSL): gathered over frames by default@@ -75,109 +81,9 @@ fn one_pass() -> bool {*ON.get_or_init(|| std::env::var("RAEA_SOLARI_UPSCALE").as_deref() != Ok("two"))}-// Bevy's G-buffer (bevy_pbr deferred/functions.wesl, types.wesl) to MetalFX's guides: r = base colour (sRGB-ish, pow-// 1/2.2) and perceptual roughness as unorm4x8; b = reflectance, metallic, occlusion, clearcoat as unorm4x8; a = a 24-bit-// octahedral normal (two 12-bit halves) and flags; g = emissive as rgb9e5. Specular albedo is F0 (Bevy's 0.16-// reflectance² for dielectrics, the base colour for metals).-// What a surface emits is no noise. Denoised as lighting, a screen's picture or a sign's letters came out smeared, its-// texture taken for noise against a near-black albedo (photo 2's monitor). So the emission's share of each pixel's-// colour goes to MetalFX's denoise strength mask, which leaves a pixel marked 1 undenoised while still gathering its-// frames (which anti-aliases its edges), and the emission, compressed as e / (1 + e), is added to its albedo, so what-// the denoiser does smooth isn't swollen against a near-black one. A pixel with nothing in the G-buffer (a forward-// mesh, the sky) is raster-lit, with nothing to denoise, and is marked 1. Measured on photo 2's monitor:-// RAEA_SOLARI_EMISSIVE=split takes the emission (times the exposure, as Solari adds it) out of the colour into `emit`-// and `restore` puts it back after MetalFX, the first way, and kept out of the denoiser an emissive edge stayed-// stepped and crawled with the jitter (500 pixels jumping 80 levels a frame on the window's and curtain's edges);-// emission as the albedo where it led, the screen's dark parts kept their noise; added to every albedo with no mask,-// the picture blurred; split only where it was weak, pixels on the boundary counted it twice and sparkled-const DECODE_WGSL: &str = r#"-@group(0) @binding(0) var gbuf: texture_2d<u32>;-@group(0) @binding(1) var diffuse: texture_storage_2d<rgba16float, write>;-@group(0) @binding(2) var specular: texture_storage_2d<rgba16float, write>;-@group(0) @binding(3) var normal: texture_storage_2d<rgba16float, write>;-@group(0) @binding(4) var rough: texture_storage_2d<r32float, write>;-@group(0) @binding(5) var color: texture_storage_2d<rgba16float, read_write>;-// [0].x: the camera's exposure, .y: 1 to split all emission out (RAEA_SOLARI_EMISSIVE=split); [1]: the output's size-// and the input's (the corner of the colour the main pass drew); [2].xyz: the camera's back, world-space; [3].xy: the-// jitter MetalFX is told, in input pixels-@group(0) @binding(6) var<uniform> params: array<vec4<f32>, 4>;-// the emission `main` took out of the colour, at the input's size, for `restore` to put back-@group(0) @binding(7) var emit: texture_storage_2d<rgba16float, read_write>;-// MetalFX's denoise strength mask: 1 leaves a pixel undenoised-@group(0) @binding(8) var mask: texture_storage_2d<r32float, write>;-fn rgb9e5(v: u32) -> vec3<f32> {- let scale = exp2(f32(i32(extractBits(v, 27u, 5u)) - 15 - 9));- return vec3<f32>(f32(extractBits(v, 0u, 9u)), f32(extractBits(v, 9u, 9u)), f32(extractBits(v, 18u, 9u))) * scale;-}-fn unorm4x8(p: u32) -> vec4<f32> {- return vec4<f32>(f32(p & 255u), f32((p >> 8u) & 255u), f32((p >> 16u) & 255u), f32(p >> 24u)) / 255.0;-}-fn octahedral(v: vec2<f32>) -> vec3<f32> {- let f = v * 2.0 - 1.0;- var n = vec3<f32>(f, 1.0 - abs(f.x) - abs(f.y));- let t = saturate(-n.z);- let w = select(vec2<f32>(t), vec2<f32>(-t), n.xy >= vec2<f32>(0.0));- n = vec3<f32>(n.xy + w, n.z);- return normalize(n);-}-@compute @workgroup_size(8, 8, 1)-fn main(@builtin(global_invocation_id) id: vec3<u32>) {- let size = textureDimensions(diffuse);- if (id.x >= size.x || id.y >= size.y) { return; }- let p = vec2<i32>(id.xy);- let g = textureLoad(gbuf, p, 0);- if (all(g == vec4<u32>(0u))) {- // nothing deferred here (a forward mesh, the sky): its colour as its albedo, so there's nothing to smooth- let c = textureLoad(color, p).rgb;- textureStore(diffuse, p, vec4<f32>(c / max(1.0, max(c.r, max(c.g, c.b))), 1.0));- textureStore(specular, p, vec4<f32>(0.0, 0.0, 0.0, 1.0));- textureStore(normal, p, vec4<f32>(params[2].xyz, 0.0));- textureStore(rough, p, vec4<f32>(1.0, 0.0, 0.0, 0.0));- textureStore(emit, p, vec4<f32>(0.0));- textureStore(mask, p, vec4<f32>(1.0, 0.0, 0.0, 0.0));- return;- }- let a = unorm4x8(g.r);- let props = unorm4x8(g.b);- let base = pow(a.rgb, vec3<f32>(2.2));- let metallic = props.y;- let f0 = mix(vec3<f32>(0.16 * props.x * props.x), base, metallic);- let n = octahedral(vec2<f32>(f32(g.a & 0xFFFu), f32((g.a >> 12u) & 0xFFFu)) / 4095.0);- textureStore(normal, p, vec4<f32>(n, 0.0));- textureStore(rough, p, vec4<f32>(a.w, 0.0, 0.0, 0.0));- let c = textureLoad(color, p);- let e = rgb9e5(g.g) * params[0].x;- textureStore(specular, p, vec4<f32>(f0, 1.0));- if (params[0].y > 0.5) {- let taken = min(e, c.rgb);- textureStore(diffuse, p, vec4<f32>(base * (1.0 - metallic), 1.0));- textureStore(color, p, vec4<f32>(c.rgb - taken, c.a));- textureStore(emit, p, vec4<f32>(taken, 0.0));- textureStore(mask, p, vec4<f32>(0.0));- return;- }- let luma = vec3<f32>(0.2126, 0.7152, 0.0722);- let share = dot(e, luma) / max(dot(c.rgb, luma), 1e-4);- textureStore(diffuse, p, vec4<f32>(min(base * (1.0 - metallic) + e / (vec3<f32>(1.0) + e), vec3<f32>(1.0)), 1.0));- textureStore(mask, p, vec4<f32>(smoothstep(0.3, 0.7, share), 0.0, 0.0, 0.0));-}-fn emitted(i: vec2<i32>) -> vec3<f32> {- return textureLoad(emit, clamp(i, vec2<i32>(0), vec2<i32>(params[1].zw) - 1)).rgb;-}-@compute @workgroup_size(8, 8, 1)-fn restore(@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);- // where this output pixel lies in the jittered G-buffer, between its pixels' centres- let q = (vec2<f32>(id.xy) + 0.5) * params[1].zw / params[1].xy - params[3].xy - 0.5;- let i = vec2<i32>(floor(q));- let t = q - floor(q);- let 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);- let c = textureLoad(color, p);- textureStore(color, p, vec4<f32>(c.rgb + e, c.a));-}-"#;+// the guides' shader: what it writes and why (the emission's split) is in its file+const DECODE_WGSL: &str = include_str!("metalfx_guides.wgsl");+/// A view's denoiser and its textures, made again when its input's or output's size changes.struct View {@@ -201,7 +107,7 @@ struct View {struct Kit {/// 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)>,+ pipeline: Option<(wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::ComputePipeline, wgpu::Sampler, wgpu::ComputePipeline)>,views: HashMap<Entity, View>,off: bool,}@@ -337,7 +243,7 @@ fn matrices(s: &ProtocolObject<dyn MTLFXTemporalDenoisedScaler>, world_to_view:}}-type Viewed = (&'static ViewTarget, &'static ViewPrepassTextures, &'static ExtractedView, &'static ExtractedCamera, &'static SolariLighting, Option<&'static MainPassResolutionOverride>, Option<&'static TemporalJitter>, Has<super::upscale::Upscaled>);+type Viewed = (&'static ViewTarget, &'static ViewPrepassTextures, &'static ExtractedView, &'static ExtractedCamera, &'static SolariLighting, Option<&'static MainPassResolutionOverride>, Option<&'static TemporalJitter>, Has<super::upscale::Upscaled>, Option<&'static SolariGuideTextures>);/// Before the forward meshes: a view at its full size, or one drawn small when RAEA_SOLARI_UPSCALE=two (its corner).fn denoise(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Local<Kit>, mut ctx: RenderContext) {@@ -359,7 +265,7 @@ fn denoise_up(view: ViewQuery<Viewed>, device: Res<RenderDevice>, mut kit: Localrun(entity, item, &device, &mut kit, &mut ctx, true);}-type Item<'a> = (&'a ViewTarget, &'a ViewPrepassTextures, &'a ExtractedView, &'a ExtractedCamera, &'a SolariLighting, Option<&'a MainPassResolutionOverride>, Option<&'a TemporalJitter>, bool);+type Item<'a> = (&'a ViewTarget, &'a ViewPrepassTextures, &'a ExtractedView, &'a ExtractedCamera, &'a SolariLighting, Option<&'a MainPassResolutionOverride>, Option<&'a TemporalJitter>, bool, Option<&'a SolariGuideTextures>);/// The guides from the G-buffer and the emissive out, at the main pass's size; MetalFX's denoiser, out to the whole/// view when `up`; its output over the colour and the emissive back in.@@ -367,7 +273,7 @@ fn run(entity: Entity, item: Item, device: &RenderDevice, kit: &mut Kit, ctx: &mif kit.off {return;}- let (target, pre, ext, cam, solari, part, jitter, _) = item;+ let (target, pre, ext, cam, solari, part, jitter, _, guides) = item;let (Some(depth), Some(motion), Some(gbuf)) = (pre.depth.as_ref(), pre.motion_vectors.as_ref(), pre.deferred.as_ref()) else { return };if target.main_texture_format() != TextureFormat::Rgba16Float {return;@@ -390,13 +296,13 @@ fn run(entity: Entity, item: Item, device: &RenderDevice, kit: &mut Kit, ctx: &m}}}- let (pipeline, restore, restore_taa, hist_sampler) = kit+ let (pipeline, restore, restore_taa, hist_sampler, pipeline_psr) = kit.pipeline.get_or_insert_with(|| {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("restore_taa"), super::emit_taa::sampler(&dev))+ (make("main"), make("restore"), make("restore_taa"), super::emit_taa::sampler(&dev), make("main_psr"))}).clone();let color_view = color.create_view(&Default::default());@@ -417,18 +323,31 @@ fn run(entity: Entity, item: Item, device: &RenderDevice, kit: &mut Kit, ctx: &mentries.push(wgpu::BindGroupEntry { binding: 7, resource: wgpu::BindingResource::TextureView(&emit) });let mask = v.mask.create_view(&Default::default());entries.push(wgpu::BindGroupEntry { binding: 8, resource: wgpu::BindingResource::TextureView(&mask) });+ // Solari's guides when it wrote them (guides.rs), else the G-buffer's+ if let Some(g) = guides {+ for (i, t) in [&g.diffuse_albedo, &g.specular_albedo, &g.normal_roughness].into_iter().enumerate() {+ entries.push(wgpu::BindGroupEntry { binding: 9 + i as u32, resource: wgpu::BindingResource::TextureView(&*t.default_view) });+ }+ }+ let pipeline = if guides.is_some() { &pipeline_psr } else { &pipeline };let bind = dev.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("metalfx guides"), layout: &pipeline.get_bind_group_layout(0), entries: &entries });{let mut pass = ctx.command_encoder().begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("metalfx guides"), timestamp_writes: None });- pass.set_pipeline(&pipeline);+ pass.set_pipeline(pipeline);pass.set_bind_group(0, &bind, &[]);pass.dispatch_workgroups(size.x.div_ceil(8), size.y.div_ceil(8), 1);}+ // with Solari's guides, its motion too: a mirror's pixel moves as what it reflects does (the prepass's is the glass's,+ // and Solari can't write it there where the GPU has no read-write Rg16Float, as Apple's hasn't)+ let guide_motion: &wgpu::Texture = match guides {+ Some(g) => &g.specular_motion_vectors.texture,+ None => &motion.texture.texture,+ };// a command buffer of its own (wgpu won't mix its own commands and raw ones on one encoder), after the guides'let mut raw = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("metalfx denoise") });let done = unsafe {raw.as_hal_mut::<Metal, _, _>(|e| match e.and_then(|e| e.raw_command_buffer()) {- Some(cb) => v.encode(cb, color, &depth.texture.texture, &motion.texture.texture, ext, jitter, solari.reset),+ Some(cb) => v.encode(cb, color, &depth.texture.texture, guide_motion, ext, jitter, solari.reset),None => Err("wgpu gave no Metal command buffer"),})};diff --git a/engine/render/raytrace/src/metalfx_guides.wgsl b/engine/render/raytrace/src/metalfx_guides.wgslnew file mode 100644index 00000000..be68ece8--- /dev/null+++ b/engine/render/raytrace/src/metalfx_guides.wgsl@@ -0,0 +1,145 @@+// MetalFX's guides (metalfx.rs): written from Bevy's G-buffer (main) or Solari's guides (main_psr), with the+// emission split out; `restore` puts the emission back after the denoiser.+// Bevy's G-buffer (bevy_pbr deferred/functions.wesl, types.wesl) to MetalFX's guides: r = base colour (sRGB-ish, pow+// 1/2.2) and perceptual roughness as unorm4x8; b = reflectance, metallic, occlusion, clearcoat as unorm4x8; a = a 24-bit+// octahedral normal (two 12-bit halves) and flags; g = emissive as rgb9e5.+// What a surface emits is no noise. Denoised as lighting, a screen's picture or a sign's letters came out smeared, its+// texture taken for noise against a near-black albedo (photo 2's monitor). So the emission's share of each pixel's+// colour goes to MetalFX's denoise strength mask, which leaves a pixel marked 1 undenoised while still gathering its+// frames (which anti-aliases its edges), and the emission, compressed as e / (1 + e), is added to its albedo, so what+// the denoiser does smooth isn't swollen against a near-black one. A pixel with nothing in the G-buffer (a forward+// mesh, the sky) is raster-lit, with nothing to denoise, and is marked 1. Measured on photo 2's monitor:+// RAEA_SOLARI_EMISSIVE=split takes the emission (times the exposure, as Solari adds it) out of the colour into `emit`+// and `restore` puts it back after MetalFX, the first way, and kept out of the denoiser an emissive edge stayed+// stepped and crawled with the jitter (500 pixels jumping 80 levels a frame on the window's and curtain's edges);+// emission as the albedo where it led, the screen's dark parts kept their noise; added to every albedo with no mask,+// the picture blurred; split only where it was weak, pixels on the boundary counted it twice and sparkled+@group(0) @binding(0) var gbuf: texture_2d<u32>;+@group(0) @binding(1) var diffuse: texture_storage_2d<rgba16float, write>;+@group(0) @binding(2) var specular: texture_storage_2d<rgba16float, write>;+@group(0) @binding(3) var normal: texture_storage_2d<rgba16float, write>;+@group(0) @binding(4) var rough: texture_storage_2d<r32float, write>;+@group(0) @binding(5) var color: texture_storage_2d<rgba16float, read_write>;+// [0].x: the camera's exposure, .y: 1 to split all emission out (RAEA_SOLARI_EMISSIVE=split); [1]: the output's size+// and the input's (the corner of the colour the main pass drew); [2].xyz: the camera's back, world-space; [3].xy: the+// jitter MetalFX is told, in input pixels+@group(0) @binding(6) var<uniform> params: array<vec4<f32>, 4>;+// the emission `main` took out of the colour, at the input's size, for `restore` to put back+@group(0) @binding(7) var emit: texture_storage_2d<rgba16float, read_write>;+// MetalFX's denoise strength mask: 1 leaves a pixel undenoised+@group(0) @binding(8) var mask: texture_storage_2d<r32float, write>;+fn rgb9e5(v: u32) -> vec3<f32> {+ let scale = exp2(f32(i32(extractBits(v, 27u, 5u)) - 15 - 9));+ return vec3<f32>(f32(extractBits(v, 0u, 9u)), f32(extractBits(v, 9u, 9u)), f32(extractBits(v, 18u, 9u))) * scale;+}+fn unorm4x8(p: u32) -> vec4<f32> {+ return vec4<f32>(f32(p & 255u), f32((p >> 8u) & 255u), f32((p >> 16u) & 255u), f32(p >> 24u)) / 255.0;+}+fn octahedral(v: vec2<f32>) -> vec3<f32> {+ let f = v * 2.0 - 1.0;+ var n = vec3<f32>(f, 1.0 - abs(f.x) - abs(f.y));+ let t = saturate(-n.z);+ let w = select(vec2<f32>(t), vec2<f32>(-t), n.xy >= vec2<f32>(0.0));+ n = vec3<f32>(n.xy + w, n.z);+ return normalize(n);+}+// A surface as the denoiser's guides take it: diffuse albedo, specular albedo, world normal, perceptual roughness+struct Surface {+ diffuse: vec3<f32>,+ specular: vec3<f32>,+ normal: vec3<f32>,+ rough: f32,+}+// from Bevy's G-buffer: specular albedo is F0 (Bevy's 0.16 reflectance² for dielectrics, the base colour for metals)+fn from_gbuffer(g: vec4<u32>) -> Surface {+ let a = unorm4x8(g.r);+ let props = unorm4x8(g.b);+ let base = pow(a.rgb, vec3<f32>(2.2));+ let metallic = props.y;+ let f0 = mix(vec3<f32>(0.16 * props.x * props.x), base, metallic);+ let n = octahedral(vec2<f32>(f32(g.a & 0xFFFu), f32((g.a >> 12u) & 0xFFFu)) / 4095.0);+ return Surface(base * (1.0 - metallic), f0, n, a.w);+}+// Solari's guides (bevy_solari realtime/guides.rs), written by its lighting pass: the surface's own, or for a mirror's+// pixel those of what it reflects (primary surface replacement), so what a mirror shows keeps its detail+@group(0) @binding(9) var guide_diffuse: texture_2d<f32>;+@group(0) @binding(10) var guide_specular: texture_2d<f32>;+@group(0) @binding(11) var guide_normal: texture_2d<f32>;+fn from_guides(p: vec2<i32>) -> Surface {+ let nr = textureLoad(guide_normal, p, 0);+ return Surface(textureLoad(guide_diffuse, p, 0).rgb, textureLoad(guide_specular, p, 0).rgb, nr.xyz, nr.w);+}+// a pixel with nothing deferred (a forward mesh, the sky): its colour as its albedo, so there's nothing to smooth.+// True when it was one+fn undeferred(p: vec2<i32>, g: vec4<u32>) -> bool {+ if (any(g != vec4<u32>(0u))) { return false; }+ sky(p);+ return true;+}+fn sky(p: vec2<i32>) {+ let c = textureLoad(color, p).rgb;+ textureStore(diffuse, p, vec4<f32>(c / max(1.0, max(c.r, max(c.g, c.b))), 1.0));+ textureStore(specular, p, vec4<f32>(0.0, 0.0, 0.0, 1.0));+ textureStore(normal, p, vec4<f32>(params[2].xyz, 0.0));+ textureStore(rough, p, vec4<f32>(1.0, 0.0, 0.0, 0.0));+ textureStore(emit, p, vec4<f32>(0.0));+ textureStore(mask, p, vec4<f32>(1.0, 0.0, 0.0, 0.0));+}+fn store(p: vec2<i32>, g: vec4<u32>, s: Surface) {+ textureStore(normal, p, vec4<f32>(s.normal, 0.0));+ textureStore(rough, p, vec4<f32>(s.rough, 0.0, 0.0, 0.0));+ textureStore(specular, p, vec4<f32>(s.specular, 1.0));+ let c = textureLoad(color, p);+ let e = rgb9e5(g.g) * params[0].x;+ if (params[0].y > 0.5) {+ let taken = min(e, c.rgb);+ textureStore(diffuse, p, vec4<f32>(s.diffuse, 1.0));+ textureStore(color, p, vec4<f32>(c.rgb - taken, c.a));+ textureStore(emit, p, vec4<f32>(taken, 0.0));+ textureStore(mask, p, vec4<f32>(0.0));+ return;+ }+ let luma = vec3<f32>(0.2126, 0.7152, 0.0722);+ let share = dot(e, luma) / max(dot(c.rgb, luma), 1e-4);+ textureStore(diffuse, p, vec4<f32>(min(s.diffuse + e / (vec3<f32>(1.0) + e), vec3<f32>(1.0)), 1.0));+ textureStore(mask, p, vec4<f32>(smoothstep(0.3, 0.7, share), 0.0, 0.0, 0.0));+}+@compute @workgroup_size(8, 8, 1)+fn main(@builtin(global_invocation_id) id: vec3<u32>) {+ let size = textureDimensions(diffuse);+ if (id.x >= size.x || id.y >= size.y) { return; }+ let p = vec2<i32>(id.xy);+ let g = textureLoad(gbuf, p, 0);+ if (undeferred(p, g)) { return; }+ store(p, g, from_gbuffer(g));+}+@compute @workgroup_size(8, 8, 1)+fn main_psr(@builtin(global_invocation_id) id: vec3<u32>) {+ let size = textureDimensions(diffuse);+ if (id.x >= size.x || id.y >= size.y) { return; }+ let p = vec2<i32>(id.xy);+ let g = textureLoad(gbuf, p, 0);+ if (undeferred(p, g)) { return; }+ // a mirror's pixel that shows the sky (Solari's diffuse albedo's alpha 1): guided as the sky's own+ if (textureLoad(guide_diffuse, p, 0).a > 0.5) {+ sky(p);+ return;+ }+ store(p, g, from_guides(p));+}+fn emitted(i: vec2<i32>) -> vec3<f32> {+ return textureLoad(emit, clamp(i, vec2<i32>(0), vec2<i32>(params[1].zw) - 1)).rgb;+}+@compute @workgroup_size(8, 8, 1)+fn restore(@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);+ // where this output pixel lies in the jittered G-buffer, between its pixels' centres+ let q = (vec2<f32>(id.xy) + 0.5) * params[1].zw / params[1].xy - params[3].xy - 0.5;+ let i = vec2<i32>(floor(q));+ let t = q - floor(q);+ let 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);+ let c = textureLoad(color, p);+ textureStore(color, p, vec4<f32>(c.rgb + e, c.a));+}diff --git a/vendor/bevy_solari/src/realtime/guides.rs b/vendor/bevy_solari/src/realtime/guides.rsnew file mode 100644index 00000000..9e8cb60d--- /dev/null+++ b/vendor/bevy_solari/src/realtime/guides.rs@@ -0,0 +1,60 @@+//! raea: Solari's denoiser guides for a denoiser other than DLSS-RR (MetalFX's, on a Mac).+//!+//! A denoiser smooths each pixel's lighting against guides: the surface's albedo, normal, roughness, depth and motion.+//! Drawn from the G-buffer, a mirror's guides are the glass's own (flat, one colour, one normal), so the denoiser takes+//! everything the mirror shows for noise and smears it (photo 4's arched mirror: its dunes, ripples and rock a blur).+//! Solari already works out better guides for DLSS-RR, primary surface replacement: a mirror's pixel takes the+//! albedo, normal, roughness, depth and motion of what it reflects, as if the camera saw that directly. They were+//! built only with the `dlss` feature. With [`SolariGuideBuffers`] in the render world, every Solari view gets them+//! in [`SolariGuideTextures`], whatever denoiser reads them.+use bevy_ecs::{component::Component, resource::Resource};+use bevy_math::UVec2;+use bevy_render::{+ render_resource::{+ Extent3d, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages,+ TextureViewDescriptor,+ },+ renderer::RenderDevice,+ texture::CachedTexture,+};++/// In the render world: every Solari view writes the guides (primary surface replacement included) to its+/// [`SolariGuideTextures`]. Inserted by the denoiser that reads them, before the render app starts.+#[derive(Resource, Clone, Copy, Default)]+pub struct SolariGuideBuffers;++/// A Solari view's guides, at its main pass's size, written each frame by its lighting pass, as DLSS-RR's are:+/// diffuse and specular albedo (Rgba8Unorm, linear), world normal and perceptual roughness (Rgba16Float), depth+/// (R32Float, reverse-z, the reflected surface's for a mirror) and the specular motion (Rg16Float).+#[derive(Component)]+pub struct SolariGuideTextures {+ pub diffuse_albedo: CachedTexture,+ pub specular_albedo: CachedTexture,+ pub normal_roughness: CachedTexture,+ pub depth: CachedTexture,+ pub specular_motion_vectors: CachedTexture,+}++pub(super) fn make(device: &RenderDevice, size: UVec2) -> SolariGuideTextures {+ let texture = |label: &'static str, format: TextureFormat| {+ let texture = device.create_texture(&TextureDescriptor {+ label: Some(label),+ size: Extent3d { width: size.x, height: size.y, depth_or_array_layers: 1 },+ mip_level_count: 1,+ sample_count: 1,+ dimension: TextureDimension::D2,+ format,+ usage: TextureUsages::TEXTURE_BINDING | TextureUsages::STORAGE_BINDING,+ view_formats: &[],+ });+ let default_view = texture.create_view(&TextureViewDescriptor::default());+ CachedTexture { texture, default_view }+ };+ SolariGuideTextures {+ diffuse_albedo: texture("solari_guide_diffuse_albedo", TextureFormat::Rgba8Unorm),+ specular_albedo: texture("solari_guide_specular_albedo", TextureFormat::Rgba8Unorm),+ normal_roughness: texture("solari_guide_normal_roughness", TextureFormat::Rgba16Float),+ depth: texture("solari_guide_depth", TextureFormat::R32Float),+ specular_motion_vectors: texture("solari_guide_specular_motion_vectors", TextureFormat::Rg16Float),+ }+}diff --git a/vendor/bevy_solari/src/realtime/initial_path.wesl b/vendor/bevy_solari/src/realtime/initial_path.weslindex c38f07ce..f4f71bac 100644--- a/vendor/bevy_solari/src/realtime/initial_path.wesl+++ b/vendor/bevy_solari/src/realtime/initial_path.wesl@@ -117,7 +117,7 @@ fn generate_initial_path(world_position: vec3<f32>, world_normal: vec3<f32>, matif ray.kind == RAY_QUERY_INTERSECTION_NONE {@if(DLSS_RR_GUIDE_BUFFERS)if !psr.finished && !next_bounce.diffuse_selected {- psr_environment_miss(pixel_id, wo);+ psr_environment_miss(pixel_id, wo, psr.replace_fully);}// raea: the sun only off a mirror's specular lobe, which light sampling can't reach; elsewhere it finds the sundiff --git a/vendor/bevy_solari/src/realtime/mod.rs b/vendor/bevy_solari/src/realtime/mod.rsindex 99130a30..737975a5 100644--- a/vendor/bevy_solari/src/realtime/mod.rs+++ b/vendor/bevy_solari/src/realtime/mod.rs@@ -1,4 +1,6 @@mod extract;+// raea: the denoiser guides (primary surface replacement) without DLSS+mod guides;mod node;mod prepare;// raea: RAEA_SOLARI_TIMES=1, each stage's GPU time@@ -41,6 +43,8 @@ use prepare::{};use tracing::warn;+pub use guides::{SolariGuideBuffers, SolariGuideTextures};+/// Raytraced direct and indirect lighting.////// When using this plugin, it's highly recommended to set `shadow_maps_enabled: false` on all lights, as Solari replacesdiff --git a/vendor/bevy_solari/src/realtime/node.rs b/vendor/bevy_solari/src/realtime/node.rsindex 8b68d613..a67497a0 100644--- a/vendor/bevy_solari/src/realtime/node.rs+++ b/vendor/bevy_solari/src/realtime/node.rs@@ -35,7 +35,6 @@ pub struct SolariLightingPipelines {bind_group_layout: BindGroupLayoutDescriptor,bind_group_layout_restir: BindGroupLayoutDescriptor,bind_group_layout_world_cache_active_cells_dispatch: BindGroupLayoutDescriptor,- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]bind_group_layout_resolve_dlss_rr_textures: BindGroupLayoutDescriptor,decay_world_cache_pipeline: CachedComputePipelineId,compact_world_cache_single_block_pipeline: CachedComputePipelineId,@@ -47,21 +46,19 @@ pub struct SolariLightingPipelines {presample_light_tiles_pipeline: CachedComputePipelineId,restir: RestirPipelines,no_restir: NoRestirPipelines,- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]- resolve_dlss_rr_textures_pipeline: CachedComputePipelineId,+ // raea: these three only when a view can have guides (DLSS-RR's, or guides.rs's)+ resolve_dlss_rr_textures_pipeline: Option<CachedComputePipelineId>,}struct RestirPipelines {initial_and_temporal: CachedComputePipelineId,- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]- initial_and_temporal_with_psr: CachedComputePipelineId,+ initial_and_temporal_with_psr: Option<CachedComputePipelineId>,spatial_and_shade: CachedComputePipelineId,}struct NoRestirPipelines {initial_and_shade: CachedComputePipelineId,- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]- initial_and_shade_with_psr: CachedComputePipelineId,+ initial_and_shade_with_psr: Option<CachedComputePipelineId>,}#[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]@@ -71,6 +68,7 @@ type SolariLightingViewQuery = (&'static ViewPrepassTextures,&'static ViewUniformOffset,&'static PreviousViewUniformOffset,+ Option<&'static super::guides::SolariGuideTextures>,);#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]@@ -81,6 +79,7 @@ type SolariLightingViewQuery = (&'static ViewUniformOffset,&'static PreviousViewUniformOffset,Option<&'static ViewDlssRayReconstructionTextures>,+ Option<&'static super::guides::SolariGuideTextures>,);pub fn solari_lighting(@@ -101,6 +100,7 @@ pub fn solari_lighting(view_prepass_textures,view_uniform_offset,previous_view_uniform_offset,+ view_guides,) = view.into_inner();#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]@@ -111,11 +111,25 @@ pub fn solari_lighting(view_uniform_offset,previous_view_uniform_offset,view_dlss_rr_textures,+ view_guides,) = view.into_inner();+ // raea: DLSS-RR's guides, else guides.rs's, both written by the same passes+ #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]+ let guides = view_dlss_rr_textures.map(|d| {+ [&d.diffuse_albedo, &d.specular_albedo, &d.normal_roughness, &d.depth, &d.specular_motion_vectors]+ });++ #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]+ let guides: Option<[&bevy_render::texture::CachedTexture; 5]> = None;+ let guides = guides.or(view_guides.map(|d| {+ [&d.diffuse_albedo, &d.specular_albedo, &d.normal_roughness, &d.depth, &d.specular_motion_vectors]+ }));+let Some(pipelines) = solari_pipelines else {return;};+ let guides = guides.filter(|_| pipelines.resolve_dlss_rr_textures_pipeline.is_some());let restir = solari_lighting_resources.reservoirs.as_ref().zip(view_prepass_textures@@ -123,31 +137,22 @@ pub fn solari_lighting(.zip(view_prepass_textures.previous_depth_only_view()),);- #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]+ // a view with guides takes the pipelines that write them (primary surface replacement)+ let psr = |id: Option<CachedComputePipelineId>| id.filter(|_| guides.is_some());let (initial_pipeline_id, spatial_pipeline_id) = if restir.is_some() {(- pipelines.restir.initial_and_temporal,+ psr(pipelines.restir.initial_and_temporal_with_psr)+ .unwrap_or(pipelines.restir.initial_and_temporal),Some(pipelines.restir.spatial_and_shade),)} else {- (pipelines.no_restir.initial_and_shade, None)+ (+ psr(pipelines.no_restir.initial_and_shade_with_psr)+ .unwrap_or(pipelines.no_restir.initial_and_shade),+ None,+ )};- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]- let (initial_pipeline_id, spatial_pipeline_id) =- match (restir.is_some(), view_dlss_rr_textures.is_some()) {- (true, true) => (- pipelines.restir.initial_and_temporal_with_psr,- Some(pipelines.restir.spatial_and_shade),- ),- (true, false) => (- pipelines.restir.initial_and_temporal,- Some(pipelines.restir.spatial_and_shade),- ),- (false, true) => (pipelines.no_restir.initial_and_shade_with_psr, None),- (false, false) => (pipelines.no_restir.initial_and_shade, None),- };-let (Some(decay_world_cache_pipeline),Some(compact_world_cache_single_block_pipeline),@@ -194,11 +199,12 @@ pub fn solari_lighting(None => None,};- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]- let Some(resolve_dlss_rr_textures_pipeline) =- pipeline_cache.get_compute_pipeline(pipelines.resolve_dlss_rr_textures_pipeline)- else {- return;+ let resolve_dlss_rr_textures_pipeline = match (guides, pipelines.resolve_dlss_rr_textures_pipeline) {+ (Some(_), Some(id)) => match pipeline_cache.get_compute_pipeline(id) {+ None => return,+ pipeline => pipeline,+ },+ _ => None,};// Past every bail-out, so this view's reservoirs will be brought up to this frame's light ids@@ -257,18 +263,17 @@ pub fn solari_lighting(&BindGroupEntries::single(s.world_cache_active_cells_dispatch.as_entire_binding()),);- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]- let bind_group_resolve_dlss_rr_textures = view_dlss_rr_textures.map(|d| {+ let bind_group_resolve_dlss_rr_textures = guides.map(|d| {render_device.create_bind_group("solari_lighting_bind_group_resolve_dlss_rr_textures",&pipeline_cache.get_bind_group_layout(&pipelines.bind_group_layout_resolve_dlss_rr_textures),&BindGroupEntries::sequential((- &d.diffuse_albedo.default_view,- &d.specular_albedo.default_view,- &d.normal_roughness.default_view,- &d.depth.default_view,- &d.specular_motion_vectors.default_view,+ &d[0].default_view,+ &d[1].default_view,+ &d[2].default_view,+ &d[3].default_view,+ &d[4].default_view,)),)});@@ -316,8 +321,9 @@ pub fn solari_lighting(let dx = solari_lighting_resources.view_size.x.div_ceil(8);let dy = solari_lighting_resources.view_size.y.div_ceil(8);- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]- if let Some(bind_group_resolve_dlss_rr_textures) = &bind_group_resolve_dlss_rr_textures {+ if let (Some(bind_group_resolve_dlss_rr_textures), Some(resolve_dlss_rr_textures_pipeline)) =+ (&bind_group_resolve_dlss_rr_textures, resolve_dlss_rr_textures_pipeline)+ {pass.set_bind_group(2, bind_group_resolve_dlss_rr_textures, &[]);pass.set_pipeline(resolve_dlss_rr_textures_pipeline);pass.dispatch_workgroups(dx, dy, 1);@@ -383,7 +389,6 @@ pub fn solari_lighting();}- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]if let Some(bind_group_resolve_dlss_rr_textures) = &bind_group_resolve_dlss_rr_textures {pass.set_bind_group(2, bind_group_resolve_dlss_rr_textures, &[]);}@@ -404,7 +409,6 @@ pub fn solari_lighting(],);}- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]if let Some(bind_group_resolve_dlss_rr_textures) = &bind_group_resolve_dlss_rr_textures {pass.set_bind_group(2, bind_group_resolve_dlss_rr_textures, &[]);}@@ -435,7 +439,10 @@ pub fn init_solari_lighting_pipelines(scene_bindings: Res<RaytracingSceneBindings>,asset_server: Res<AssetServer>,render_adapter: Res<RenderAdapter>,+ guides: Option<Res<super::guides::SolariGuideBuffers>>,) {+ // raea: the pipelines that write the guides, for DLSS-RR or for guides.rs's+ let psr = guides.is_some() || cfg!(all(feature = "dlss", not(feature = "force_disable_dlss")));let motion_vectors_storage_read_write = render_adapter.get_texture_format_features(MOTION_VECTOR_PREPASS_FORMAT).flags@@ -493,7 +500,6 @@ pub fn init_solari_lighting_pipelines(&BindGroupLayoutEntries::single(ShaderStages::COMPUTE, storage_buffer_sized(false, None)),);- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]let bind_group_layout_resolve_dlss_rr_textures = BindGroupLayoutDescriptor::new("solari_lighting_bind_group_layout_resolve_dlss_rr_textures",&BindGroupLayoutEntries::sequential(@@ -525,7 +531,6 @@ pub fn init_solari_lighting_pipelines(ExtraBindGroup::WorldCacheDispatch => {layout.push(bind_group_layout_world_cache_active_cells_dispatch.clone());}- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]ExtraBindGroup::DlssRrGuideBuffers => {layout.push(bind_group_layout_resolve_dlss_rr_textures.clone());}@@ -546,7 +551,6 @@ pub fn init_solari_lighting_pipelines(ExtraBindGroup::WorldCacheDispatch => {shader_defs.push("WORLD_CACHE_NON_ATOMIC_LIFE_BUFFER".into());}- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]ExtraBindGroup::DlssRrGuideBuffers => {shader_defs.push("DLSS_RR_GUIDE_BUFFERS".into());}@@ -568,7 +572,6 @@ pub fn init_solari_lighting_pipelines(bind_group_layout_restir: bind_group_layout_restir.clone(),bind_group_layout_world_cache_active_cells_dispatch:bind_group_layout_world_cache_active_cells_dispatch.clone(),- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]bind_group_layout_resolve_dlss_rr_textures: bind_group_layout_resolve_dlss_rr_textures.clone(),decay_world_cache_pipeline: create_pipeline(@@ -644,15 +647,16 @@ pub fn init_solari_lighting_pipelines(ExtraBindGroup::None,vec![],),- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]- initial_and_temporal_with_psr: create_pipeline(- "solari_lighting_initial_and_temporal_with_psr_pipeline",- "initial_and_temporal",- load_embedded_asset!(asset_server.as_ref(), "restir.wesl"),- true,- ExtraBindGroup::DlssRrGuideBuffers,- vec![],- ),+ initial_and_temporal_with_psr: psr.then(|| {+ create_pipeline(+ "solari_lighting_initial_and_temporal_with_psr_pipeline",+ "initial_and_temporal",+ load_embedded_asset!(asset_server.as_ref(), "restir.wesl"),+ true,+ ExtraBindGroup::DlssRrGuideBuffers,+ vec![],+ )+ }),spatial_and_shade: create_pipeline("solari_lighting_spatial_and_shade_pipeline","spatial_and_shade",@@ -671,31 +675,32 @@ pub fn init_solari_lighting_pipelines(ExtraBindGroup::None,vec![],),- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]- initial_and_shade_with_psr: create_pipeline(- "solari_lighting_initial_and_shade_with_psr_pipeline",- "initial_and_shade",- load_embedded_asset!(asset_server.as_ref(), "no_restir.wesl"),+ initial_and_shade_with_psr: psr.then(|| {+ create_pipeline(+ "solari_lighting_initial_and_shade_with_psr_pipeline",+ "initial_and_shade",+ load_embedded_asset!(asset_server.as_ref(), "no_restir.wesl"),+ false,+ ExtraBindGroup::DlssRrGuideBuffers,+ vec![],+ )+ }),+ },+ resolve_dlss_rr_textures_pipeline: psr.then(|| {+ create_pipeline(+ "solari_lighting_resolve_dlss_rr_textures_pipeline",+ "resolve_dlss_rr_textures",+ load_embedded_asset!(asset_server.as_ref(), "resolve_dlss_rr_textures.wesl"),false,ExtraBindGroup::DlssRrGuideBuffers,vec![],- ),- },- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]- resolve_dlss_rr_textures_pipeline: create_pipeline(- "solari_lighting_resolve_dlss_rr_textures_pipeline",- "resolve_dlss_rr_textures",- load_embedded_asset!(asset_server.as_ref(), "resolve_dlss_rr_textures.wesl"),- false,- ExtraBindGroup::DlssRrGuideBuffers,- vec![],- ),+ )+ }),});}enum ExtraBindGroup {None,WorldCacheDispatch,- #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]DlssRrGuideBuffers,}diff --git a/vendor/bevy_solari/src/realtime/prepare.rs b/vendor/bevy_solari/src/realtime/prepare.rsindex 43404865..6e80c326 100644--- a/vendor/bevy_solari/src/realtime/prepare.rs+++ b/vendor/bevy_solari/src/realtime/prepare.rs@@ -151,6 +151,8 @@ pub fn prepare_solari_lighting_resources(render_device: Res<RenderDevice>,render_queue: Res<RenderQueue>,frame_count: Res<FrameCount>,+ // raea: the guides for a denoiser other than DLSS-RR (guides.rs)+ guides: Option<Res<super::guides::SolariGuideBuffers>>,mut commands: Commands,) {for query_item in &query {@@ -250,6 +252,11 @@ pub fn prepare_solari_lighting_resources(world_cache_active_cells_dispatch,view_size,});+ if guides.is_some() {+ commands+ .entity(entity)+ .insert(super::guides::make(&render_device, view_size));+ }#[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]if has_dlss_rr {diff --git a/vendor/bevy_solari/src/realtime/resolve_dlss_rr_textures.wesl b/vendor/bevy_solari/src/realtime/resolve_dlss_rr_textures.weslindex 906096f2..77bf3051 100644--- a/vendor/bevy_solari/src/realtime/resolve_dlss_rr_textures.wesl+++ b/vendor/bevy_solari/src/realtime/resolve_dlss_rr_textures.wesl@@ -108,9 +108,21 @@ fn psr_chain_mirror(psr: PsrState, plane_normal: vec3<f32>) -> PsrState {return chained;}-fn psr_environment_miss(pixel_id: vec2<u32>, primary_wo: vec3<f32>) {+fn psr_environment_miss(pixel_id: vec2<u32>, primary_wo: vec3<f32>, replace_fully: bool) {let far_position = view.world_position - (primary_wo * ENVIRONMENT_VIRTUAL_DISTANCE);- textureStore(specular_motion_vectors, pixel_id, vec4(calculate_motion_vector(far_position, far_position), vec2(0.0)));+ let motion = calculate_motion_vector(far_position, far_position);+ textureStore(specular_motion_vectors, pixel_id, vec4(motion, vec2(0.0)));+ // raea: a mirror that shows the sky is guided as the sky's own pixels are: infinitely far, nothing to denoise.+ // Its diffuse albedo's alpha 1 says so to a denoiser other than DLSS-RR (guides.rs); left as the glass's, the+ // denoiser smoothed the clouds a mirror shows away+ if replace_fully {+ textureStore(dlss_rr_depth, pixel_id, vec4(0.0));+ @if(MOTION_VECTORS_READ_WRITE)+ textureStore(motion_vectors, pixel_id, vec4(motion, vec2(0.0)));+ textureStore(diffuse_albedo, pixel_id, vec4(0.0, 0.0, 0.0, 1.0));+ textureStore(specular_albedo, pixel_id, vec4(0.5));+ textureStore(normal_roughness, pixel_id, vec4(0.0, 0.0, 1.0, 0.0));+ }}/// Primary surface replacement for perfect mirrors. The reflection chain has been followed to its