Files
horizon-airdef/crates/horizon-client/src/gfx/hd.rs
T

2739 lines
109 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! AirDef fork: HD lighting. Before the world pass the solid terrain and the
//! entities (with the mods' models) are drawn once more into a G-buffer: the
//! surface colour without light and its normal. After the world pass the
//! mods' point lights (rocket flames, flares, blasts) light every pixel of it
//! 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;
pub const NORMAL: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
/// Sky and block light per pixel.
pub const LIGHT_LEVELS: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
/// The lit world and the post pass's output.
pub const HDR: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
/// The water pass's targets: the surface colour with the block light, and the normal with the sky light.
pub const WATER_TINT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
pub const WATER_NORMAL: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
/// The most lights drawn a frame.
pub const MAX_LIGHTS: usize = 512;
/// The side (pixels) of a tile of the screen with its own short list of lights.
const TILE: u32 = 16;
/// The indices all the tile lists may hold together; a tile past it loops over every light.
const TILE_INDICES: usize = 1 << 19;
/// A list length that means "every light": the list overflowed.
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)]
#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
pub struct HdLight {
/// xyz: camera-relative position; w: radius.
pub pos: [f32; 4],
/// rgb: colour; w: intensity.
pub color: [f32; 4],
}
/// The frame's HD settings.
#[derive(Clone, Copy, Debug)]
pub struct HdSettings {
pub exposure: f32,
pub bloom: f32,
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct HdFrame {
/// Clip space to camera-relative position.
inverse_view_proj: [[f32; 4]; 4],
/// width, height, 1/width, 1/height.
resolution: [f32; 4],
/// lights, exposure, bloom, a frame counter.
params: [f32; 4],
/// The shadow cascades: camera-relative position to the light's clip space.
cascades: [[[f32; 4]; 4]; 2],
/// xyz: towards the sun (or the moon at night); w: how much it lights (0 set or hidden).
sun: [f32; 4],
sun_color: [f32; 4],
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);
/// 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],
/// The previous frame's camera-relative view-projection without jitter (for TAA).
prev_view_proj: [[f32; 4]; 4],
/// xyz: how far the camera moved since that frame; w: 1 when the history is usable.
taa: [f32; 4],
/// x: the history's weight; y: the sharpening (0 without TAA); zw: the jitter in world pixels.
taa_params: [f32; 4],
/// The (jittered) world-to-clip matrix the world was drawn with (rays in the water pass).
view_proj: [[f32; 4]; 4],
/// x: the water effect runs this frame; y: seconds for the waves (wraps at 600); zw: the
/// camera's x and z modulo 256, the waves' period.
water: [f32; 4],
/// rgb: the sky's colour; w: 1 when there is a sky.
sky_color: [f32; 4],
}
/// What the world around looks like this frame (from the renderer's globals).
#[derive(Clone, Copy, Debug)]
pub struct HdScene {
/// The shadow cascades' matrices (`cascades`; the far one may be a frame or two old).
pub cascades: [Mat4; 2],
/// The (jittered) projection the world was drawn with.
pub view_proj: Mat4,
/// Last frame's view-projection without jitter, and the camera's move since (TAA).
pub prev_view_proj: Mat4,
pub camera_delta: glam::Vec3,
/// This frame is anti-aliased over time (the projection is jittered).
pub taa: bool,
/// The jitter in world-target pixels, screen orientation (x right, y down): the world's sample
/// of a pixel lies this far from its centre (the upscaler weighs samples by it).
pub jitter_px: [f32; 2],
/// Towards the sun, and the sky's darkening (0 day, 1 night).
pub sun: glam::Vec3,
pub dark: f32,
pub rain: f32,
pub fog_color: [f32; 4],
pub fog: [f32; 4],
/// The sky has a sun at all (the Overworld).
pub sky: bool,
pub sky_color: [f32; 3],
/// The camera's x and z modulo 256 (the waves' period), so the waves hold still in the world.
pub camera_mod: [f32; 2],
/// The water effect may run (not underwater, not disabled).
pub water: bool,
}
/// The cascades' half sizes (blocks) and shadow map size.
pub const CASCADES: [f32; 2] = [40.0, 176.0];
pub const SHADOW_SIZE: u32 = 2048;
const COMMON: &str = r#"
struct HdFrame {
inverse_view_proj: mat4x4<f32>,
resolution: vec4<f32>,
params: vec4<f32>,
cascades: array<mat4x4<f32>, 2>,
sun: vec4<f32>,
sun_color: vec4<f32>,
fog_color: vec4<f32>,
fog: vec4<f32>,
ambient: vec4<f32>,
shadow: vec4<f32>,
prev_view_proj: mat4x4<f32>,
taa: vec4<f32>,
taa_params: vec4<f32>,
view_proj: mat4x4<f32>,
water: vec4<f32>,
sky_color: vec4<f32>,
}
struct FullOut {
@builtin(position) position: vec4<f32>,
@location(0) uv: vec2<f32>,
}
@vertex
fn vs_full(@builtin(vertex_index) i: u32) -> FullOut {
let uv = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
var out: FullOut;
out.position = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0);
out.uv = uv;
return out;
}
"#;
const LIGHT: &str = r#"
struct Light {
pos: vec4<f32>,
color: vec4<f32>,
}
@group(0) @binding(0) var<uniform> frame: HdFrame;
@group(0) @binding(1) var scene_color: texture_2d<f32>;
@group(0) @binding(2) var scene_depth: texture_depth_2d;
@group(0) @binding(3) var albedo_tex: texture_2d<f32>;
@group(0) @binding(4) var normal_tex: texture_2d<f32>;
@group(0) @binding(5) var gbuffer_depth: texture_depth_2d;
@group(0) @binding(6) var<storage, read> lights: array<Light>;
@group(0) @binding(7) var light_tex: texture_2d<f32>;
@group(0) @binding(8) var shadow_map: texture_depth_2d_array;
@group(0) @binding(9) var shadow_sampler: sampler_comparison;
@group(0) @binding(10) var lightmap: texture_2d<f32>;
@group(0) @binding(11) var linear: sampler;
// Per tile of 16x16 pixels: where its surface list and its halo list start in this array and
// 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 water pass's depth: the nearest water surface (0 where there is none).
@group(0) @binding(14) var water_depth: texture_depth_2d;
// 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 {
let p = px + vec2<f32>(5.588238 * frame.params.w);
return fract(52.9829189 * fract(dot(p, vec2<f32>(0.06711056, 0.00583715))));
}
// Where a camera-relative point falls in cascade c: uv and depth.
fn cascade_at(p: vec3<f32>, c: i32) -> vec3<f32> {
let s = frame.cascades[c] * vec4<f32>(p, 1.0);
return vec3<f32>(s.x * 0.5 + 0.5, 0.5 - s.y * 0.5, s.z);
}
// The sun's (or moon's) light reaching p: 1 lit, 0 in shadow; soft-edged.
fn shadow(p: vec3<f32>, n: vec3<f32>) -> f32 {
return shadow_taps(p, n, 1);
}
// `shadow` with a (2 * r + 1) square of taps: the floor under water takes one (the water dims and
// blurs it anyway).
fn shadow_taps(p: vec3<f32>, n: vec3<f32>, r: i32) -> f32 {
let dist = length(p);
let c = select(1, 0, dist < frame.shadow.y * 0.92);
let texel = select(frame.shadow.z, frame.shadow.y, c == 0) * 2.0 / 2048.0;
let q = p + n * texel * 1.5;
let s = cascade_at(q, c);
if any(s.xy < vec2<f32>(0.0)) || any(s.xy > vec2<f32>(1.0)) || s.z > 1.0 { return 1.0; }
var lit = 0.0;
let step = 1.0 / 2048.0;
for (var y = -r; y <= r; y++) {
for (var x = -r; x <= r; x++) {
lit += textureSampleCompareLevel(shadow_map, shadow_sampler, s.xy + vec2<f32>(f32(x), f32(y)) * step, c, s.z - 0.0005);
}
}
let fade = clamp((frame.shadow.z - dist) / 16.0, 0.0, 1.0);
return mix(1.0, lit / f32((2 * r + 1) * (2 * r + 1)), fade);
}
// One shadow sample, for the rays through the air.
fn lit_at(p: vec3<f32>) -> f32 {
let s = cascade_at(p, 1);
if any(s.xy < vec2<f32>(0.0)) || any(s.xy > vec2<f32>(1.0)) || s.z > 1.0 { return 1.0; }
return textureSampleCompareLevel(shadow_map, shadow_sampler, s.xy, 1, s.z - 0.001);
}
fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
if d <= start { return 0.0; }
if d >= end { return 1.0; }
return (d - start) / (end - start);
}
@fragment
fn fs_light(in: FullOut) -> @location(0) vec4<f32> {
let px = vec2<i32>(in.position.xy);
let scene = textureLoad(scene_color, px, 0).rgb;
let d = textureLoad(scene_depth, px, 0);
let g = textureLoad(gbuffer_depth, px, 0);
// Water in front of the opaque world with nothing translucent over it: here the floor is lit
// and the water composite lays the surface over it (it knows the pixel by the alpha 0.5).
var water = false;
if frame.water.x > 0.5 && g > 0.0 {
let wd = textureLoad(water_depth, px, 0);
water = wd > 0.0 && wd >= g && d - wd <= d * 0.002;
}
let dd = select(d, g, water);
let ndc = vec4<f32>(in.uv.x * 2.0 - 1.0, 1.0 - in.uv.y * 2.0, max(dd, 0.000001), 1.0);
let h = frame.inverse_view_proj * ndc;
let p = h.xyz / h.w;
let view = normalize(p);
let sun = frame.sun.xyz;
let sun_on = frame.sun.w;
let count = u32(frame.params.x);
let tile = ((u32(px.y) >> 4u) * u32(frame.shadow.w) + (u32(px.x) >> 4u)) * 4u;
let surface_start = tiles[tile];
let surface_all = tiles[tile + 1u] == 0xffffffffu;
let surface_count = select(tiles[tile + 1u], count, surface_all);
let halo_start = tiles[tile + 2u];
let halo_all = tiles[tile + 3u] == 0xffffffffu;
let halo_count = select(tiles[tile + 3u], count, halo_all);
var c = scene;
let surface = water || (d > 0.0 && abs(d - g) <= max(d, g) * 0.002);
if surface {
let n = normalize(textureLoad(normal_tex, px, 0).xyz);
let albedo = textureLoad(albedo_tex, px, 0);
let lm = textureLoad(light_tex, px, 0).xy;
// Vanilla's light (sky and blocks through the lightmap), shaded where the sun can't reach.
let base = textureSampleLevel(lightmap, linear, clamp(vec2<f32>(lm.y, lm.x) * (15.0 / 16.0) + 0.5 / 16.0, vec2<f32>(0.5 / 16.0), vec2<f32>(15.5 / 16.0)), 0.0).rgb;
let block = textureSampleLevel(lightmap, linear, vec2<f32>(lm.y * (15.0 / 16.0) + 0.5 / 16.0, 0.5 / 16.0), 0.0).rgb;
let sky_reach = smoothstep(0.35, 0.95, lm.x);
var s = 1.0;
let ndl = dot(n, sun);
if sun_on > 0.0 && ndl > 0.0 && sky_reach > 0.0 { s = shadow_taps(p, n, select(1, 0, water)); } else { s = 0.0; }
// 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;
// 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;
// (The water dims and blurs the floor under it: no occlusion there.)
if frame.ambient.w > 0.0 && !water { 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)];
let to = l.pos.xyz - p;
let dist = length(to);
if dist >= l.pos.w { continue; }
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 * ao_lights;
}
c = albedo.rgb * light + albedo.rgb * albedo.a * 1.5;
// Vanilla's fog over it again.
let sph = length(p);
let cyl = max(length(p.xz), abs(p.y));
let f = max(linear_fog(sph, frame.fog.x, frame.fog.y), linear_fog(cyl, frame.fog.z, frame.fog.w));
c = mix(c, frame.fog_color.rgb, f * frame.fog_color.a);
}
// Light in the air: the sun's rays between the shadows, and halos round the mods' lights.
let far = select(min(length(p), frame.shadow.z), frame.shadow.z, d <= 0.0);
let density = frame.ambient.z;
if sun_on > 0.0 && density > 0.0 {
let steps = 14;
let jitter = ign(in.position.xy);
var acc = 0.0;
for (var i = 0; i < steps; i++) {
let t = (f32(i) + jitter) / f32(steps) * far;
acc += lit_at(view * t);
}
// Henyey-Greenstein, forward scattering: brightest looking towards the sun.
let cos_t = dot(view, sun);
let gk = 0.6;
let phase = (1.0 - gk * gk) / pow(1.0 + gk * gk - 2.0 * gk * cos_t, 1.5) * 0.08;
c += frame.sun_color.rgb * sun_on * (acc / f32(steps)) * phase * (1.0 - exp(-far * density));
}
for (var k = 0u; k < halo_count; k++) {
let l = lights[select(tiles[halo_start + k], k, halo_all)];
// Nearest point of the view ray to the light, and the glow along the ray in front of it.
let t0 = dot(l.pos.xyz, view);
let hh = length(l.pos.xyz - view * t0) + 0.5;
if hh > l.pos.w * 0.5 { continue; }
let a0 = atan((0.0 - t0) / hh);
let a1 = atan((far - t0) / hh);
c += l.color.rgb * l.color.w * (a1 - a0) / hh * 0.004 * (0.3 + density * 300.0);
}
return vec4<f32>(c, select(1.0, 0.5, water));
}
"#;
const WATER: &str = r#"
const PI: f32 = 3.14159265;
const REFLECT_STEPS: i32 = 24;
const REFLECT_RANGE: f32 = 96.0;
@group(0) @binding(0) var<uniform> frame: HdFrame;
@group(0) @binding(1) var lit_tex: texture_2d<f32>;
@group(0) @binding(2) var gbuffer_depth: texture_depth_2d;
@group(0) @binding(3) var water_tint: texture_2d<f32>;
@group(0) @binding(4) var water_normal: texture_2d<f32>;
@group(0) @binding(5) var water_depth: texture_depth_2d;
@group(0) @binding(6) var shadow_map: texture_depth_2d_array;
@group(0) @binding(7) var shadow_sampler: sampler_comparison;
@group(0) @binding(8) var lightmap: texture_2d<f32>;
@group(0) @binding(9) var linear: sampler;
fn ign(px: vec2<f32>) -> f32 {
let p = px + 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 the screen point `uv` at depth z.
fn position_at(uv: vec2<f32>, z: f32) -> vec3<f32> {
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;
}
// The screen point (uv, clip w) of a camera-relative position.
fn project(p: vec3<f32>) -> vec3<f32> {
let c = frame.view_proj * vec4<f32>(p, 1.0);
return vec3<f32>(c.x / c.w * 0.5 + 0.5, 0.5 - c.y / c.w * 0.5, c.w);
}
fn on_screen(uv: vec2<f32>) -> bool {
return all(uv > vec2<f32>(0.0)) && all(uv < vec2<f32>(1.0));
}
fn texel(uv: vec2<f32>) -> vec2<i32> {
return clamp(vec2<i32>(uv * frame.resolution.xy), vec2<i32>(0), vec2<i32>(frame.resolution.xy) - 1);
}
// Sine waves in world space: wave vectors that are whole multiples of 2 pi / 256 and speeds that
// are whole cycles per 600 s, so the sum repeats every 256 blocks and 10 minutes and holds still
// in the world as the camera moves. x, y: the vector in units of 2 pi / 256; z: the slope the
// wave adds; w: its phase.
const WAVES = array<vec4<f32>, 10>(
vec4<f32>(3.0, 1.0, 0.040, 0.3),
vec4<f32>(-2.0, 5.0, 0.045, 2.1),
vec4<f32>(7.0, 2.0, 0.040, 4.4),
vec4<f32>(-5.0, -9.0, 0.040, 1.2),
vec4<f32>(11.0, -4.0, 0.035, 5.6),
vec4<f32>(13.0, 10.0, 0.035, 3.3),
vec4<f32>(-17.0, 7.0, 0.030, 0.9),
vec4<f32>(9.0, 23.0, 0.030, 2.7),
vec4<f32>(-27.0, 19.0, 0.025, 4.9),
vec4<f32>(31.0, 30.0, 0.025, 1.8),
);
// The gradient of the water's height at world x, z: the waves that a pixel `footprint` blocks
// wide can still resolve (finer ones fade out, or they would shimmer).
fn wave_gradient(xz: vec2<f32>, footprint: f32) -> vec2<f32> {
var grad = vec2<f32>(0.0);
for (var i = 0; i < 10; i++) {
let w = WAVES[i];
let k = w.xy * (2.0 * PI / 256.0);
let len = length(k);
let fade = clamp((2.0 * PI / len) / max(footprint, 0.0001) * 0.25 - 0.5, 0.0, 1.0);
let cycles = round(sqrt(9.8 * len) * 0.5 * 600.0 / (2.0 * PI));
let omega = cycles * 2.0 * PI / 600.0;
let phase = dot(k, xz) - omega * frame.water.y + w.w;
grad += (k / len) * (w.z * fade * cos(phase));
}
return grad;
}
fn cascade_at(p: vec3<f32>, c: i32) -> vec3<f32> {
let s = frame.cascades[c] * vec4<f32>(p, 1.0);
return vec3<f32>(s.x * 0.5 + 0.5, 0.5 - s.y * 0.5, s.z);
}
// The sun's (or moon's) light reaching p: 1 lit, 0 in shadow (as the lighting pass has it).
fn shadow(p: vec3<f32>, n: vec3<f32>) -> f32 {
let dist = length(p);
let c = select(1, 0, dist < frame.shadow.y * 0.92);
let texel_size = select(frame.shadow.z, frame.shadow.y, c == 0) * 2.0 / 2048.0;
let q = p + n * texel_size * 1.5;
let s = cascade_at(q, c);
if any(s.xy < vec2<f32>(0.0)) || any(s.xy > vec2<f32>(1.0)) || s.z > 1.0 { return 1.0; }
var lit = 0.0;
let step = 1.0 / 2048.0;
for (var y = -1; y <= 1; y++) {
for (var x = -1; x <= 1; x++) {
lit += textureSampleCompareLevel(shadow_map, shadow_sampler, s.xy + vec2<f32>(f32(x), f32(y)) * step, c, s.z - 0.0005);
}
}
let fade = clamp((frame.shadow.z - dist) / 16.0, 0.0, 1.0);
return mix(1.0, lit / 9.0, fade);
}
fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
if d <= start { return 0.0; }
if d >= end { return 1.0; }
return (d - start) / (end - start);
}
// What the sky shows along r when the ray leaves the screen: the horizon's colour rising to
// the zenith's, darker where the water lies under cover (`vis` is the sky light there).
fn sky_along(r: vec3<f32>, vis: f32) -> vec3<f32> {
var c = frame.fog_color.rgb;
if frame.sky_color.w > 0.5 {
c = mix(frame.fog_color.rgb, frame.sky_color.rgb, smoothstep(0.0, 0.5, r.y));
}
return c * mix(0.12, 1.0, vis);
}
// Marches the ray from p along r over the depth buffer (28 steps, growing, jittered so TAA
// averages the placement; then a binary search for the crossing). xyz: the colour found,
// w: how much to trust it (0 for a miss, less near the screen's edge).
fn reflection(p: vec3<f32>, r: vec3<f32>, jitter: f32) -> vec4<f32> {
var near = 0.0;
for (var i = 0; i < REFLECT_STEPS; i++) {
let u = (f32(i) + jitter) / f32(REFLECT_STEPS);
let s = 0.12 + REFLECT_RANGE * u * u;
let q = p + r * s;
let sp = project(q);
if sp.z <= 0.0 || !on_screen(sp.xy) { break; }
let z = textureLoad(gbuffer_depth, texel(sp.xy), 0);
if z > 0.0 {
let c = frame.view_proj * vec4<f32>(q, 1.0);
// Reversed Z: a larger depth is nearer; the ray is behind the surface when the
// surface is nearer than it.
if z > c.z / c.w {
let behind = length(q) - length(position_at(sp.xy, z));
if behind < 0.4 + 0.08 * s {
var lo = near;
var hi = s;
for (var k = 0; k < 5; k++) {
let m = 0.5 * (lo + hi);
let mq = p + r * m;
let mp = project(mq);
let mc = frame.view_proj * vec4<f32>(mq, 1.0);
let mz = textureLoad(gbuffer_depth, texel(mp.xy), 0);
if mz > mc.z / mc.w { hi = m; } else { lo = m; }
}
let hp = project(p + r * hi);
let edge = min(min(hp.x, 1.0 - hp.x), min(hp.y, 1.0 - hp.y));
let colour = textureSampleLevel(lit_tex, linear, hp.xy, 0.0).rgb;
return vec4<f32>(colour, smoothstep(0.0, 0.08, edge));
}
}
}
near = s;
}
return vec4<f32>(0.0);
}
// The sun's glint on the waves (GGX, a rough lobe so it glitters instead of aliasing).
fn glint(n: vec3<f32>, v: vec3<f32>, l: vec3<f32>) -> f32 {
let h = normalize(l + v);
let a = 0.05;
let nh = max(dot(n, h), 0.0);
let d = a * a / (PI * pow(nh * nh * (a * a - 1.0) + 1.0, 2.0));
let f = 0.02 + 0.98 * pow(1.0 - max(dot(v, h), 0.0), 5.0);
return min(d * f * 0.25 * max(dot(n, l), 0.0) / max(dot(n, v), 0.1), 12.0);
}
// The water over the lit world: the world behind it (refracted by the waves, dimmed and tinted
// by the water's depth), the sky and the world above it (a screen-space reflection) by Fresnel,
// and the sun's glint. Pixels without water pass through.
@fragment
fn fs_water(in: FullOut) -> @location(0) vec4<f32> {
let px = vec2<i32>(in.position.xy);
let base = textureLoad(lit_tex, px, 0);
if base.a > 0.75 { return vec4<f32>(base.rgb, 1.0); }
let wd = textureLoad(water_depth, px, 0);
let g = textureLoad(gbuffer_depth, px, 0);
let tint = textureLoad(water_tint, px, 0);
let nt = textureLoad(water_normal, px, 0);
let p = position_at(in.uv, wd);
let dist = length(p);
let v = -p / dist;
let geometric = normalize(nt.xyz * 2.0 - 1.0);
// The waves tilt the flat parts of the surface only.
let footprint = dist * frame.resolution.w * 1.4;
let grad = wave_gradient(p.xz + frame.water.zw, footprint);
let flat_part = smoothstep(0.6, 0.95, geometric.y);
var n = normalize(geometric + vec3<f32>(-grad.x, 0.0, -grad.y) * flat_part);
n = normalize(n + v * max(0.03 - dot(n, v), 0.0));
let ndv = max(dot(n, v), 0.02);
// Light on the water: vanilla's lightmap at the surface, and the sun where it reaches.
let levels = vec2<f32>(nt.a, tint.a);
let sky_reach = smoothstep(0.35, 0.95, levels.x);
let ambient = textureSampleLevel(lightmap, linear, clamp(vec2<f32>(levels.y, levels.x) * (15.0 / 16.0) + 0.5 / 16.0, vec2<f32>(0.5 / 16.0), vec2<f32>(15.5 / 16.0)), 0.0).rgb;
let block = textureSampleLevel(lightmap, linear, vec2<f32>(levels.y * (15.0 / 16.0) + 0.5 / 16.0, 0.5 / 16.0), 0.0).rgb;
let sun = frame.sun.xyz;
let sun_on = frame.sun.w;
var sunlit = 0.0;
if sun_on > 0.0 && sun.y > 0.0 && sky_reach > 0.0 { sunlit = shadow(p, vec3<f32>(0.0, 1.0, 0.0)) * sky_reach; }
let volume_light = max(ambient * frame.ambient.x, block * frame.ambient.y) + frame.sun_color.rgb * sun_on * sunlit * 0.8;
// Refraction: where the ray through the waves meets the world, against where the flat surface
// would send it (so still water looks as vanilla's and only the waves distort).
let floor0 = position_at(in.uv, g);
let depth0 = max(length(floor0) - dist, 0.0);
let bent = refract(-v, n, 0.75) - refract(-v, geometric, 0.75);
var uv_floor = in.uv;
var floor_z = g;
let moved = project(floor0 + bent * min(depth0, 24.0));
if moved.z > 0.0 && on_screen(moved.xy) {
let z = textureLoad(gbuffer_depth, texel(moved.xy), 0);
// Only what lies behind the water: not the bank or an entity in front of it.
if z > 0.0 && z <= wd {
uv_floor = moved.xy;
floor_z = z;
}
}
let thickness = clamp(length(position_at(uv_floor, floor_z)) - dist, 0.0, 48.0);
let behind = textureSampleLevel(lit_tex, linear, uv_floor, 0.0).rgb;
// A deep, dark water: the biome's colour darkened and a little greyed, so it reads as
// depth rather than as bright paint.
let biome = clamp(tint.rgb, vec3<f32>(0.03), vec3<f32>(1.0));
let colour = mix(vec3<f32>(dot(biome, vec3<f32>(0.333))), biome, 0.8) * vec3<f32>(0.55, 0.68, 0.8);
// The colours the water takes up fastest are the ones it has the least of.
let absorb = exp(-(vec3<f32>(1.0) - colour) * 1.1 * (thickness + 0.3));
let refracted = behind * absorb + colour * volume_light * 0.6 * (vec3<f32>(1.0) - absorb);
// Reflection: the screen where the ray stays on it, the sky where it leaves it or misses.
var r = reflect(-v, n);
r.y = abs(r.y);
// Looking down onto it the reflection is a few percent of the picture: the sky alone does.
let fresnel = 0.02 + 0.98 * pow(1.0 - ndv, 5.0);
var hit = vec4<f32>(0.0);
if fresnel > 0.04 { hit = reflection(p, r, ign(in.position.xy)); }
let sky_vis = mix(0.15, 1.0, sky_reach);
let reflected = mix(sky_along(r, sky_vis), hit.rgb, hit.w);
var c = refracted * (1.0 - fresnel) + reflected * fresnel;
if sun_on > 0.0 && sunlit > 0.0 {
c += frame.sun_color.rgb * sun_on * sunlit * glint(n, v, sun);
}
// Vanilla's fog over it, at the surface.
let sph = dist;
let cyl = max(length(p.xz), abs(p.y));
let f = max(linear_fog(sph, frame.fog.x, frame.fog.y), linear_fog(cyl, frame.fog.z, frame.fog.w));
c = mix(c, frame.fog_color.rgb, f * frame.fog_color.a);
return vec4<f32>(max(c, vec3<f32>(0.0)), 1.0);
}
"#;
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>;
@group(0) @binding(2) var linear: sampler;
// The first step down keeps only what is brighter than white (a soft knee).
@fragment
fn fs_prefilter(in: FullOut) -> @location(0) vec4<f32> {
let c = textureSampleLevel(source, linear, in.uv, 0.0).rgb;
let peak = max(c.r, max(c.g, c.b));
let knee = 0.35;
let soft = clamp(peak - 0.85 + knee, 0.0, 2.0 * knee);
let weight = max(soft * soft / (4.0 * knee + 0.0001), peak - 0.85) / max(peak, 0.0001);
return vec4<f32>(c * weight, 1.0);
}
// 13 taps (Call of Duty: Advanced Warfare's bloom), half size each step.
@fragment
fn fs_down(in: FullOut) -> @location(0) vec4<f32> {
let t = 1.0 / vec2<f32>(textureDimensions(source));
let s = in.uv;
let a = textureSampleLevel(source, linear, s + t * vec2(-2.0, -2.0), 0.0).rgb;
let b = textureSampleLevel(source, linear, s + t * vec2(0.0, -2.0), 0.0).rgb;
let c = textureSampleLevel(source, linear, s + t * vec2(2.0, -2.0), 0.0).rgb;
let d = textureSampleLevel(source, linear, s + t * vec2(-2.0, 0.0), 0.0).rgb;
let e = textureSampleLevel(source, linear, s, 0.0).rgb;
let f = textureSampleLevel(source, linear, s + t * vec2(2.0, 0.0), 0.0).rgb;
let g = textureSampleLevel(source, linear, s + t * vec2(-2.0, 2.0), 0.0).rgb;
let h = textureSampleLevel(source, linear, s + t * vec2(0.0, 2.0), 0.0).rgb;
let i = textureSampleLevel(source, linear, s + t * vec2(2.0, 2.0), 0.0).rgb;
let j = textureSampleLevel(source, linear, s + t * vec2(-1.0, -1.0), 0.0).rgb;
let k = textureSampleLevel(source, linear, s + t * vec2(1.0, -1.0), 0.0).rgb;
let l = textureSampleLevel(source, linear, s + t * vec2(-1.0, 1.0), 0.0).rgb;
let m = textureSampleLevel(source, linear, s + t * vec2(1.0, 1.0), 0.0).rgb;
var o = e * 0.125 + (a + c + g + i) * 0.03125 + (b + d + f + h) * 0.0625 + (j + k + l + m) * 0.125;
return vec4<f32>(o, 1.0);
}
// A 3×3 tent, added onto the bigger level.
@fragment
fn fs_up(in: FullOut) -> @location(0) vec4<f32> {
let t = 1.0 / vec2<f32>(textureDimensions(source));
let s = in.uv;
var o = textureSampleLevel(source, linear, s, 0.0).rgb * 4.0;
o += (textureSampleLevel(source, linear, s + t * vec2(-1.0, 0.0), 0.0).rgb
+ textureSampleLevel(source, linear, s + t * vec2(1.0, 0.0), 0.0).rgb
+ textureSampleLevel(source, linear, s + t * vec2(0.0, -1.0), 0.0).rgb
+ textureSampleLevel(source, linear, s + t * vec2(0.0, 1.0), 0.0).rgb) * 2.0;
o += textureSampleLevel(source, linear, s + t * vec2(-1.0, -1.0), 0.0).rgb
+ textureSampleLevel(source, linear, s + t * vec2(1.0, -1.0), 0.0).rgb
+ textureSampleLevel(source, linear, s + t * vec2(-1.0, 1.0), 0.0).rgb
+ textureSampleLevel(source, linear, s + t * vec2(1.0, 1.0), 0.0).rgb;
return vec4<f32>(o / 16.0, 1.0);
}
"#;
const TONEMAP: &str = r#"
@group(0) @binding(0) var<uniform> frame: HdFrame;
@group(0) @binding(1) var hdr: texture_2d<f32>;
@group(0) @binding(2) var bloom: texture_2d<f32>;
@group(0) @binding(3) var linear: sampler;
@fragment
fn fs_tonemap(in: FullOut) -> @location(0) vec4<f32> {
var c = textureSampleLevel(hdr, linear, in.uv, 0.0).rgb;
// A slight sharpen after TAA (its history resampling softens): the centre against its four
// neighbours, kept within their range so it can't ring.
let k = frame.taa_params.y;
if k > 0.0 {
let t = 1.0 / vec2<f32>(textureDimensions(hdr));
let n0 = textureSampleLevel(hdr, linear, in.uv + vec2<f32>(t.x, 0.0), 0.0).rgb;
let n1 = textureSampleLevel(hdr, linear, in.uv - vec2<f32>(t.x, 0.0), 0.0).rgb;
let n2 = textureSampleLevel(hdr, linear, in.uv + vec2<f32>(0.0, t.y), 0.0).rgb;
let n3 = textureSampleLevel(hdr, linear, in.uv - vec2<f32>(0.0, t.y), 0.0).rgb;
let lo = min(min(n0, n1), min(min(n2, n3), c));
let hi = max(max(n0, n1), max(max(n2, n3), c));
c = clamp(c * (1.0 + 4.0 * k) - (n0 + n1 + n2 + n3) * k, lo, hi);
}
c = c * frame.params.y;
c += textureSampleLevel(bloom, linear, in.uv, 0.0).rgb * frame.params.z;
// Up to 0.8 as it is (vanilla's look); above it, rolled off towards white by the
// brightest channel, so hues hold instead of clipping.
let peak = max(c.r, max(c.g, c.b));
let t = 0.8;
if peak > t {
let x = (peak - t) / (1.0 - t);
let rolled = t + (1.0 - t) * (x / (1.0 + x));
c = c * (rolled / peak);
// Very bright light bleaches towards white, as film does.
c = mix(c, vec3<f32>(rolled), clamp((peak - 2.0) / 8.0, 0.0, 0.6));
}
// A light grade: a touch more colour, and a gentle S round the middle grey.
let luma = dot(c, vec3<f32>(0.2126, 0.7152, 0.0722));
c = max(mix(vec3<f32>(luma), c, 1.12), vec3<f32>(0.0));
c = mix(c, c * c * (3.0 - 2.0 * c), 0.18);
return vec4<f32>(c, 1.0);
}
"#;
const TAA: &str = r#"
struct TaaOut {
@location(0) color: vec4<f32>,
@location(1) history: vec4<f32>,
}
@group(0) @binding(0) var<uniform> frame: HdFrame;
@group(0) @binding(1) var source: texture_2d<f32>;
@group(0) @binding(2) var depth_tex: texture_depth_2d;
@group(0) @binding(3) var history: texture_2d<f32>;
@group(0) @binding(4) var linear: sampler;
fn to_ycocg(c: vec3<f32>) -> vec3<f32> {
return vec3<f32>(c.r * 0.25 + c.g * 0.5 + c.b * 0.25, c.r * 0.5 - c.b * 0.5, c.g * 0.5 - c.r * 0.25 - c.b * 0.25);
}
fn from_ycocg(c: vec3<f32>) -> vec3<f32> {
let t = c.x - c.z;
return vec3<f32>(t + c.y, c.x + c.z, t - c.y);
}
// Compress the range so a very bright pixel does not dominate the blend or the clamp.
fn squash(c: vec3<f32>) -> vec3<f32> {
return c / (1.0 + max(c.r, max(c.g, c.b)));
}
fn unsquash(c: vec3<f32>) -> vec3<f32> {
return c / max(1.0 - max(c.r, max(c.g, c.b)), 0.001);
}
// The history at a uv, filtered with a Catmull-Rom spline (five bilinear taps) so that
// resampling it every frame doesn't blur.
fn history_color(uv: vec2<f32>) -> vec3<f32> {
let size = vec2<f32>(textureDimensions(history));
let pos = uv * size;
let c1 = floor(pos - 0.5) + 0.5;
let f = pos - c1;
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 = (c1 - 1.0) / size;
let t3 = (c1 + 2.0) / size;
let t12 = (c1 + w2 / w12) / size;
var sum = textureSampleLevel(history, linear, vec2<f32>(t12.x, t0.y), 0.0).rgb * (w12.x * w0.y);
var total = w12.x * w0.y;
sum += textureSampleLevel(history, linear, vec2<f32>(t0.x, t12.y), 0.0).rgb * (w0.x * w12.y);
total += w0.x * w12.y;
sum += textureSampleLevel(history, linear, t12, 0.0).rgb * (w12.x * w12.y);
total += w12.x * w12.y;
sum += textureSampleLevel(history, linear, vec2<f32>(t3.x, t12.y), 0.0).rgb * (w3.x * w12.y);
total += w3.x * w12.y;
sum += textureSampleLevel(history, linear, vec2<f32>(t12.x, t3.y), 0.0).rgb * (w12.x * w3.y);
total += w12.x * w3.y;
return max(sum / total, vec3<f32>(0.0));
}
// Pulls `p` towards the box's centre until it is inside.
fn clip_to_box(lo: vec3<f32>, hi: vec3<f32>, p: vec3<f32>) -> vec3<f32> {
let centre = (lo + hi) * 0.5;
let ext = max((hi - lo) * 0.5, vec3<f32>(0.00001));
let off = (p - centre) / ext;
let m = max(abs(off.x), max(abs(off.y), abs(off.z)));
return select(p, centre + (p - centre) / m, m > 1.0);
}
// Temporal anti-aliasing: the history, reprojected by depth and the camera's move, clamped to
// the colours round this pixel (so what moved or was uncovered can't ghost), blended in.
@fragment
fn fs_taa(in: FullOut) -> TaaOut {
let size = vec2<i32>(textureDimensions(source));
let px = vec2<i32>(in.position.xy);
let d = textureLoad(depth_tex, px, 0);
var sum = vec3<f32>(0.0);
var sum2 = vec3<f32>(0.0);
var lo = vec3<f32>(1.0e9);
var hi = vec3<f32>(-1.0e9);
var centre = vec3<f32>(0.0);
for (var y = -1; y <= 1; y++) {
for (var x = -1; x <= 1; x++) {
let q = clamp(px + vec2<i32>(x, y), vec2<i32>(0), size - 1);
let s = to_ycocg(squash(textureLoad(source, q, 0).rgb));
sum += s;
sum2 += s * s;
lo = min(lo, s);
hi = max(hi, s);
if x == 0 && y == 0 { centre = s; }
}
}
let sky = d <= 0.0;
let ndc = vec4<f32>(in.uv.x * 2.0 - 1.0, 1.0 - in.uv.y * 2.0, max(d, 0.000001), 1.0);
let h = frame.inverse_view_proj * ndc;
let p = h.xyz / h.w;
let dist = select(length(p), 0.0, sky);
var resolved = centre;
if frame.taa.w > 0.5 {
let prev = frame.prev_view_proj * vec4<f32>(select(p + frame.taa.xyz, p, sky), 1.0);
if prev.w > 0.0 {
let pn = prev.xy / prev.w;
let uv = vec2<f32>(pn.x * 0.5 + 0.5, 0.5 - pn.y * 0.5);
if all(uv > vec2<f32>(0.0)) && all(uv < vec2<f32>(1.0)) {
let hp = clamp(vec2<i32>(uv * vec2<f32>(size)), vec2<i32>(0), size - 1);
let seen = textureLoad(history, hp, 0).a;
let expected = select(length(p + frame.taa.xyz), 0.0, sky);
// The same surface as last frame (not uncovered), by its distance.
if abs(seen - expected) <= expected * 0.03 + 0.25 {
let mean = sum / 9.0;
let sigma = sqrt(max(sum2 / 9.0 - mean * mean, vec3<f32>(0.0)));
let box_lo = min(max(mean - sigma * 1.5, lo), centre);
let box_hi = max(min(mean + sigma * 1.5, hi), centre);
let past = clip_to_box(box_lo, box_hi, to_ycocg(squash(history_color(uv))));
// Fast motion trusts the history less.
let moved = length((uv - in.uv) * vec2<f32>(size));
let keep = mix(frame.taa_params.x, frame.taa_params.x * 0.75, clamp(moved / 4.0, 0.0, 1.0));
resolved = mix(centre, past, keep);
}
}
}
}
let color = unsquash(from_ycocg(resolved));
var out: TaaOut;
out.color = vec4<f32>(color, 1.0);
out.history = vec4<f32>(color, dist);
return out;
}
// The jittered samples' reconstruction filter (a polynomial fit of Lanczos-2, radius 2 in
// world-target pixels): 1 at 0, 0 at 1 and 2, a little negative between.
fn lanczos2(x: f32) -> f32 {
let x2 = min(x * x, 4.0);
let a = 0.4 * x2 - 1.0;
let b = 0.25 * x2 - 1.0;
return (1.5625 * a * a - 0.5625) * b * b;
}
// Temporal upscaling: the world (and its depth) is smaller than the output. Each output pixel
// gathers the 3x3 world samples round it, each weighed by its distance from the pixel's centre
// (the samples lie off the pixel centres by the frame's jitter), clamps the reprojected full-size
// history to their colour box and blends: more history where the nearest sample is far away.
@fragment
fn fs_taau(in: FullOut) -> TaaOut {
let low = vec2<f32>(textureDimensions(source));
let lowi = vec2<i32>(low);
let high = vec2<f32>(textureDimensions(history));
let jit = frame.taa_params.zw;
// The output pixel's place among the world's samples: sample i lies at index i - jit, and
// the nearest to this pixel is `base`.
let t = in.uv * low - 0.5 + jit;
let base = vec2<i32>(floor(t + 0.5));
var sum = vec3<f32>(0.0);
var sum2 = vec3<f32>(0.0);
var lo = vec3<f32>(1.0e9);
var hi = vec3<f32>(-1.0e9);
var weighted = vec3<f32>(0.0);
var total = 0.0;
for (var y = -1; y <= 1; y++) {
for (var x = -1; x <= 1; x++) {
let q = clamp(base + vec2<i32>(x, y), vec2<i32>(0), lowi - 1);
let s = to_ycocg(squash(textureLoad(source, q, 0).rgb));
sum += s;
sum2 += s * s;
lo = min(lo, s);
hi = max(hi, s);
let off = vec2<f32>(base + vec2<i32>(x, y)) - t;
let w = lanczos2(off.x) * lanczos2(off.y);
weighted += s * w;
total += w;
}
}
let current = weighted / max(total, 0.001);
// Depth: the nearest of the 2x2 samples round the pixel (steady between frames at an edge).
let corner = vec2<i32>(floor(in.uv * low - 0.5 + jit));
var d = 0.0;
for (var y = 0; y <= 1; y++) {
for (var x = 0; x <= 1; x++) {
d = max(d, textureLoad(depth_tex, clamp(corner + vec2<i32>(x, y), vec2<i32>(0), lowi - 1), 0));
}
}
let sky = d <= 0.0;
// The world was drawn shifted by the jitter in clip space; this pixel's unshifted point.
let jc = vec2<f32>(jit.x * 2.0 / low.x, -jit.y * 2.0 / low.y);
let ndc = vec4<f32>(in.uv.x * 2.0 - 1.0 + jc.x, 1.0 - in.uv.y * 2.0 + jc.y, max(d, 0.000001), 1.0);
let h = frame.inverse_view_proj * ndc;
let p = h.xyz / h.w;
let dist = select(length(p), 0.0, sky);
var resolved = current;
if frame.taa.w > 0.5 {
let prev = frame.prev_view_proj * vec4<f32>(select(p + frame.taa.xyz, p, sky), 1.0);
if prev.w > 0.0 {
let pn = prev.xy / prev.w;
let uv = vec2<f32>(pn.x * 0.5 + 0.5, 0.5 - pn.y * 0.5);
if all(uv > vec2<f32>(0.0)) && all(uv < vec2<f32>(1.0)) {
let hp = clamp(vec2<i32>(uv * high), vec2<i32>(0), vec2<i32>(high) - 1);
let seen = textureLoad(history, hp, 0).a;
let expected = select(length(p + frame.taa.xyz), 0.0, sky);
if abs(seen - expected) <= expected * 0.03 + 0.25 {
let mean = sum / 9.0;
let sigma = sqrt(max(sum2 / 9.0 - mean * mean, vec3<f32>(0.0)));
let box_lo = min(max(mean - sigma * 1.25, lo), current);
let box_hi = max(min(mean + sigma * 1.25, hi), current);
let past = clip_to_box(box_lo, box_hi, to_ycocg(squash(history_color(uv))));
// How far the nearest sample is from the pixel's centre (0 on it, 1 at the
// corner of the world's pixel): the farther, the less the frame says.
let near = clamp(length(t - floor(t + 0.5)) / 0.7071, 0.0, 1.0);
let fresh = (1.0 - frame.taa_params.x) * mix(1.8, 0.5, near);
let moved = length((uv - in.uv) * high);
let keep = (1.0 - fresh) * mix(1.0, 0.8, clamp(moved / 4.0, 0.0, 1.0));
resolved = mix(current, past, clamp(keep, 0.0, 0.98));
}
}
}
}
let color = unsquash(from_ycocg(resolved));
var out: TaaOut;
out.color = vec4<f32>(color, 1.0);
out.history = vec4<f32>(color, dist);
return out;
}
"#;
struct Target {
view: wgpu::TextureView,
}
fn target(
device: &wgpu::Device,
label: &str,
size: [u32; 2],
format: wgpu::TextureFormat,
) -> Target {
let view = device
.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: size[0].max(1),
height: size[1].max(1),
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&Default::default());
Target { view }
}
/// The outside views and sampler the lighting group reads.
type LightKey = (
wgpu::TextureView,
wgpu::TextureView,
wgpu::TextureView,
wgpu::Sampler,
);
/// What bloom and the tone curve read: the lit world, or the post pass's output.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum HdSource {
Lit,
Fx,
/// The anti-aliased result of `taa`.
Taa,
}
/// TAA is on unless `HORIZON_HD_TAA=0`.
pub fn taa_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("HORIZON_HD_TAA").map_or(true, |v| v != "0"))
}
/// The water effect is on unless `HORIZON_HD_WATER=0`.
pub fn water_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("HORIZON_HD_WATER").map_or(true, |v| v != "0"))
}
/// The Halton sequence's `index`-th number in `base`, in (0, 1).
fn halton(mut index: u32, base: u32) -> f32 {
let (mut f, mut r) = (1.0, 0.0);
while index > 0 {
f /= base as f32;
r += f * (index % base) as f32;
index /= base;
}
r
}
/// The history's weight when upscaling (the frames each pixel gathers are sparse, so more of them
/// are kept than without; `fs_taau` lowers it where the frame's sample is near).
const UPSCALE_HISTORY: f32 = 0.92;
/// The world's size relative to the output (`HORIZON_HD_SCALE`, per axis, 0.25..=1) while HD is on, if
/// set: it replaces the resolution scale of Horizon's settings for HD. 1 renders at full size.
pub fn scale_override() -> Option<f32> {
static SCALE: std::sync::OnceLock<Option<f32>> = std::sync::OnceLock::new();
*SCALE.get_or_init(|| {
let v: f32 = std::env::var("HORIZON_HD_SCALE").ok()?.parse().ok()?;
v.is_finite().then(|| v.clamp(0.25, 1.0))
})
}
/// How many jitter positions the sequence cycles through for an output `ratio` times the world's
/// size per axis: 16 without upscaling, else 8 per output pixel's share of a world pixel
/// (ratio squared), so every output pixel gets samples all over the world pixel it lies in.
pub fn jitter_count(ratio: f32) -> u32 {
if ratio <= 1.001 {
16
} else {
((8.0 * ratio * ratio).ceil() as u32).clamp(16, 64)
}
}
/// Frame `frame`'s sub-pixel offset of the projection in clip space (a fraction of the
/// screen's size in x and y), from the Halton(2, 3) sequence over `count` frames.
pub fn jitter(frame: u32, size: [u32; 2], count: u32) -> [f32; 2] {
let i = frame % count.max(1) + 1;
[
(halton(i, 2) - 0.5) * 2.0 / size[0].max(1) as f32,
(halton(i, 3) - 0.5) * 2.0 / size[1].max(1) as f32,
]
}
pub struct Hd {
/// The world's size (the G-buffer, lighting, AO, post pass), and the output's (TAA, bloom,
/// tone curve): bigger when the world is upscaled.
size: [u32; 2],
out: [u32; 2],
pub albedo: wgpu::TextureView,
pub normal: wgpu::TextureView,
pub levels: wgpu::TextureView,
/// The shadow cascades: the array to sample, one view per layer to draw.
shadow_array: wgpu::TextureView,
shadow_layers: Vec<wgpu::TextureView>,
shadow_sampler: wgpu::Sampler,
/// The globals the shadow passes draw with (the light's view), and the camera's to put back.
pub shadow_globals: [wgpu::Buffer; 2],
pub main_globals: wgpu::Buffer,
frames: u32,
pub depth: wgpu::TextureView,
/// The lit world, and the post pass's output.
pub lit: wgpu::TextureView,
pub fx: wgpu::TextureView,
/// Water: its surface colour and normal, its depth (the nearest water surface; 0 elsewhere),
/// the lit world with the water over it, and what draws and composites them.
water_tint: wgpu::TextureView,
water_normal: wgpu::TextureView,
water_depth: wgpu::TextureView,
lit_water: wgpu::TextureView,
water_layout: wgpu::BindGroupLayout,
water_pipeline: wgpu::RenderPipeline,
water_group: Option<((wgpu::TextureView, wgpu::Sampler), wgpu::BindGroup)>,
/// The water effect runs this frame (the scene allows it and there is translucent terrain on
/// screen), and `lit_view` is the composite.
water_active: bool,
/// The frame's translucent terrain exists (set by the renderer before `write`).
pub water_geometry: bool,
water_composited: bool,
started: std::time::Instant,
/// TAA: the resolved frame, and the two histories (one read, one written, alternating).
taa: wgpu::TextureView,
history: [wgpu::TextureView; 2],
history_ready: bool,
history_flip: usize,
taa_active: bool,
taa_layout: wgpu::BindGroupLayout,
taa_pipeline: wgpu::RenderPipeline,
taau_pipeline: wgpu::RenderPipeline,
taa_groups: Option<((wgpu::TextureView, wgpu::TextureView), [wgpu::BindGroup; 2])>,
bloom: Vec<Target>,
/// Bind groups, rebuilt only when their views change: `resize` drops all of them, the
/// lighting and the source-reading ones are keyed by the views they read.
light_group: Option<(LightKey, wgpu::BindGroup)>,
prefilter_group: Option<(wgpu::TextureView, wgpu::BindGroup)>,
tone_group: Option<(wgpu::TextureView, wgpu::BindGroup)>,
/// Reading bloom level k - 1 (for the down pass into level k, index k - 1) and level k (for
/// the up pass onto level k - 1, index k - 1).
down_groups: Vec<wgpu::BindGroup>,
up_groups: Vec<wgpu::BindGroup>,
frame: wgpu::Buffer,
lights: wgpu::Buffer,
/// The tiles' light lists (see `tile_lists`), sized for the screen, and the tiles per row.
tiles: wgpu::Buffer,
tiles_x: u32,
tile_scratch: Vec<Vec<u16>>,
tile_words: Vec<u32>,
sampler: wgpu::Sampler,
light_layout: wgpu::BindGroupLayout,
light_pipeline: wgpu::RenderPipeline,
bloom_layout: wgpu::BindGroupLayout,
prefilter: wgpu::RenderPipeline,
down: wgpu::RenderPipeline,
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`.
fn tiles_buffer(device: &wgpu::Device, size: [u32; 2]) -> wgpu::Buffer {
let tiles = (size[0].div_ceil(TILE).max(1) * size[1].div_ceil(TILE).max(1)) as usize;
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("HD light tiles"),
size: ((tiles * 4 + TILE_INDICES) * std::mem::size_of::<u32>()) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
}
/// Where a camera-relative sphere can show on the screen.
enum Cover {
/// Nowhere: it is wholly behind the camera.
Nothing,
/// Anywhere: it crosses the camera's plane, or holds the camera.
Everywhere,
/// Inside this pixel rectangle (min x, min y, max x, max y).
Rect([f32; 4]),
}
/// The screen cover of the sphere at `c` of radius `r`: the projection of the 8 corners of the
/// box round it. A box is convex and so is its projection while every corner is in front of the
/// camera, so the rectangle holds the whole sphere. With some corners behind, the projection
/// is not bounded and the cover is the whole screen; with all of them behind, no pixel ray
/// (they all point forward) can meet the sphere.
fn cover(view_proj: &Mat4, c: glam::Vec3, r: f32, size: [u32; 2]) -> Cover {
if !c.is_finite() || !r.is_finite() {
return Cover::Everywhere;
}
// A little more than the shader's radius, against rounding.
let r = r * 1.01 + 0.01;
let (mut lo, mut hi) = (glam::Vec2::splat(f32::MAX), glam::Vec2::splat(f32::MIN));
let mut front = 0;
for corner in 0..8 {
let o = glam::Vec3::new(
if corner & 1 == 0 { -r } else { r },
if corner & 2 == 0 { -r } else { r },
if corner & 4 == 0 { -r } else { r },
);
let h = *view_proj * (c + o).extend(1.0);
if h.w > 0.0 {
front += 1;
let ndc = glam::Vec2::new(h.x, h.y) / h.w;
let px = glam::Vec2::new(
(ndc.x * 0.5 + 0.5) * size[0] as f32,
(0.5 - ndc.y * 0.5) * size[1] as f32,
);
lo = lo.min(px);
hi = hi.max(px);
}
}
match front {
0 => Cover::Nothing,
8 => Cover::Rect([lo.x - 2.0, lo.y - 2.0, hi.x + 2.0, hi.y + 2.0]),
_ => Cover::Everywhere,
}
}
/// Fills `words` with each 16x16 tile's two lists of the lights that can reach it: header
/// (surface start, surface length, halo start, halo length) per tile, then the indices; a
/// length of `EVERY_LIGHT` stands for all of `lights` (a list past the buffer's room). The
/// surface list holds the lights whose sphere can touch what the tile sees. The halo list
/// holds the lights whose halo can reach a ray of the tile: the shader adds a halo for the
/// view *line* passing within half the radius of the light, so a ray pointing away from a light
/// behind it is lit too, and the mirrored sphere is covered as well. Lights stay in order, so
/// the sums are the ones of the full loop.
fn tile_lists(
view_proj: &Mat4,
lights: &[HdLight],
size: [u32; 2],
scratch: &mut Vec<Vec<u16>>,
words: &mut Vec<u32>,
) {
let tx = size[0].div_ceil(TILE).max(1) as usize;
let ty = size[1].div_ceil(TILE).max(1) as usize;
let tiles = tx * ty;
scratch.resize_with(tiles * 2, Vec::new);
scratch.truncate(tiles * 2);
scratch.iter_mut().for_each(Vec::clear);
let mut add = |list: usize, area: Cover, light: u16| match area {
Cover::Nothing => {}
Cover::Everywhere => {
for t in 0..tiles {
scratch[t * 2 + list].push(light);
}
}
Cover::Rect([x0, y0, x1, y1]) => {
let tile = TILE as f32;
if x1 < 0.0 || y1 < 0.0 || x0 >= size[0] as f32 || y0 >= size[1] as f32 {
return;
}
let from = |v: f32, n: usize| ((v / tile).floor().max(0.0) as usize).min(n - 1);
for y in from(y0, ty)..=from(y1, ty) {
for x in from(x0, tx)..=from(x1, tx) {
scratch[(y * tx + x) * 2 + list].push(light);
}
}
}
};
for (i, l) in lights.iter().enumerate() {
let c = glam::Vec3::new(l.pos[0], l.pos[1], l.pos[2]);
add(0, cover(view_proj, c, l.pos[3], size), i as u16);
// The shader's halo reach: the line within `radius / 2 - 0.5` of the light.
let reach = l.pos[3] * 0.5 - 0.5;
if reach > 0.0 || !reach.is_finite() {
add(1, cover(view_proj, c, reach, size), i as u16);
add(1, cover(view_proj, -c, reach, size), i as u16);
}
}
words.clear();
words.resize(tiles * 4, 0);
let mut room = TILE_INDICES;
for t in 0..tiles {
for list in 0..2 {
let ids = &mut scratch[t * 2 + list];
// Both the sphere and its mirror can name a light: once is enough.
ids.dedup();
let at = t * 4 + list * 2;
if ids.len() > room {
words[at + 1] = EVERY_LIGHT;
} else {
room -= ids.len();
words[at] = words.len() as u32;
words[at + 1] = ids.len() as u32;
words.extend(ids.iter().map(|&i| u32::from(i)));
}
}
}
}
/// 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),
source: wgpu::ShaderSource::Wgsl(format!("{COMMON}{body}").into()),
})
}
fn fullscreen(
device: &wgpu::Device,
label: &str,
layout: &wgpu::BindGroupLayout,
module: &wgpu::ShaderModule,
entry: &str,
format: wgpu::TextureFormat,
blend: Option<wgpu::BlendState>,
) -> wgpu::RenderPipeline {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some(label),
bind_group_layouts: &[Some(layout)],
..Default::default()
});
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module,
entry_point: Some("vs_full"),
compilation_options: Default::default(),
buffers: &[],
},
fragment: Some(wgpu::FragmentState {
module,
entry_point: Some(entry),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend,
write_mask: wgpu::ColorWrites::ALL,
})],
}),
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
multiview_mask: None,
cache: None,
})
}
fn entries(kinds: &[wgpu::BindingType]) -> Vec<wgpu::BindGroupLayoutEntry> {
kinds
.iter()
.enumerate()
.map(|(i, ty)| wgpu::BindGroupLayoutEntry {
binding: i as u32,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: *ty,
count: None,
})
.collect()
}
const UNIFORM: wgpu::BindingType = wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
};
const FLOAT: wgpu::BindingType = wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
};
const UNFILTERED: wgpu::BindingType = wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
};
const DEPTH: wgpu::BindingType = wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
};
const SAMPLER: wgpu::BindingType = wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering);
impl Hd {
pub fn new(
device: &wgpu::Device,
size: [u32; 2],
screen: wgpu::TextureFormat,
globals_size: u64,
) -> Self {
let light_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("HD lighting"),
entries: &entries(&[
UNIFORM,
UNFILTERED,
DEPTH,
UNFILTERED,
UNFILTERED,
DEPTH,
wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
UNFILTERED,
wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2Array,
multisampled: false,
},
wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
FLOAT,
SAMPLER,
wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
UNFILTERED,
DEPTH,
]),
});
let water_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("HD water"),
entries: &entries(&[
UNIFORM,
FLOAT,
DEPTH,
UNFILTERED,
UNFILTERED,
DEPTH,
wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2Array,
multisampled: false,
},
wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
FLOAT,
SAMPLER,
]),
});
let taa_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("HD TAA"),
entries: &entries(&[UNIFORM, UNFILTERED, DEPTH, FLOAT, SAMPLER]),
});
let taa_module = module(device, "HD TAA", TAA);
let taa_pipeline = |entry: &str| {
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("HD TAA"),
bind_group_layouts: &[Some(&taa_layout)],
..Default::default()
});
let target = Some(wgpu::ColorTargetState {
format: HDR,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
});
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("HD TAA"),
layout: Some(&layout),
vertex: wgpu::VertexState {
module: &taa_module,
entry_point: Some("vs_full"),
compilation_options: Default::default(),
buffers: &[],
},
fragment: Some(wgpu::FragmentState {
module: &taa_module,
entry_point: Some(entry),
compilation_options: Default::default(),
targets: &[target.clone(), target],
}),
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
multiview_mask: None,
cache: None,
})
};
let (taa_pipeline, taau_pipeline) = (taa_pipeline("fs_taa"), taa_pipeline("fs_taau"));
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]),
});
let tone_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("HD tone mapping"),
entries: &entries(&[UNIFORM, FLOAT, FLOAT, SAMPLER]),
});
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 water = module(device, "HD water", WATER);
let water_pipeline = fullscreen(
device,
"HD water",
&water_layout,
&water,
"fs_water",
HDR,
None,
);
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,
dst_factor: wgpu::BlendFactor::One,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::REPLACE,
};
let light_pipeline = fullscreen(
device,
"HD lighting",
&light_layout,
&light,
"fs_light",
HDR,
None,
);
let prefilter = fullscreen(
device,
"HD bloom prefilter",
&bloom_layout,
&bloom,
"fs_prefilter",
HDR,
None,
);
let down = fullscreen(
device,
"HD bloom down",
&bloom_layout,
&bloom,
"fs_down",
HDR,
None,
);
let up = fullscreen(
device,
"HD bloom up",
&bloom_layout,
&bloom,
"fs_up",
HDR,
Some(add),
);
let tone = fullscreen(
device,
"HD tone mapping",
&tone_layout,
&tone,
"fs_tonemap",
screen,
None,
);
let frame = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("HD frame"),
size: std::mem::size_of::<HdFrame>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let lights = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("HD lights"),
size: (MAX_LIGHTS * std::mem::size_of::<HdLight>()) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("HD"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
..Default::default()
});
let shadow_texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("HD shadow cascades"),
size: wgpu::Extent3d {
width: SHADOW_SIZE,
height: SHADOW_SIZE,
depth_or_array_layers: 2,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Depth32Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let shadow_array = shadow_texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
let shadow_layers = (0..2)
.map(|l| {
shadow_texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2),
base_array_layer: l,
array_layer_count: Some(1),
..Default::default()
})
})
.collect();
let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("HD shadows"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
compare: Some(wgpu::CompareFunction::LessEqual),
..Default::default()
});
let globals = |label| {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
size: globals_size,
usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
};
let mut hd = Hd {
size: [0, 0],
out: [0, 0],
albedo: target(device, "HD albedo", [1, 1], ALBEDO).view,
normal: target(device, "HD normal", [1, 1], NORMAL).view,
levels: target(device, "HD light levels", [1, 1], LIGHT_LEVELS).view,
shadow_array,
shadow_layers,
shadow_sampler,
shadow_globals: [
globals("HD shadow globals 0"),
globals("HD shadow globals 1"),
],
main_globals: globals("HD camera globals"),
frames: 0,
depth: target(
device,
"HD depth",
[1, 1],
wgpu::TextureFormat::Depth32Float,
)
.view,
lit: target(device, "HD lit", [1, 1], HDR).view,
fx: target(device, "HD post", [1, 1], HDR).view,
water_tint: target(device, "HD water colour", [1, 1], WATER_TINT).view,
water_normal: target(device, "HD water normal", [1, 1], WATER_NORMAL).view,
water_depth: target(
device,
"HD water depth",
[1, 1],
wgpu::TextureFormat::Depth32Float,
)
.view,
lit_water: target(device, "HD lit with water", [1, 1], HDR).view,
water_layout,
water_pipeline,
water_group: None,
water_active: false,
water_geometry: false,
water_composited: false,
started: std::time::Instant::now(),
taa: target(device, "HD TAA", [1, 1], HDR).view,
history: [
target(device, "HD TAA history", [1, 1], HDR).view,
target(device, "HD TAA history", [1, 1], HDR).view,
],
history_ready: false,
history_flip: 0,
taa_active: false,
taa_layout,
taa_pipeline,
taau_pipeline,
taa_groups: None,
bloom: Vec::new(),
light_group: None,
prefilter_group: None,
tone_group: None,
down_groups: Vec::new(),
up_groups: Vec::new(),
frame,
lights,
tiles: tiles_buffer(device, [1, 1]),
tiles_x: 1,
tile_scratch: Vec::new(),
tile_words: Vec::new(),
sampler,
light_layout,
light_pipeline,
bloom_layout,
prefilter,
down,
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, size);
hd
}
/// The targets: the world's at `size` (the world target's), the output's (TAA history, bloom)
/// at `out`, which is bigger when the world is upscaled.
pub fn resize(&mut self, device: &wgpu::Device, size: [u32; 2], out: [u32; 2]) {
let out = [out[0].max(size[0]), out[1].max(size[1])];
if self.size == size && self.out == out {
return;
}
self.size = size;
self.out = out;
self.albedo = target(device, "HD albedo", size, ALBEDO).view;
self.normal = target(device, "HD normal", size, NORMAL).view;
self.levels = target(device, "HD light levels", size, LIGHT_LEVELS).view;
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;
self.water_tint = target(device, "HD water colour", size, WATER_TINT).view;
self.water_normal = target(device, "HD water normal", size, WATER_NORMAL).view;
self.water_depth = target(
device,
"HD water depth",
size,
wgpu::TextureFormat::Depth32Float,
)
.view;
self.lit_water = target(device, "HD lit with water", size, HDR).view;
self.water_group = None;
self.taa = target(device, "HD TAA", out, HDR).view;
self.history = [
target(device, "HD TAA history", out, HDR).view,
target(device, "HD TAA history", out, HDR).view,
];
self.history_ready = false;
self.taa_groups = None;
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)
.map(|k| {
let s = [(out[0] >> (k + 1)).max(1), (out[1] >> (k + 1)).max(1)];
target(device, "HD bloom", s, HDR)
})
.collect();
// Every group names a view that was just replaced.
self.light_group = None;
self.prefilter_group = None;
self.tone_group = None;
self.down_groups = (1..self.bloom.len())
.map(|k| self.bloom_group(device, &self.bloom[k - 1].view))
.collect();
self.up_groups = (1..self.bloom.len())
.map(|k| self.bloom_group(device, &self.bloom[k].view))
.collect();
}
/// The world is smaller than the output, so TAA upsamples it.
fn upscaling(&self) -> bool {
self.out != self.size
}
/// This frame's camera, sun, fog, lights and settings.
pub fn write(
&mut self,
queue: &wgpu::Queue,
scene: &HdScene,
lights: &[HdLight],
settings: HdSettings,
) {
let n = lights.len().min(MAX_LIGHTS);
if n > 0 {
queue.write_buffer(&self.lights, 0, bytemuck::cast_slice(&lights[..n]));
}
// Written every frame, empty too: the shader reads the counts, not `params.x`.
tile_lists(
&scene.view_proj,
&lights[..n],
self.size,
&mut self.tile_scratch,
&mut self.tile_words,
);
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 = scene.cascades;
let night = scene.dark.clamp(0.0, 1.0);
self.water_active = scene.water && water_enabled() && self.water_geometry;
self.taa_active = scene.taa && taa_enabled();
// A long jump of the camera (a teleport) starts the history over.
if !self.taa_active || scene.camera_delta.length() > 64.0 {
self.history_ready = false;
}
let frame = HdFrame {
prev_view_proj: scene.prev_view_proj.to_cols_array_2d(),
taa: [
scene.camera_delta.x,
scene.camera_delta.y,
scene.camera_delta.z,
if self.history_ready { 1.0 } else { 0.0 },
],
view_proj: scene.view_proj.to_cols_array_2d(),
water: [
if self.water_active { 1.0 } else { 0.0 },
(self.started.elapsed().as_secs_f64() % 600.0) as f32,
scene.camera_mod[0],
scene.camera_mod[1],
],
sky_color: [
scene.sky_color[0],
scene.sky_color[1],
scene.sky_color[2],
if scene.sky { 1.0 } else { 0.0 },
],
taa_params: [
if self.upscaling() {
UPSCALE_HISTORY
} else {
// A still picture keeps 94% of the past: the jitter's shimmer on pixel-art
// textures averages out instead of flickering.
0.94
},
if self.taa_active { 0.12 } else { 0.0 },
scene.jitter_px[0],
scene.jitter_px[1],
],
inverse_view_proj: scene.view_proj.inverse().to_cols_array_2d(),
resolution: [
self.size[0] as f32,
self.size[1] as f32,
1.0 / self.size[0] as f32,
1.0 / self.size[1] as f32,
],
params: [
n as f32,
settings.exposure,
settings.bloom,
(self.frames % 64) as f32,
],
cascades: cascades.map(|m| m.to_cols_array_2d()),
sun: [dir.x, dir.y, dir.z, strength],
sun_color: [color.x, color.y, color.z, night],
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,
self.ao_strength.max(0.0),
],
shadow: [
if strength > 0.0 { 1.0 } else { 0.0 },
CASCADES[0],
CASCADES[1],
self.tiles_x as f32,
],
};
queue.write_buffer(&self.frame, 0, bytemuck::bytes_of(&frame));
}
/// The shadow pass of cascade `c`: its depth layer cleared, nothing else.
pub fn shadow_pass<'e>(
&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],
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
..Default::default()
})
.forget_lifetime()
}
/// The G-buffer pass's attachments: albedo and normal cleared, its own depth.
pub fn gbuffer_pass<'e>(
&mut self,
encoder: &'e mut wgpu::CommandEncoder,
) -> wgpu::RenderPass<'e> {
let clear = |view| {
Some(wgpu::RenderPassColorAttachment {
view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})
};
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),
clear(&self.levels),
],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(0.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
..Default::default()
})
.forget_lifetime()
}
fn draw(
encoder: &mut wgpu::CommandEncoder,
label: &str,
to: &wgpu::TextureView,
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,
depth_slice: None,
ops: wgpu::Operations {
load: if load {
wgpu::LoadOp::Load
} else {
wgpu::LoadOp::Clear(wgpu::Color::BLACK)
},
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
pass.set_pipeline(pipeline);
pass.set_bind_group(0, group, &[]);
pass.draw(0..3, 0..1);
}
/// Lights the world (its colour and depth) into `lit`.
pub fn light(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
world: (&wgpu::TextureView, &wgpu::TextureView),
lightmap: (&wgpu::TextureView, &wgpu::Sampler),
) {
let key = (
world.0.clone(),
world.1.clone(),
lightmap.0.clone(),
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,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: self.frame.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(world.0),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(world.1),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&self.albedo),
},
wgpu::BindGroupEntry {
binding: 4,
resource: wgpu::BindingResource::TextureView(&self.normal),
},
wgpu::BindGroupEntry {
binding: 5,
resource: wgpu::BindingResource::TextureView(&self.depth),
},
wgpu::BindGroupEntry {
binding: 6,
resource: self.lights.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::TextureView(&self.levels),
},
wgpu::BindGroupEntry {
binding: 8,
resource: wgpu::BindingResource::TextureView(&self.shadow_array),
},
wgpu::BindGroupEntry {
binding: 9,
resource: wgpu::BindingResource::Sampler(&self.shadow_sampler),
},
wgpu::BindGroupEntry {
binding: 10,
resource: wgpu::BindingResource::TextureView(lightmap.0),
},
wgpu::BindGroupEntry {
binding: 11,
resource: wgpu::BindingResource::Sampler(lightmap.1),
},
wgpu::BindGroupEntry {
binding: 12,
resource: self.tiles.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 13,
resource: wgpu::BindingResource::TextureView(&self.ao_blurred),
},
wgpu::BindGroupEntry {
binding: 14,
resource: wgpu::BindingResource::TextureView(&self.water_depth),
},
],
});
self.light_group = Some((key, group));
}
let Some((_, group)) = &self.light_group else {
return;
};
self.water_composited = false;
Self::draw(
encoder,
"HD lighting",
&self.lit,
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,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: self.frame.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(source),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::Sampler(&self.sampler),
},
],
})
}
/// Bloom from `source` (the lit world or the post pass's output), then the tone curve onto `screen`.
pub fn finish(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
source: HdSource,
screen: &wgpu::TextureView,
) {
let source = match source {
HdSource::Lit => self.lit_view().clone(),
HdSource::Fx => self.fx.clone(),
HdSource::Taa => self.taa.clone(),
};
if self
.prefilter_group
.as_ref()
.is_none_or(|(v, _)| *v != source)
{
let group = self.bloom_group(device, &source);
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,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: self.frame.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&source),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(&self.bloom[0].view),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::Sampler(&self.sampler),
},
],
});
self.tone_group = Some((source, group));
}
let (Some((_, prefilter)), Some((_, tone))) = (&self.prefilter_group, &self.tone_group)
else {
return;
};
// Down: the prefilter into the first level, then each level from the one above.
Self::draw(
encoder,
"HD bloom prefilter",
&self.bloom[0].view,
false,
&self.prefilter,
prefilter,
stamp(&mut self.timing, BLOOM_NAMES[0]),
);
for k in 1..self.bloom.len() {
Self::draw(
encoder,
"HD bloom down",
&self.bloom[k].view,
false,
&self.down,
&self.down_groups[k - 1],
stamp(&mut self.timing, BLOOM_NAMES[k]),
);
}
// Up: each level added onto the bigger one.
for k in (1..self.bloom.len()).rev() {
Self::draw(
encoder,
"HD bloom up",
&self.bloom[k - 1].view,
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,
stamp(&mut self.timing, "hd tonemap"),
);
}
/// Temporal anti-aliasing of `source` (with the world's `depth`): the source it left, to hand
/// to `finish` — the same one when TAA is off this frame.
pub fn taa(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
source: HdSource,
depth: &wgpu::TextureView,
) -> HdSource {
if !self.taa_active {
return source;
}
let input = match source {
HdSource::Lit => self.lit_view().clone(),
HdSource::Fx => self.fx.clone(),
HdSource::Taa => return source,
};
let key = (input, depth.clone());
if self.taa_groups.as_ref().is_none_or(|(k, _)| *k != key) {
let groups = [0, 1].map(|read| {
self.make_group(
device,
"HD TAA",
&self.taa_layout,
&[
wgpu::BindingResource::Buffer(self.frame.as_entire_buffer_binding()),
wgpu::BindingResource::TextureView(&key.0),
wgpu::BindingResource::TextureView(depth),
wgpu::BindingResource::TextureView(&self.history[read]),
wgpu::BindingResource::Sampler(&self.sampler),
],
)
});
self.taa_groups = Some((key, groups));
}
let Some((_, groups)) = &self.taa_groups else {
return source;
};
let (read, write) = (self.history_flip, 1 - self.history_flip);
let upscaling = self.upscaling();
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("HD TAA"),
timestamp_writes: stamp(
&mut self.timing,
if upscaling { "hd taau" } else { "hd taa" },
),
color_attachments: &[&self.taa, &self.history[write]].map(|view| {
Some(wgpu::RenderPassColorAttachment {
view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})
}),
..Default::default()
});
pass.set_pipeline(if upscaling {
&self.taau_pipeline
} else {
&self.taa_pipeline
});
pass.set_bind_group(0, &groups[read], &[]);
pass.draw(0..3, 0..1);
drop(pass);
self.history_flip = write;
self.history_ready = true;
HdSource::Taa
}
/// The lit world as later passes see it: with the water over it when the effect ran.
pub fn lit_view(&self) -> &wgpu::TextureView {
if self.water_composited {
&self.lit_water
} else {
&self.lit
}
}
/// The water effect runs this frame (the renderer draws the water quads with `water_pass`).
pub fn water_active(&self) -> bool {
self.water_active
}
/// The water pass's attachments: the surface colour and normal, and the water's own depth,
/// all cleared. The caller draws the translucent terrain with `fs_water`.
pub fn water_pass<'e>(
&mut self,
encoder: &'e mut wgpu::CommandEncoder,
) -> wgpu::RenderPass<'e> {
let clear = |view| {
Some(wgpu::RenderPassColorAttachment {
view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
})
};
encoder
.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("HD water"),
timestamp_writes: stamp(&mut self.timing, "hd water"),
color_attachments: &[clear(&self.water_tint), clear(&self.water_normal)],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.water_depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(0.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
..Default::default()
})
.forget_lifetime()
}
/// Lays the water over the lit world (refraction, reflection, glint) into a target of its
/// own; `lit_view` is that target after this.
pub fn water_composite(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
lightmap: (&wgpu::TextureView, &wgpu::Sampler),
) {
if !self.water_active {
return;
}
let key = (lightmap.0.clone(), lightmap.1.clone());
if self.water_group.as_ref().is_none_or(|(k, _)| *k != key) {
let group = self.make_group(
device,
"HD water",
&self.water_layout,
&[
wgpu::BindingResource::Buffer(self.frame.as_entire_buffer_binding()),
wgpu::BindingResource::TextureView(&self.lit),
wgpu::BindingResource::TextureView(&self.depth),
wgpu::BindingResource::TextureView(&self.water_tint),
wgpu::BindingResource::TextureView(&self.water_normal),
wgpu::BindingResource::TextureView(&self.water_depth),
wgpu::BindingResource::TextureView(&self.shadow_array),
wgpu::BindingResource::Sampler(&self.shadow_sampler),
wgpu::BindingResource::TextureView(lightmap.0),
wgpu::BindingResource::Sampler(&self.sampler),
],
);
self.water_group = Some((key, group));
}
let Some((_, group)) = &self.water_group else {
return;
};
Self::draw(
encoder,
"HD water composite",
&self.lit_water,
false,
&self.water_pipeline,
group,
stamp(&mut self.timing, "hd water composite"),
);
self.water_composited = true;
}
/// 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
}
}
/// The light that casts the shadows: towards the sun by day, the moon by night; how strong
/// (0 below the horizon or without a sky) and its colour (warm low, white high, cold moon).
pub fn light_of(scene: &HdScene) -> (glam::Vec3, f32, glam::Vec3) {
if !scene.sky {
return (glam::Vec3::Y, 0.0, glam::Vec3::ZERO);
}
let sun = scene.sun.normalize_or(glam::Vec3::Y);
let clear = 1.0 - scene.rain * 0.85;
if sun.y > -0.02 {
let up = smooth(-0.02, 0.18, sun.y);
let warm = smooth(0.0, 0.45, sun.y);
let color = glam::Vec3::new(1.0, 0.62, 0.38).lerp(glam::Vec3::new(1.0, 0.95, 0.86), warm);
(sun, 0.6 * up * clear, color)
} else {
let moon = -sun;
let up = smooth(-0.02, 0.18, moon.y);
(moon, 0.15 * up * clear, glam::Vec3::new(0.55, 0.66, 1.0))
}
}
fn smooth(a: f32, b: f32, x: f32) -> f32 {
let t = ((x - a) / (b - a)).clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
/// The cascades' light view-projections (camera-relative), each square snapped to its texels in
/// the world so the shadows don't crawl as the camera moves.
pub fn cascades(camera: glam::DVec3, light: glam::Vec3) -> [Mat4; 2] {
let l = light.normalize_or(glam::Vec3::Y).as_dvec3();
let forward = -l;
let reference = if l.y.abs() > 0.99 {
glam::DVec3::Z
} else {
glam::DVec3::Y
};
let right = forward.cross(reference).normalize();
let up = right.cross(forward);
CASCADES.map(|r| {
let texel = f64::from(r) * 2.0 / f64::from(SHADOW_SIZE);
let snap = |v: f64| (v / texel).floor() * texel - v;
let centre = right * snap(camera.dot(right)) + up * snap(camera.dot(up));
let eye = centre + l * 400.0;
let view = glam::DMat4::look_at_rh(eye, centre, up);
let r = f64::from(r);
let projection = glam::DMat4::orthographic_rh(-r, r, -r, r, 1.0, 800.0);
(projection * view).as_mat4()
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lighting_shader_parses() {
for (name, body) in [
("light", LIGHT),
("bloom", BLOOM),
("tonemap", TONEMAP),
("taa", TAA),
("ao", AO),
("ao blur", AO_BLUR),
("water", WATER),
] {
let source = format!("{COMMON}{body}");
let module = naga::front::wgsl::parse_str(&source).unwrap_or_else(|e| {
panic!("{name}: {}", e.emit_to_string(&source));
});
naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
)
.validate(&module)
.unwrap_or_else(|e| panic!("{name}: {e:?}"));
}
}
#[test]
fn jitter_stays_within_a_pixel() {
let size = [1920u32, 1080];
let mut seen = std::collections::HashSet::new();
for f in 0..32 {
let j = jitter(f, size, 16);
assert!(j[0].abs() <= 1.0 / size[0] as f32 + 1e-9);
assert!(j[1].abs() <= 1.0 / size[1] as f32 + 1e-9);
seen.insert((j[0].to_bits(), j[1].to_bits()));
}
assert_eq!(seen.len(), 16);
}
#[test]
fn jitter_covers_the_upscale_ratio() {
assert_eq!(jitter_count(1.0), 16);
assert_eq!(jitter_count(1.0 / 0.67), 18);
assert_eq!(jitter_count(2.0), 32);
let size = [1280u32, 720];
let count = jitter_count(2.0);
let seen: std::collections::HashSet<_> = (0..count * 2)
.map(|f| {
let j = jitter(f, size, count);
(j[0].to_bits(), j[1].to_bits())
})
.collect();
assert_eq!(seen.len(), count as usize);
}
#[test]
fn tile_lists_keep_lights_that_reach_a_tile() {
let size = [320, 160];
let proj = Mat4::perspective_rh(1.0, 2.0, 0.05, 1000.0);
let light = |x: f32, y: f32, z: f32, r: f32| HdLight {
pos: [x, y, z, r],
color: [1.0; 4],
};
let lights = [
// Dead ahead and small; far to the side; behind the camera; holding the camera.
light(0.0, 0.0, -20.0, 4.0),
light(30.0, 0.0, -5.0, 4.0),
light(0.0, 0.0, 10.0, 8.0),
light(1.0, 0.0, 0.0, 6.0),
];
let (mut scratch, mut words) = (Vec::new(), Vec::new());
tile_lists(&proj, &lights, size, &mut scratch, &mut words);
let list = |tile: usize, which: usize| -> Vec<u32> {
let (start, len) = (words[tile * 4 + which * 2], words[tile * 4 + which * 2 + 1]);
words[start as usize..(start + len) as usize].to_vec()
};
// The centre tile sees the first light and the one at the camera, in both lists.
let centre = 5 * 20 + 10;
assert_eq!(list(centre, 0), vec![0, 3]);
assert!(list(centre, 1).contains(&0) && list(centre, 1).contains(&3));
// A far corner sees only the one at the camera.
assert_eq!(list(0, 0), vec![3]);
// The light behind the camera shows in the halo list where the view points away.
assert!(list(centre, 1).contains(&2));
assert!(!list(0, 0).contains(&2));
}
}