diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index a8031c1f6..bdc5b867a 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -72,9 +72,6 @@ mod cull; mod end_sky; mod flat; mod hd; -mod hd_noise; -mod hd_sky; -mod hd_volumes; mod hdr; pub mod lightning; mod lod; diff --git a/crates/horizon-client/src/gfx/hd.rs b/crates/horizon-client/src/gfx/hd.rs deleted file mode 100644 index e84a618a9..000000000 --- a/crates/horizon-client/src/gfx/hd.rs +++ /dev/null @@ -1,3414 +0,0 @@ -//! 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::hd_sky; -pub use super::hd_volumes::clouds_enabled; -use super::hd_volumes::{self, HdVolumes}; -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], - /// xyz: towards the sun itself (not the moon); w: 1 when the atmosphere draws the sky. - sky_sun: [f32; 4], - /// x: vanilla's sky fog end; z: how overcast the sky is (rain: 0 clear, 1 vanilla's colours). - sky_extra: [f32; 4], - /// Vanilla's sunrise colour fan (rgb, alpha), taken out of the sky before the atmosphere is put in. - sunrise: [f32; 4], - /// x: the cloud slab's base height relative to the camera; y: its thickness; z: 1 when the - /// volumetric clouds are drawn; w: seconds (the wind). - clouds: [f32; 4], - /// xy: the camera's x and z in the world modulo 65536; z: extra coverage (rain); w: 1 when the - /// clouds' history is usable. - cloud_cam: [f32; 4], - /// xyz: the direction the clouds are lit from (the sun, or the moon at night). - cloud_dir: [f32; 4], - /// rgb: the colour of that light at the clouds; w: its strength. - cloud_sun: [f32; 4], - /// x: 1 when the volumetric fog is drawn; y: the camera's height in the world; z: the morning mist. - vfog: [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, - /// The same frame's matrix as it was drawn, jitter included. History kept on the jittered - /// pixel grid (`fs_taa`, scale 1) is looked up with this; `fs_taau` resolves the history on the - /// unjittered output grid and uses `prev_view_proj`. - pub prev_view_proj_jittered: 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, - /// Vanilla's sunrise fan colour and its sky fog end (to subtract vanilla's sky from the world). - pub sunrise: [f32; 4], - pub sky_fog_end: f32, - /// The volumetric clouds are drawn (vanilla's option is on, in the Overworld). - pub clouds: bool, - /// The camera's world position, x and z modulo 65536 (precision), and y; seconds of game time. - pub camera_world: [f32; 3], - pub seconds: f32, -} - -/// 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, - resolution: vec4, - params: vec4, - cascades: array, 2>, - sun: vec4, - sun_color: vec4, - fog_color: vec4, - fog: vec4, - ambient: vec4, - shadow: vec4, - prev_view_proj: mat4x4, - taa: vec4, - taa_params: vec4, - view_proj: mat4x4, - water: vec4, - sky_color: vec4, - sky_sun: vec4, - sky_extra: vec4, - sunrise: vec4, - clouds: vec4, - cloud_cam: vec4, - cloud_dir: vec4, - cloud_sun: vec4, - vfog: vec4, -} -struct FullOut { - @builtin(position) position: vec4, - @location(0) uv: vec2, -} -@vertex -fn vs_full(@builtin(vertex_index) i: u32) -> FullOut { - let uv = vec2(f32((i << 1u) & 2u), f32(i & 2u)); - var out: FullOut; - out.position = vec4(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, - color: vec4, -} -@group(0) @binding(0) var frame: HdFrame; -@group(0) @binding(1) var scene_color: texture_2d; -@group(0) @binding(2) var scene_depth: texture_depth_2d; -@group(0) @binding(3) var albedo_tex: texture_2d; -@group(0) @binding(4) var normal_tex: texture_2d; -@group(0) @binding(5) var gbuffer_depth: texture_depth_2d; -@group(0) @binding(6) var lights: array; -@group(0) @binding(7) var light_tex: texture_2d; -@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; -@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 tiles: array; -// 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; -// The water pass's depth: the nearest water surface (0 where there is none). -@group(0) @binding(14) var water_depth: texture_depth_2d; -//SKY15 -// The volumetric fog (half resolution: light in rgb, transmittance in a), the distance it was marched -// to, the volumetric clouds (half resolution: light, transmittance) and the clouds' shadow map. -@group(0) @binding(16) var fog_tex: texture_2d; -@group(0) @binding(17) var fog_dist_tex: texture_2d; -@group(0) @binding(18) var cloud_tex: texture_2d; -@group(0) @binding(19) var cloud_shadow_tex: texture_2d; -const CLOUD_SHADOW_R: f32 = 1200.0; -// The pixel being lit, for the shadow filter's noise. -var frag_px: vec2; - -// 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, dist: f32) -> f32 { - let size = vec2(textureDimensions(ao_tex)); - let f = vec2(px) * 0.5; - let base = vec2(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(i, j), vec2(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(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 { - let p = px + vec2(5.588238 * frame.params.w); - return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); -} - -// Where a camera-relative point falls in cascade c: uv and depth. -fn cascade_at(p: vec3, c: i32) -> vec3 { - let s = frame.cascades[c] * vec4(p, 1.0); - return vec3(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, n: vec3) -> f32 { - return shadow_taps(p, n, 1); -} - -// A point of a disc of radius 1 (Vogel's spiral), turned by `angle`. -fn vogel(i: i32, count: i32, angle: f32) -> vec2 { - let r = sqrt((f32(i) + 0.5) / f32(count)); - let a = f32(i) * 2.39996323 + angle; - return vec2(cos(a), sin(a)) * r; -} - -// The near cascade's soft shadow: a blocker search sets the penumbra's width (wider the farther -// the shadow's caster is above the receiver), then a ring of taps turned by a per-pixel noise -// filters it; the temporal pass averages the noise. `s`: the point in the cascade (uv, depth), -// `texel`: the cascade's texel in blocks. -fn soft_shadow(s: vec3, texel: f32) -> f32 { - let angle = ign(frag_px) * 6.2831853; - var blocker = 0.0; - var found = 0.0; - for (var i = 0; i < 8; i++) { - let o = vogel(i, 8, angle) * (6.0 / 2048.0); - let q = clamp(vec2((s.xy + o) * 2048.0), vec2(0), vec2(2047)); - let z = textureLoad(shadow_map, q, 0, 0); - if z < s.z - 0.0006 { - blocker += z; - found += 1.0; - } - } - if found < 0.5 { return 1.0; } - // The caster's height above the receiver, in blocks (the cascade's depth spans 799 blocks). - let height = (s.z - blocker / found) * 799.0; - let radius = clamp(height * 0.18 / texel, 1.6, 8.0); - var lit = 0.0; - for (var i = 0; i < 12; i++) { - let o = vogel(i, 12, angle + 1.7) * (radius / 2048.0); - lit += textureSampleCompareLevel(shadow_map, shadow_sampler, s.xy + o, 0, s.z - 0.0005 - 0.00005 * radius); - } - return lit / 12.0; -} - -// `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, n: vec3, 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(0.0)) || any(s.xy > vec2(1.0)) || s.z > 1.0 { return 1.0; } - var lit = 0.0; - let fade = clamp((frame.shadow.z - dist) / 16.0, 0.0, 1.0); - if r == 1 && c == 0 { - return mix(1.0, soft_shadow(s, texel), fade); - } - 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(x), f32(y)) * step, c, s.z - 0.0005); - } - } - 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 { - let s = cascade_at(p, 1); - if any(s.xy < vec2(0.0)) || any(s.xy > vec2(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); -} - -// The share of the sunlight the clouds let through at a camera-relative point: the shadow map -// holds, for the sun's way down through the slab from a point of its base, the optical depth -// (Photon's cloud shadow map, as a lookup rather than a pass). -fn cloud_shadow(p: vec3) -> f32 { - if frame.clouds.z < 0.5 { return 1.0; } - let l = frame.cloud_dir.xyz; - if l.y < 0.1 { return 1.0; } - let t = (frame.clouds.x - p.y) / l.y; - if t <= 0.0 { return 1.0; } - let q = p.xz + l.xz * t; - let uv = q / (2.0 * CLOUD_SHADOW_R) + vec2(0.5); - if any(uv < vec2(0.0)) || any(uv > vec2(1.0)) { return 1.0; } - let od = textureSampleLevel(cloud_shadow_tex, linear, uv, 0.0).r; - // Fade out as the sun gets low (the shadow then falls far from the cloud). - let fade = smoothstep(0.1, 0.25, l.y); - return mix(1.0, mix(1.0, exp(-od * 0.9), 0.9), fade); -} - -// The volumetric fog at a full-resolution pixel `dist` away: the four nearest half-resolution -// texels weighted by closeness and by how near their march's length is (so it does not bleed over edges). -fn fog_at(px: vec2, dist: f32) -> vec4 { - let size = vec2(textureDimensions(fog_tex)); - let f = vec2(px) * 0.5 - vec2(0.25); - let base = vec2(floor(f)); - let t = f - floor(f); - var sum = vec4(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(i, j), vec2(0), size - 1); - let s = textureLoad(fog_tex, q, 0); - let sd = textureLoad(fog_dist_tex, q, 0).x; - let bw = select(1.0 - t.x, t.x, i == 1) * select(1.0 - t.y, t.y, j == 1); - let dz = (sd - dist) / (0.06 * dist + 0.4); - let w = bw / (1.0 + dz * dz * dz * dz); - sum += s * w; - total += w; - } - } - if total < 0.0001 { - return textureLoad(fog_tex, clamp(px / 2, vec2(0), size - 1), 0); - } - return sum / total; -} - -struct LightOut { - // The lit colour; alpha 0.5 marks water (the floor under it, lit without any air), 0.6 an - // object in front of the water (the scene as drawn). - @location(0) lit: vec4, - // Water: the air between the camera and the surface (scattered light, transmittance); - // in front of the water: the floor lit (rgb); else nothing. - @location(1) air: vec4, -} - -// An opaque surface lit: the ambient, the sun and the mods' lights over its albedo. -fn shade_surface(px: vec2, p: vec3, water: bool) -> vec3 { - let sun = frame.sun.xyz; - let sun_on = frame.sun.w; - let atmosphere = frame.sky_sun.w > 0.5; - 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 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(lm.y, lm.x) * (15.0 / 16.0) + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0).rgb; - let block = textureSampleLevel(lightmap, linear, vec2(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)) * cloud_shadow(p); } 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); - // The sky's light is bluish from above and carries the horizon's colour from the sides; - // faces turned up take more of it than the ones turned down. - var sky_tint = vec3(1.0); - if atmosphere { - let reach = smoothstep(0.25, 0.9, lm.x); - let up = clamp(n.y * 0.5 + 0.5, 0.0, 1.0); - let shape = mix(0.66, 1.1, smoothstep(0.1, 1.0, up)); - let hue = mix(vec3(1.0), sky_light_tint(n), 0.4 * (1.0 - 0.5 * frame.sun_color.a)); - sky_tint = mix(vec3(1.0), hue * shape, reach); - } - var light = max(base * sky_tint * 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; - } - return albedo.rgb * light + albedo.rgb * albedo.a * 1.5; -} - -@fragment -fn fs_light(in: FullOut) -> LightOut { - let px = vec2(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 over the opaque world (or over nothing): the water composite lays the surface over - // the floor, which is lit here with no air. Something translucent in front of the water - // (`front`: nearer than its surface) keeps the scene as drawn; the floor goes beside it. - var wd = 0.0; - var water_here = false; - if frame.water.x > 0.5 { - wd = textureLoad(water_depth, px, 0); - water_here = wd > 0.0 && (g <= 0.0 || wd >= g); - } - let front = water_here && g > 0.0 && d - wd > d * 0.002; - let water = water_here && !front; - let has_floor = water && g > 0.0; - let dd = select(d, g, has_floor); - let ndc = vec4(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); - // Where the air ends: the water's surface over water, else the pixel itself. - var ps = p; - if water { - let hf = frame.inverse_view_proj * vec4(in.uv.x * 2.0 - 1.0, 1.0 - in.uv.y * 2.0, max(wd, 0.000001), 1.0); - ps = hf.xyz / hf.w; - } - let view_s = normalize(ps); - 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 halo_start = tiles[tile + 2u]; - let halo_all = tiles[tile + 3u] == 0xffffffffu; - let halo_count = select(tiles[tile + 3u], count, halo_all); - frag_px = in.position.xy; - let atmosphere = frame.sky_sun.w > 0.5; - var c = scene; - // The sky: the atmosphere's, with what the world drew over vanilla's plain sky (sun, moon, - // stars, clouds) kept on top. - if d <= 0.0 && atmosphere { - var kept = max(scene - vanilla_sky(view), vec3(0.0)); - var sky = atmosphere_sky(view); - // The sun: vanilla's square sprite is taken out and a round disc with a soft haze round - // it (warm, strongest low) is drawn in its place. - let toward = dot(view, frame.sky_sun.xyz); - kept *= 1.0 - smoothstep(0.965, 0.975, toward); - let clear = 1.0 - frame.sky_extra.z; - let shine = smoothstep(-0.04, 0.02, frame.sky_sun.y) * clear; - let glow = max(toward, 0.0); - let angle = acos(clamp(toward, -1.0, 1.0)); - sky += frame.sun_color.rgb * shine * (pow(glow, 24.0) * 0.07 + pow(glow, 400.0) * 0.4 + 6.0 * (1.0 - smoothstep(0.016, 0.022, angle))); - c = sky + kept; - // The volumetric clouds over the sky and the sun. - if frame.clouds.z > 0.5 { - let cl = textureSampleLevel(cloud_tex, linear, in.uv, 0.0); - c = c * cl.a + cl.rgb; - } - } - // (Vanilla's clouds, when the volumetric ones are off, take the low sun's colour in their own - // pass: `vanilla_cloud_tint`, applied to their colour on the CPU.) - let surface = has_floor || (!water_here && d > 0.0 && abs(d - g) <= max(d, g) * 0.002); - if surface { - c = shade_surface(px, p, water); - // Vanilla's fog over it again (the water composite does it at the surface). - if !water { - 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)); - let haze = haze_colour(view); - c = mix(c, haze, f * frame.fog_color.a); - // Aerial perspective: far things take the horizon's colour a little before the fog does. - if atmosphere && frame.fog.x > 1.0e6 { - c = mix(c, haze, (1.0 - exp(-sph / 700.0)) * 0.5); - } - } - } - // What lies behind a translucent thing in front of the water: the floor, lit. - var floor_lit = vec3(0.0); - if front { - let hg = frame.inverse_view_proj * vec4(in.uv.x * 2.0 - 1.0, 1.0 - in.uv.y * 2.0, max(g, 0.000001), 1.0); - floor_lit = shade_surface(px, hg.xyz / hg.w, true); - } - // The air between the camera and the pixel (the water's surface over water): the volumetric - // fog (what it hides, what it scatters), the sun's rays between the shadows, and the halos - // round the mods' lights. Over water they go to the composite, which lays them over the - // finished water; elsewhere over the pixel here. - var air_t = 1.0; - var air_s = vec3(0.0); - let far = select(min(length(ps), frame.shadow.z), frame.shadow.z, d <= 0.0); - let density = frame.ambient.z; - let volumetric = frame.vfog.x > 0.5 && atmosphere; - if volumetric { - var fog_len = 192.0; - if d > 0.0 { fog_len = min(length(ps), 192.0); } - let fg = fog_at(px, fog_len); - air_t = fg.a; - air_s = fg.rgb; - } - if !volumetric && 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_s * t); - } - // Henyey-Greenstein, forward scattering: brightest looking towards the sun. - let cos_t = dot(view_s, 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; - air_s += 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_s); - let hh = length(l.pos.xyz - view_s * t0) + 0.5; - if hh > l.pos.w * 0.5 { continue; } - let a0 = atan((0.0 - t0) / hh); - let a1 = atan((far - t0) / hh); - // Thicker air glows more round a light, but only so far: the mist at dusk and many fires - // at once would otherwise wash the picture out. - air_s += l.color.rgb * l.color.w * (a1 - a0) / hh * 0.004 * (0.3 + min(density * 300.0, 0.9)); - } - var out: LightOut; - if water { - out.lit = vec4(c, 0.5); - out.air = vec4(air_s, air_t); - } else { - out.lit = vec4(c * air_t + air_s, select(1.0, 0.6, front)); - out.air = vec4(floor_lit, 0.0); - } - return out; -} -"#; - -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 frame: HdFrame; -@group(0) @binding(1) var lit_tex: texture_2d; -@group(0) @binding(2) var gbuffer_depth: texture_depth_2d; -@group(0) @binding(3) var water_tint: texture_2d; -@group(0) @binding(4) var water_normal: texture_2d; -@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; -@group(0) @binding(9) var linear: sampler; -//SKY10 -// What the lighting left beside the lit world: over water the air in front of the surface (scattered -// light, transmittance), in front of the water the lit floor. -@group(0) @binding(11) var air_tex: texture_2d; - -fn ign(px: vec2) -> f32 { - let p = px + vec2(5.588238 * frame.params.w); - return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); -} - -// The camera-relative position of the screen point `uv` at depth z. -fn position_at(uv: vec2, z: f32) -> vec3 { - let h = frame.inverse_view_proj * vec4(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) -> vec3 { - let c = frame.view_proj * vec4(p, 1.0); - return vec3(c.x / c.w * 0.5 + 0.5, 0.5 - c.y / c.w * 0.5, c.w); -} - -fn on_screen(uv: vec2) -> bool { - return all(uv > vec2(0.0)) && all(uv < vec2(1.0)); -} - -fn texel(uv: vec2) -> vec2 { - return clamp(vec2(uv * frame.resolution.xy), vec2(0), vec2(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, 26>( - vec4(3.0, 1.0, 0.040, 0.3), - vec4(-2.0, 5.0, 0.045, 2.1), - vec4(7.0, 2.0, 0.040, 4.4), - vec4(-5.0, -9.0, 0.040, 1.2), - vec4(11.0, -4.0, 0.035, 5.6), - vec4(13.0, 10.0, 0.035, 3.3), - vec4(-17.0, 7.0, 0.030, 0.9), - vec4(9.0, 23.0, 0.030, 2.7), - vec4(-27.0, 19.0, 0.025, 4.9), - vec4(31.0, 30.0, 0.025, 1.8), - // Fine ripples (wavelengths of 0.7 to 3 blocks) for the many small sun sparkles: slopes small, - // faded out by distance and pixel size like the rest. - vec4(83.0, 41.0, 0.042, 0.4), - vec4(-97.0, 59.0, 0.042, 3.1), - vec4(71.0, -113.0, 0.042, 5.0), - vec4(131.0, 89.0, 0.040, 1.5), - vec4(-157.0, -103.0, 0.040, 4.2), - vec4(191.0, -67.0, 0.038, 2.4), - vec4(-223.0, 149.0, 0.038, 0.8), - vec4(101.0, 241.0, 0.036, 3.7), - vec4(-263.0, -181.0, 0.034, 5.5), - vec4(311.0, 127.0, 0.034, 2.0), - // Finer still (0.35 to 0.6 blocks): the small sparkles. - vec4(397.0, -263.0, 0.050, 1.1), - vec4(-467.0, 331.0, 0.050, 4.6), - vec4(521.0, 449.0, 0.045, 3.0), - vec4(-613.0, -199.0, 0.045, 5.9), - vec4(293.0, 577.0, 0.045, 0.2), - vec4(-701.0, 263.0, 0.040, 2.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, footprint: f32) -> vec2 { - var grad = vec2(0.0); - for (var i = 0; i < 26; 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.2 - 0.6, 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)); - } - // A little higher than the table's slopes. - return grad * 1.25; -} - -fn cascade_at(p: vec3, c: i32) -> vec3 { - let s = frame.cascades[c] * vec4(p, 1.0); - return vec3(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, n: vec3) -> 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(0.0)) || any(s.xy > vec2(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(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, vis: f32) -> vec3 { - var c = frame.fog_color.rgb; - if frame.sky_sun.w > 0.5 { - c = atmosphere_sky(r); - } else 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, r: vec3, jitter: f32) -> vec4 { - 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(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(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(colour, smoothstep(0.0, 0.08, edge)); - } - } - } - near = s; - } - return vec4(0.0); -} - -// The sun's glint on the waves (GGX, a rough lobe so it glitters instead of aliasing). -fn glint(n: vec3, v: vec3, l: vec3) -> f32 { - let h = normalize(l + v); - let a = 0.07; - 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 { - let px = vec2(in.position.xy); - let base = textureLoad(lit_tex, px, 0); - if base.a > 0.75 { return vec4(base.rgb, 1.0); } - // Alpha 0.6: something translucent stands in front of the water here (base is the scene). - let front = base.a > 0.55; - let aux = textureLoad(air_tex, px, 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(-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(nt.a, tint.a); - let sky_reach = smoothstep(0.35, 0.95, levels.x); - var ambient = textureSampleLevel(lightmap, linear, clamp(vec2(levels.y, levels.x) * (15.0 / 16.0) + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0).rgb; - if frame.sky_sun.w > 0.5 { - ambient *= mix(vec3(1.0), sky_light_tint(vec3(0.0, 1.0, 0.0)), 0.7 * sky_reach); - } - let block = textureSampleLevel(lightmap, linear, vec2(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(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). Not where - // something translucent is in front of the water, nor onto texels that hold such a thing. - let has_floor = g > 0.0; - var uv_floor = in.uv; - var floor_z = g; - if has_floor && !front { - 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); - 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); - // The four texels the filter blends: none may be a pixel with a translucent thing - // in front of the water. - let marks = textureGather(3, lit_tex, linear, moved.xy); - let tainted = any((marks > vec4(0.55)) & (marks < vec4(0.75))); - // Only what lies behind the water: not the bank or an entity in front of it. - if z > 0.0 && z <= wd && !tainted { - uv_floor = moved.xy; - floor_z = z; - } - } - } - var thickness = 48.0; - if has_floor { - thickness = clamp(length(position_at(uv_floor, floor_z)) - dist, 0.0, 48.0); - } - var behind = textureSampleLevel(lit_tex, linear, uv_floor, 0.0).rgb; - if front { behind = aux.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(0.03), vec3(1.0)); - let colour = mix(vec3(dot(biome, vec3(0.333))), biome, 0.85) * vec3(0.78, 0.86, 0.95); - // The colours the water takes up fastest are the ones it has the least of. - let absorb = exp(-(vec3(1.0) - colour) * 0.6 * (thickness + 0.3)); - let refracted = behind * absorb + colour * volume_light * mix(0.65, 0.3, frame.sun_color.a) * (vec3(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(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)); - let haze = haze_colour(-v); - c = mix(c, haze, f * frame.fog_color.a); - if frame.sky_sun.w > 0.5 && frame.fog.x > 1.0e6 { - c = mix(c, haze, (1.0 - exp(-dist / 700.0)) * 0.5); - } - if front { - // The scene as drawn, with the water's change to the floor laid under the translucent thing. - c = base.rgb + (c - aux.rgb) * 0.7; - } else { - // The air between the camera and the surface: volumetric fog, rays, halos. - c = c * aux.a + aux.rgb; - } - return vec4(max(c, vec3(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 frame: HdFrame; -@group(0) @binding(1) var depth_tex: texture_depth_2d; -@group(0) @binding(2) var normal_tex: texture_2d; - -// Interleaved gradient noise, shifted per frame (params.w) and per use. -fn noise(px: vec2, shift: vec2) -> f32 { - let p = px + shift + vec2(5.588238 * frame.params.w); - return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); -} - -// The camera-relative position of a (continuous) full-resolution pixel at depth z. -fn position_at(px: vec2, z: f32) -> vec3 { - let uv = px * frame.resolution.zw; - let h = frame.inverse_view_proj * vec4(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 { - let size = vec2(textureDimensions(depth_tex)); - let ic = min(vec2(in.position.xy) * 2, size - 1); - let z = textureLoad(depth_tex, ic, 0); - if z <= 0.0 { return vec2(1.0, 0.0); } - let nrm = textureLoad(normal_tex, ic, 0).xyz; - let c = vec2(ic) + 0.5; - let p = position_at(c, z); - let dist = length(p); - if dot(nrm, nrm) < 0.01 { return vec2(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(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(1.0, dist); } - let radius = reach * per_px; - let rot = noise(in.position.xy, vec2(0.0)); - let jitter = noise(in.position.xy, vec2(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(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(floor(c + d2 * (r * sg))); - if any(ip < vec2(0)) || any(ip >= size) { continue; } - let sz = textureLoad(depth_tex, ip, 0); - if sz <= 0.0 { continue; } - let to = position_at(vec2(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(mix(1.0, ao, 1.0 - smoothstep(40.0, 96.0, dist)), dist); -} -"#; - -const AO_BLUR: &str = r#" -@group(0) @binding(0) var frame: HdFrame; -@group(0) @binding(1) var raw_ao: texture_2d; - -// 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 { - let size = vec2(textureDimensions(raw_ao)); - let ip = vec2(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(x, y); - if any(q < vec2(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(sum / max(total, 0.0001), centre.y); -} -"#; - -const BLOOM: &str = r#" -@group(0) @binding(0) var frame: HdFrame; -@group(0) @binding(1) var source: texture_2d; -@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 { - 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(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 { - let t = 1.0 / vec2(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(o, 1.0); -} -// A 3×3 tent, added onto the bigger level. -@fragment -fn fs_up(in: FullOut) -> @location(0) vec4 { - let t = 1.0 / vec2(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(o / 16.0, 1.0); -} -"#; - -const TONEMAP: &str = r#" -@group(0) @binding(0) var frame: HdFrame; -@group(0) @binding(1) var hdr: texture_2d; -@group(0) @binding(2) var bloom: texture_2d; -@group(0) @binding(3) var linear: sampler; - -@fragment -fn fs_tonemap(in: FullOut) -> @location(0) vec4 { - 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(textureDimensions(hdr)); - let n0 = textureSampleLevel(hdr, linear, in.uv + vec2(t.x, 0.0), 0.0).rgb; - let n1 = textureSampleLevel(hdr, linear, in.uv - vec2(t.x, 0.0), 0.0).rgb; - let n2 = textureSampleLevel(hdr, linear, in.uv + vec2(0.0, t.y), 0.0).rgb; - let n3 = textureSampleLevel(hdr, linear, in.uv - vec2(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(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(0.2126, 0.7152, 0.0722)); - c = max(mix(vec3(luma), c, 1.12), vec3(0.0)); - c = mix(c, c * c * (3.0 - 2.0 * c), 0.18); - return vec4(c, 1.0); -} -"#; - -const TAA: &str = r#" -struct TaaOut { - @location(0) color: vec4, - @location(1) history: vec4, -} -@group(0) @binding(0) var frame: HdFrame; -@group(0) @binding(1) var source: texture_2d; -@group(0) @binding(2) var depth_tex: texture_depth_2d; -@group(0) @binding(3) var history: texture_2d; -@group(0) @binding(4) var linear: sampler; - -fn to_ycocg(c: vec3) -> vec3 { - return vec3(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) -> vec3 { - let t = c.x - c.z; - return vec3(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) -> vec3 { - return c / (1.0 + max(c.r, max(c.g, c.b))); -} -fn unsquash(c: vec3) -> vec3 { - 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) -> vec3 { - let size = vec2(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(t12.x, t0.y), 0.0).rgb * (w12.x * w0.y); - var total = w12.x * w0.y; - sum += textureSampleLevel(history, linear, vec2(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(t3.x, t12.y), 0.0).rgb * (w3.x * w12.y); - total += w3.x * w12.y; - sum += textureSampleLevel(history, linear, vec2(t12.x, t3.y), 0.0).rgb * (w12.x * w3.y); - total += w12.x * w3.y; - return max(sum / total, vec3(0.0)); -} - -// Pulls `p` towards the box's centre until it is inside. -fn clip_to_box(lo: vec3, hi: vec3, p: vec3) -> vec3 { - let centre = (lo + hi) * 0.5; - let ext = max((hi - lo) * 0.5, vec3(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(textureDimensions(source)); - let px = vec2(in.position.xy); - let d = textureLoad(depth_tex, px, 0); - var sum = vec3(0.0); - var sum2 = vec3(0.0); - var lo = vec3(1.0e9); - var hi = vec3(-1.0e9); - var centre = vec3(0.0); - for (var y = -1; y <= 1; y++) { - for (var x = -1; x <= 1; x++) { - let q = clamp(px + vec2(x, y), vec2(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(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(select(p + frame.taa.xyz, p, sky), 1.0); - if prev.w > 0.0 { - let pn = prev.xy / prev.w; - let uv = vec2(pn.x * 0.5 + 0.5, 0.5 - pn.y * 0.5); - if all(uv > vec2(0.0)) && all(uv < vec2(1.0)) { - let hp = clamp(vec2(uv * vec2(size)), vec2(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(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(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(color, 1.0); - out.history = vec4(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(textureDimensions(source)); - let lowi = vec2(low); - let high = vec2(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(floor(t + 0.5)); - var sum = vec3(0.0); - var sum2 = vec3(0.0); - var lo = vec3(1.0e9); - var hi = vec3(-1.0e9); - var weighted = vec3(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(x, y), vec2(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(base + vec2(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(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(x, y), vec2(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(jit.x * 2.0 / low.x, -jit.y * 2.0 / low.y); - let ndc = vec4(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(select(p + frame.taa.xyz, p, sky), 1.0); - if prev.w > 0.0 { - let pn = prev.xy / prev.w; - let uv = vec2(pn.x * 0.5 + 0.5, 0.5 - pn.y * 0.5); - if all(uv > vec2(0.0)) && all(uv < vec2(1.0)) { - let hp = clamp(vec2(uv * high), vec2(0), vec2(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(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(color, 1.0); - out.history = vec4(color, dist); - return out; -} -"#; - -pub(super) struct Target { - pub(super) view: wgpu::TextureView, -} - -pub(super) 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 = 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 = 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 { - static SCALE: std::sync::OnceLock> = 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, - 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, - /// The lighting's second target: the air over water, the floor beside translucent things. - air: 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, - /// The volumetric clouds and the fog run this frame. - clouds_active: bool, - fog_active: bool, - /// The sky-view texture (see `hd_sky`), the pass that marches it and its bind group. - sky_lut: wgpu::TextureView, - sky_pipeline: wgpu::RenderPipeline, - sky_group: wgpu::BindGroup, - /// The sun's height the sky-view texture was marched for (it depends on nothing else), and - /// whether this frame's sun has moved enough to march it again. - sky_drawn_for: f32, - sky_stale: 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, - /// 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)>; 2], - /// The volumetric clouds and fog (see `hd_volumes`). - volumes: HdVolumes, - 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, - up_groups: Vec, - 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>, - tile_words: Vec, - 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, - ao_blur_group: Option, - /// GPU time of the HD passes while diagnostics ask for it (`set_timing`). - timing: Option, - /// 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::()) 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>, - words: &mut Vec, -) { - 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, - name: &str, -) -> Option> { - 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) -} - -/// The shader's source: the common part, then the body with the sky-reading functions where it -/// has a marker (`//SKY15`: the sky-view texture is binding 15, `//SKY10`: binding 10). -pub(super) fn assemble(body: &str) -> String { - let mut body = body.to_owned(); - // Highest number first: `//SKY1` must not eat the start of `//SKY15`. - for binding in (0..32).rev() { - body = body.replace( - &format!("//SKY{binding}"), - &hd_sky::SKY_FUNCS.replace("SKYBIND", &binding.to_string()), - ); - } - format!("{COMMON}{body}") -} - -pub(super) fn module(device: &wgpu::Device, label: &str, body: &str) -> wgpu::ShaderModule { - // Development: with `HORIZON_HD_SHADER_DIR` set, a shader's body is read from - // `/