HD: GPU time per pass in the F3 timing list, half-resolution GTAO with a depth-aware blur

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 16:43:36 +03:00
committed by airdef
parent 2228844b92
commit 37cf7ea714
2 changed files with 443 additions and 10 deletions
+21 -2
View File
@@ -3725,9 +3725,20 @@ impl Renderer {
(_, Some(native)) => native.timing.as_ref(),
_ => None,
};
timer
let mut times = timer
.map(pack_timing::PassTiming::medians)
.unwrap_or_default()
.unwrap_or_default();
// AirDef fork: the HD lighting's passes (shadows, G-buffer, occlusion, lighting, bloom,
// tone curve) while it is on.
if let Some(hd) = &self.hd {
times.extend(hd.pass_times());
}
times
}
/// AirDef fork: bind groups the HD lighting made in the last frame (0 in a steady state).
pub fn hd_bind_groups_last_frame(&self) -> Option<u64> {
self.hd.as_ref().map(|hd| hd.groups_last_frame)
}
/// The dimension the shader pack was last set for.
pub fn shader_pack_dimension(&self) -> Option<i32> {
@@ -4981,6 +4992,8 @@ impl Renderer {
if let Some(settings) = frame.hd {
hd.write(&self.queue, &hd_scene, frame.hd_lights, settings);
}
hd.set_timing(device, &self.queue, self.pass_timing);
hd.timing_begin(device, &self.queue);
// The sun's (or moon's) shadow cascades: the world's globals swapped for the light's.
if shadow_strength > 0.0 {
// The quads the shadow shader would not discard (overlays 4, 9, 10 and 40:
@@ -5090,6 +5103,9 @@ impl Renderer {
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(0..entity_quads * 6, 0, 0..1);
}
drop(pass);
// Contact shadows from the G-buffer's depth and normals, for the lighting.
hd.ao(&mut encoder);
} else if !hd_on {
self.hd = None;
}
@@ -5831,6 +5847,9 @@ impl Renderer {
if let Some(Some(timer)) = Self::pass_timer(&mut self.pack_post, &mut self.native) {
timer.submitted(&self.queue);
}
if hd_on && let Some(hd) = &mut self.hd {
hd.timing_submitted(&self.queue);
}
if let Some((path, buffer)) = readback {
self.screenshot_result = Some(
self.write_screenshot(&path, &buffer)
+422 -8
View File
@@ -5,7 +5,9 @@
//! into a high-dynamic-range target; the mod's post pass runs on that; then
//! bright parts bloom and a tone curve brings it to the screen — vanilla's
//! range (up to about 0.8) left as it is, only what is brighter rolled off.
use super::pack_timing::PassTiming;
use glam::Mat4;
use std::sync::atomic::{AtomicU64, Ordering};
/// The G-buffer's formats.
pub const ALBEDO: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
@@ -24,6 +26,25 @@ const TILE_INDICES: usize = 1 << 19;
const EVERY_LIGHT: u32 = u32::MAX;
/// Bloom's mip levels.
const BLOOM_LEVELS: usize = 6;
/// The ambient occlusion's targets (half resolution): occlusion and the distance it was taken at.
pub const AO_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rg16Float;
/// The occlusion's default strength (`Hd::ao_strength`; 0 turns it off).
pub const AO_STRENGTH: f32 = 1.0;
/// The timed passes of bloom, by level (each is timed on its own; the report sums them).
const BLOOM_NAMES: [&str; 2 * BLOOM_LEVELS] = [
"hd bloom#0",
"hd bloom#1",
"hd bloom#2",
"hd bloom#3",
"hd bloom#4",
"hd bloom#5",
"hd bloom#6",
"hd bloom#7",
"hd bloom#8",
"hd bloom#9",
"hd bloom#10",
"hd bloom#11",
];
/// A light for this frame, relative to the camera.
#[repr(C)]
@@ -59,7 +80,8 @@ struct HdFrame {
fog_color: [f32; 4],
/// Environmental start, end; render-distance start, end.
fog: [f32; 4],
/// x: sky light kept in the shade; y: blocks' light; z: the air's density (rays, halos).
/// x: sky light kept in the shade; y: blocks' light; z: the air's density (rays, halos);
/// w: the ambient occlusion's strength (0 off).
ambient: [f32; 4],
/// x: shadows on; y, z: the cascades' half sizes; w: the light tiles per row.
shadow: [f32; 4],
@@ -133,6 +155,34 @@ struct Light {
// how long they are (4 words), then the lists of light indices. A length of 0xffffffff means
// every light.
@group(0) @binding(12) var<storage, read> tiles: array<u32>;
// Ambient occlusion at half resolution: x the occlusion (1 open), y the distance it was taken at.
@group(0) @binding(13) var ao_tex: texture_2d<f32>;
// The occlusion at a full-resolution pixel `dist` away: the four nearest half-resolution texels
// weighted by closeness and by how near their distance is, so it doesn't bleed across edges.
fn ao_at(px: vec2<i32>, dist: f32) -> f32 {
let size = vec2<i32>(textureDimensions(ao_tex));
let f = vec2<f32>(px) * 0.5;
let base = vec2<i32>(floor(f));
let t = f - floor(f);
var sum = 0.0;
var total = 0.0;
for (var j = 0; j < 2; j++) {
for (var i = 0; i < 2; i++) {
let q = clamp(base + vec2<i32>(i, j), vec2<i32>(0), size - 1);
let s = textureLoad(ao_tex, q, 0).xy;
let bw = select(1.0 - t.x, t.x, i == 1) * select(1.0 - t.y, t.y, j == 1);
let dz = (s.y - dist) / (0.03 * dist + 0.1);
let w = select(0.0, bw / (1.0 + dz * dz * dz * dz), s.y > 0.0);
sum += s.x * w;
total += w;
}
}
if total < 0.0001 {
return textureLoad(ao_tex, clamp(px / 2, vec2<i32>(0), size - 1), 0).x;
}
return sum / total;
}
// Interleaved gradient noise: a different offset each pixel and frame, for the ray march.
fn ign(px: vec2<f32>) -> f32 {
@@ -214,7 +264,13 @@ fn fs_light(in: FullOut) -> @location(0) vec4<f32> {
// Shadowed sky light (ambient) keeps vanilla's look, blocks' light stays as is; the sun adds
// direct light by the face's angle.
let direct = frame.sun_color.rgb * sun_on * max(ndl, 0.0) * s * sky_reach;
var light = max(base * frame.ambient.x, block * frame.ambient.y) + direct;
// Contact shadows from the ambient occlusion: on the ambient and blocks' light fully, on
// the mods' lights by half, not on the sun or on emission.
var occlusion = 1.0;
if frame.ambient.w > 0.0 { occlusion = ao_at(px, length(p)); }
let ao_ambient = mix(1.0, occlusion, frame.ambient.w);
let ao_lights = mix(1.0, occlusion, frame.ambient.w * 0.5);
var light = max(base * frame.ambient.x, block * frame.ambient.y) * ao_ambient + direct;
// The mods' lights.
for (var k = 0u; k < surface_count; k++) {
let l = lights[select(tiles[surface_start + k], k, surface_all)];
@@ -224,7 +280,7 @@ fn fs_light(in: FullOut) -> @location(0) vec4<f32> {
let window = pow(clamp(1.0 - pow(dist / l.pos.w, 4.0), 0.0, 1.0), 2.0);
let falloff = l.color.w / (dist * dist + 1.0) * window;
let k = max(dot(n, to / max(dist, 0.001)) * 0.85 + 0.15, 0.0);
light += l.color.rgb * falloff * k;
light += l.color.rgb * falloff * k * ao_lights;
}
c = albedo.rgb * light + albedo.rgb * albedo.a * 1.5;
// Vanilla's fog over it again.
@@ -264,6 +320,131 @@ fn fs_light(in: FullOut) -> @location(0) vec4<f32> {
}
"#;
const AO: &str = r#"
const AO_RADIUS: f32 = 1.8;
const AO_SLICES: i32 = 3;
const AO_STEPS: i32 = 5;
const PI: f32 = 3.14159265;
@group(0) @binding(0) var<uniform> frame: HdFrame;
@group(0) @binding(1) var depth_tex: texture_depth_2d;
@group(0) @binding(2) var normal_tex: texture_2d<f32>;
// Interleaved gradient noise, shifted per frame (params.w) and per use.
fn noise(px: vec2<f32>, shift: vec2<f32>) -> f32 {
let p = px + shift + vec2<f32>(5.588238 * frame.params.w);
return fract(52.9829189 * fract(dot(p, vec2<f32>(0.06711056, 0.00583715))));
}
// The camera-relative position of a (continuous) full-resolution pixel at depth z.
fn position_at(px: vec2<f32>, z: f32) -> vec3<f32> {
let uv = px * frame.resolution.zw;
let h = frame.inverse_view_proj * vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, z, 1.0);
return h.xyz / h.w;
}
// Ground-truth ambient occlusion (horizon based): per slice through the view ray, the highest
// horizon on either side, integrated against the normal's cosine lobe. Half resolution: one
// pixel of each 2x2.
@fragment
fn fs_ao(in: FullOut) -> @location(0) vec2<f32> {
let size = vec2<i32>(textureDimensions(depth_tex));
let ic = min(vec2<i32>(in.position.xy) * 2, size - 1);
let z = textureLoad(depth_tex, ic, 0);
if z <= 0.0 { return vec2<f32>(1.0, 0.0); }
let nrm = textureLoad(normal_tex, ic, 0).xyz;
let c = vec2<f32>(ic) + 0.5;
let p = position_at(c, z);
let dist = length(p);
if dot(nrm, nrm) < 0.01 { return vec2<f32>(1.0, dist); }
let n = normalize(nrm);
let v = -p / dist;
// Blocks per pixel here (the plane of equal depth is square to the view), so how far in
// pixels the radius reaches.
let per_px = max(length(position_at(c + vec2<f32>(4.0, 0.0), z) - p) / 4.0, 0.00001);
let reach = min(AO_RADIUS / per_px, 56.0);
if reach < 2.0 { return vec2<f32>(1.0, dist); }
let radius = reach * per_px;
let rot = noise(in.position.xy, vec2<f32>(0.0));
let jitter = noise(in.position.xy, vec2<f32>(37.0, 17.0));
var visibility = 0.0;
for (var s = 0; s < AO_SLICES; s++) {
let phi = (f32(s) + rot) / f32(AO_SLICES) * PI;
let d2 = vec2<f32>(cos(phi), sin(phi));
// The slice's direction in space, square to the view ray, and its plane's axis.
let q = position_at(c + d2 * 4.0, z) - p;
let dir = normalize(q - v * dot(q, v));
let axis = cross(dir, v);
let projected = n - axis * dot(n, axis);
let plen = length(projected);
if plen < 0.0001 { visibility += 1.0; continue; }
let cos_n = clamp(dot(projected, v) / plen, -1.0, 1.0);
let nang = select(-1.0, 1.0, dot(projected, dir) >= 0.0) * acos(cos_n);
var c_neg = -1.0;
var c_pos = -1.0;
for (var i = 0; i < AO_STEPS; i++) {
let t = (f32(i) + jitter) / f32(AO_STEPS);
let r = 1.5 + (reach - 1.5) * t * t;
for (var side = 0; side < 2; side++) {
let sg = select(-1.0, 1.0, side == 1);
let ip = vec2<i32>(floor(c + d2 * (r * sg)));
if any(ip < vec2<i32>(0)) || any(ip >= size) { continue; }
let sz = textureLoad(depth_tex, ip, 0);
if sz <= 0.0 { continue; }
let to = position_at(vec2<f32>(ip) + 0.5, sz) - p;
let len = length(to);
// Points on (or under) the surface's own plane don't occlude it.
if dot(to, n) < 0.1 * len { continue; }
// Far points count less, to nothing at the radius.
let fall = clamp((len - radius * 0.6) / (radius * 0.4), 0.0, 1.0);
let ch = mix(dot(to / len, v), -1.0, fall);
if side == 1 { c_pos = max(c_pos, ch); } else { c_neg = max(c_neg, ch); }
}
}
var h_neg = -acos(clamp(c_neg, -1.0, 1.0));
var h_pos = acos(clamp(c_pos, -1.0, 1.0));
h_neg = nang + max(h_neg - nang, -0.5 * PI);
h_pos = nang + min(h_pos - nang, 0.5 * PI);
let sn = sin(nang);
let arc_neg = cos_n + 2.0 * h_neg * sn - cos(2.0 * h_neg - nang);
let arc_pos = cos_n + 2.0 * h_pos * sn - cos(2.0 * h_pos - nang);
visibility += plen * 0.25 * (arc_neg + arc_pos);
}
let ao = clamp(visibility / f32(AO_SLICES), 0.0, 1.0);
// Far away it is too coarse to show: fade out.
return vec2<f32>(mix(1.0, ao, 1.0 - smoothstep(40.0, 96.0, dist)), dist);
}
"#;
const AO_BLUR: &str = r#"
@group(0) @binding(0) var<uniform> frame: HdFrame;
@group(0) @binding(1) var raw_ao: texture_2d<f32>;
// A 5x5 blur that only takes texels at about the same distance (so not across an edge).
@fragment
fn fs_ao_blur(in: FullOut) -> @location(0) vec2<f32> {
let size = vec2<i32>(textureDimensions(raw_ao));
let ip = vec2<i32>(in.position.xy);
let centre = textureLoad(raw_ao, ip, 0).xy;
if centre.y <= 0.0 { return centre; }
let tolerance = 0.03 * centre.y + 0.1;
var sum = 0.0;
var total = 0.0;
for (var y = -2; y <= 2; y++) {
for (var x = -2; x <= 2; x++) {
let q = ip + vec2<i32>(x, y);
if any(q < vec2<i32>(0)) || any(q >= size) { continue; }
let s = textureLoad(raw_ao, q, 0).xy;
if s.y <= 0.0 { continue; }
let dz = (s.y - centre.y) / tolerance;
let w = 1.0 / (1.0 + dz * dz * dz * dz);
sum += s.x * w;
total += w;
}
}
return vec2<f32>(sum / max(total, 0.0001), centre.y);
}
"#;
const BLOOM: &str = r#"
@group(0) @binding(0) var<uniform> frame: HdFrame;
@group(0) @binding(1) var source: texture_2d<f32>;
@@ -434,6 +615,23 @@ pub struct Hd {
up: wgpu::RenderPipeline,
tone_layout: wgpu::BindGroupLayout,
tone: wgpu::RenderPipeline,
/// The ambient occlusion: its strength in the lighting, the half-resolution targets (raw, then
/// blurred), their passes and bind groups (made at `resize`).
pub ao_strength: f32,
ao_raw: wgpu::TextureView,
ao_blurred: wgpu::TextureView,
ao_layout: wgpu::BindGroupLayout,
ao_blur_layout: wgpu::BindGroupLayout,
ao_pipeline: wgpu::RenderPipeline,
ao_blur_pipeline: wgpu::RenderPipeline,
ao_group: Option<wgpu::BindGroup>,
ao_blur_group: Option<wgpu::BindGroup>,
/// GPU time of the HD passes while diagnostics ask for it (`set_timing`).
timing: Option<PassTiming>,
/// Bind groups made so far, and in the last frame (a steady state makes none).
groups_made: AtomicU64,
groups_seen: u64,
pub groups_last_frame: u64,
}
/// The tiles' header (4 words each) and index lists for a screen of `size`.
@@ -567,6 +765,22 @@ fn tile_lists(
}
}
/// The timestamps of the pass `name` while HD passes are timed.
fn stamp<'a>(
timing: &'a mut Option<PassTiming>,
name: &str,
) -> Option<wgpu::RenderPassTimestampWrites<'a>> {
timing.as_mut()?.writes(name)
}
/// `HORIZON_HD_AO=0` turns the ambient occlusion off, another number sets its strength.
fn ao_strength_default() -> f32 {
std::env::var("HORIZON_HD_AO")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(AO_STRENGTH)
}
fn module(device: &wgpu::Device, label: &str, body: &str) -> wgpu::ShaderModule {
device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some(label),
@@ -685,8 +899,17 @@ impl Hd {
has_dynamic_offset: false,
min_binding_size: None,
},
UNFILTERED,
]),
});
let ao_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("HD ambient occlusion"),
entries: &entries(&[UNIFORM, DEPTH, UNFILTERED]),
});
let ao_blur_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("HD ambient occlusion blur"),
entries: &entries(&[UNIFORM, UNFILTERED]),
});
let bloom_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("HD bloom"),
entries: &entries(&[UNIFORM, FLOAT, SAMPLER]),
@@ -698,6 +921,26 @@ impl Hd {
let light = module(device, "HD lighting", LIGHT);
let bloom = module(device, "HD bloom", BLOOM);
let tone = module(device, "HD tone mapping", TONEMAP);
let ao = module(device, "HD ambient occlusion", AO);
let ao_blur = module(device, "HD ambient occlusion blur", AO_BLUR);
let ao_pipeline = fullscreen(
device,
"HD ambient occlusion",
&ao_layout,
&ao,
"fs_ao",
AO_FORMAT,
None,
);
let ao_blur_pipeline = fullscreen(
device,
"HD ambient occlusion blur",
&ao_blur_layout,
&ao_blur,
"fs_ao_blur",
AO_FORMAT,
None,
);
let add = wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
@@ -858,6 +1101,19 @@ impl Hd {
up,
tone_layout,
tone,
ao_strength: ao_strength_default(),
ao_raw: target(device, "HD AO", [1, 1], AO_FORMAT).view,
ao_blurred: target(device, "HD AO blurred", [1, 1], AO_FORMAT).view,
ao_layout,
ao_blur_layout,
ao_pipeline,
ao_blur_pipeline,
ao_group: None,
ao_blur_group: None,
timing: None,
groups_made: AtomicU64::new(0),
groups_seen: 0,
groups_last_frame: 0,
};
hd.resize(device, size);
hd
@@ -875,6 +1131,28 @@ impl Hd {
self.depth = target(device, "HD depth", size, wgpu::TextureFormat::Depth32Float).view;
self.lit = target(device, "HD lit", size, HDR).view;
self.fx = target(device, "HD post", size, HDR).view;
let half = [size[0].div_ceil(2), size[1].div_ceil(2)];
self.ao_raw = target(device, "HD AO", half, AO_FORMAT).view;
self.ao_blurred = target(device, "HD AO blurred", half, AO_FORMAT).view;
self.ao_group = Some(self.make_group(
device,
"HD ambient occlusion",
&self.ao_layout,
&[
wgpu::BindingResource::Buffer(self.frame.as_entire_buffer_binding()),
wgpu::BindingResource::TextureView(&self.depth),
wgpu::BindingResource::TextureView(&self.normal),
],
));
self.ao_blur_group = Some(self.make_group(
device,
"HD ambient occlusion blur",
&self.ao_blur_layout,
&[
wgpu::BindingResource::Buffer(self.frame.as_entire_buffer_binding()),
wgpu::BindingResource::TextureView(&self.ao_raw),
],
));
self.tiles = tiles_buffer(device, size);
self.tiles_x = size[0].div_ceil(TILE).max(1);
self.bloom = (0..BLOOM_LEVELS)
@@ -917,6 +1195,15 @@ impl Hd {
);
queue.write_buffer(&self.tiles, 0, bytemuck::cast_slice(&self.tile_words));
self.frames = self.frames.wrapping_add(1);
let made = self.groups_made.load(Ordering::Relaxed);
self.groups_last_frame = made - self.groups_seen;
self.groups_seen = made;
if PassTiming::logging() && self.frames.is_multiple_of(240) {
log::info!(
"HD bind groups made in the last frame: {} ({made} in all)",
self.groups_last_frame
);
}
// The sun by day, the moon (opposite) by night, faded out round the horizon.
let (dir, strength, color) = light_of(scene);
let cascades = cascades(scene.camera, dir);
@@ -941,7 +1228,12 @@ impl Hd {
fog_color: scene.fog_color,
fog: scene.fog,
// In the shade by day a surface keeps half its sky light; at night almost all.
ambient: [0.5 + 0.45 * night, 1.0, 0.0018 + scene.rain * 0.006, 0.0],
ambient: [
0.5 + 0.45 * night,
1.0,
0.0018 + scene.rain * 0.006,
self.ao_strength.max(0.0),
],
shadow: [
if strength > 0.0 { 1.0 } else { 0.0 },
CASCADES[0],
@@ -954,13 +1246,14 @@ impl Hd {
/// The shadow pass of cascade `c`: its depth layer cleared, nothing else.
pub fn shadow_pass<'e>(
&self,
&mut self,
encoder: &'e mut wgpu::CommandEncoder,
c: usize,
) -> wgpu::RenderPass<'e> {
encoder
.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("HD shadow cascade"),
timestamp_writes: stamp(&mut self.timing, ["hd shadow 0", "hd shadow 1"][c.min(1)]),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.shadow_layers[c],
@@ -976,7 +1269,10 @@ impl Hd {
}
/// The G-buffer pass's attachments: albedo and normal cleared, its own depth.
pub fn gbuffer_pass<'e>(&self, encoder: &'e mut wgpu::CommandEncoder) -> wgpu::RenderPass<'e> {
pub fn gbuffer_pass<'e>(
&mut self,
encoder: &'e mut wgpu::CommandEncoder,
) -> wgpu::RenderPass<'e> {
let clear = |view| {
Some(wgpu::RenderPassColorAttachment {
view,
@@ -991,6 +1287,7 @@ impl Hd {
encoder
.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("HD G-buffer"),
timestamp_writes: stamp(&mut self.timing, "hd g-buffer"),
color_attachments: &[
clear(&self.albedo),
clear(&self.normal),
@@ -1016,9 +1313,11 @@ impl Hd {
load: bool,
pipeline: &wgpu::RenderPipeline,
group: &wgpu::BindGroup,
timestamp_writes: Option<wgpu::RenderPassTimestampWrites<'_>>,
) {
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some(label),
timestamp_writes,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: to,
resolve_target: None,
@@ -1054,6 +1353,7 @@ impl Hd {
lightmap.1.clone(),
);
if self.light_group.as_ref().is_none_or(|(k, _)| *k != key) {
self.groups_made.fetch_add(1, Ordering::Relaxed);
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("HD lighting"),
layout: &self.light_layout,
@@ -1110,6 +1410,10 @@ impl Hd {
binding: 12,
resource: self.tiles.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 13,
resource: wgpu::BindingResource::TextureView(&self.ao_blurred),
},
],
});
self.light_group = Some((key, group));
@@ -1124,10 +1428,36 @@ impl Hd {
false,
&self.light_pipeline,
group,
stamp(&mut self.timing, "hd lighting"),
);
}
/// A bind group of consecutive bindings 0.., counted (`groups_last_frame`).
fn make_group(
&self,
device: &wgpu::Device,
label: &str,
layout: &wgpu::BindGroupLayout,
resources: &[wgpu::BindingResource<'_>],
) -> wgpu::BindGroup {
self.groups_made.fetch_add(1, Ordering::Relaxed);
let entries: Vec<_> = resources
.iter()
.enumerate()
.map(|(i, r)| wgpu::BindGroupEntry {
binding: i as u32,
resource: r.clone(),
})
.collect();
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some(label),
layout,
entries: &entries,
})
}
fn bloom_group(&self, device: &wgpu::Device, source: &wgpu::TextureView) -> wgpu::BindGroup {
self.groups_made.fetch_add(1, Ordering::Relaxed);
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("HD bloom"),
layout: &self.bloom_layout,
@@ -1169,6 +1499,7 @@ impl Hd {
self.prefilter_group = Some((source.clone(), group));
}
if self.tone_group.as_ref().is_none_or(|(v, _)| *v != source) {
self.groups_made.fetch_add(1, Ordering::Relaxed);
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("HD tone mapping"),
layout: &self.tone_layout,
@@ -1205,6 +1536,7 @@ impl Hd {
false,
&self.prefilter,
prefilter,
stamp(&mut self.timing, BLOOM_NAMES[0]),
);
for k in 1..self.bloom.len() {
Self::draw(
@@ -1214,6 +1546,7 @@ impl Hd {
false,
&self.down,
&self.down_groups[k - 1],
stamp(&mut self.timing, BLOOM_NAMES[k]),
);
}
// Up: each level added onto the bigger one.
@@ -1225,9 +1558,84 @@ impl Hd {
true,
&self.up,
&self.up_groups[k - 1],
stamp(&mut self.timing, BLOOM_NAMES[BLOOM_LEVELS + k - 1]),
);
}
Self::draw(encoder, "HD tone mapping", screen, false, &self.tone, tone);
Self::draw(
encoder,
"HD tone mapping",
screen,
false,
&self.tone,
tone,
stamp(&mut self.timing, "hd tonemap"),
);
}
/// The ambient occlusion from the G-buffer's depth and normals: the half-resolution pass, then
/// its blur. Run after the G-buffer pass; nothing when the strength is 0.
pub fn ao(&mut self, encoder: &mut wgpu::CommandEncoder) {
if self.ao_strength <= 0.0 {
return;
}
let (Some(raw), Some(blur)) = (&self.ao_group, &self.ao_blur_group) else {
return;
};
Self::draw(
encoder,
"HD ambient occlusion",
&self.ao_raw,
false,
&self.ao_pipeline,
raw,
stamp(&mut self.timing, "hd ao"),
);
Self::draw(
encoder,
"HD ambient occlusion blur",
&self.ao_blurred,
false,
&self.ao_blur_pipeline,
blur,
stamp(&mut self.timing, "hd ao blur"),
);
}
/// Times the HD passes on the GPU while `on` (and the device can), else not.
pub fn set_timing(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, on: bool) {
if on != self.timing.is_some() {
self.timing = on.then(|| PassTiming::new(device, queue)).flatten();
}
}
/// At the start of the frame's passes, before the first of them.
pub fn timing_begin(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
if let Some(t) = &mut self.timing {
t.begin(device, queue);
}
}
/// After the frame is submitted.
pub fn timing_submitted(&mut self, queue: &wgpu::Queue) {
if let Some(t) = &mut self.timing {
t.submitted(queue);
}
}
/// Each HD pass's median GPU time in milliseconds (bloom's passes summed into one).
pub fn pass_times(&self) -> Vec<(String, f32)> {
let Some(t) = &self.timing else {
return Vec::new();
};
let mut out: Vec<(String, f32)> = Vec::new();
for (name, ms) in t.medians() {
let name = name.split('#').next().unwrap_or(&name).to_owned();
match out.iter_mut().find(|o| o.0 == name) {
Some(o) => o.1 += ms,
None => out.push((name, ms)),
}
}
out
}
}
@@ -1286,7 +1694,13 @@ mod tests {
#[test]
fn lighting_shader_parses() {
for (name, body) in [("light", LIGHT), ("bloom", BLOOM)] {
for (name, body) in [
("light", LIGHT),
("bloom", BLOOM),
("tonemap", TONEMAP),
("ao", AO),
("ao blur", AO_BLUR),
] {
let source = format!("{COMMON}{body}");
let module = naga::front::wgsl::parse_str(&source).unwrap_or_else(|e| {
panic!("{name}: {}", e.emit_to_string(&source));