diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 285bec65b..e117526de 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -37,6 +37,8 @@ const HELP: &[&str] = &[ "options [PAGE] open the options (video sound controls keybinds mouse chat accessibility language font packs mods graphics graphics-advanced)", "stats [reset|raw] frame-time summary since the last reset (raw: every frame/cpu/gpu time too)", "model-instancing on|off GPU instancing of the mod models' mass group (#147 diagnostic; off = per-vertex fallback)", + "smoke-skip on|off the HD smoke's empty-brick skip in the fog (diagnostic; off = every step marched)", + "light-tiles on|off the HD light tiles (diagnostic; off = every pixel takes every light)", "dlss [on|off|status] NVIDIA DLSS upscaling (default on where supported; off = native TAAU live; on after an off start applies at the next launch)", "bench SECONDS reset stats, wait, then reply with the summary", "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]] fly the camera along a line at constant speed, then reply with the frame summary (raw: every frame time too)", @@ -784,6 +786,28 @@ impl Game<'_> { horizon_client::gfx::set_model_instancing(on); Ok(Some(json!({ "model_instancing": on }))) } + "smoke-skip" => { + // AirDef fork: the diagnostic toggle of the HD smoke's empty-brick skip — + // both ways on one recording, no restart. + let on = match arg(1)? { + "on" => true, + "off" => false, + other => return Err(format!("smoke-skip needs on|off, not {other}").into()), + }; + horizon_client::gfx::set_smoke_skip(on); + Ok(Some(json!({ "smoke_skip": on }))) + } + "light-tiles" => { + // AirDef fork: the diagnostic toggle of the HD light tiles — both ways on one + // recording, no restart. + let on = match arg(1)? { + "on" => true, + "off" => false, + other => return Err(format!("light-tiles needs on|off, not {other}").into()), + }; + horizon_client::gfx::set_light_tiles(on); + Ok(Some(json!({ "light_tiles": on }))) + } "dlss" => { // AirDef fork: the player's DLSS toggle, persisted in // horizon-graphics.txt. Off evaluates the native TAAU from diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 86b7f8e15..beb0d2f10 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -67,6 +67,18 @@ pub fn set_model_instancing(on: bool) { MODEL_INSTANCING.store(on, std::sync::atomic::Ordering::Relaxed); } +/// AirDef fork: the diagnostic runtime toggle of the HD smoke's empty-brick skip in the fog +/// (`smoke-skip` control command): off marches every step, as before the skip. +pub fn set_smoke_skip(on: bool) { + hd::set_skip(on); +} + +/// AirDef fork: the diagnostic runtime toggle of the light tiles (`light-tiles` control command): +/// off makes every pixel take every light, the shader's whole-list path. +pub fn set_light_tiles(on: bool) { + hd::set_untiled(!on); +} + /// AirDef fork: the player's DLSS request, live. On by default; the startup /// decision (`horizon-graphics.txt`'s `dlss` and `HORIZON_DLSS`) seeds it /// once at renderer startup, on every build. Off evaluates the diff --git a/crates/horizon-client/src/gfx/hd/fog.wgsl b/crates/horizon-client/src/gfx/hd/fog.wgsl index 40a81e540..9d80d04aa 100644 --- a/crates/horizon-client/src/gfx/hd/fog.wgsl +++ b/crates/horizon-client/src/gfx/hd/fog.wgsl @@ -13,6 +13,10 @@ @group(0) @binding(9) var ground_tex: texture_2d; // The far smoke grid (12-block cells). @group(0) @binding(10) var smoke_far_tex: texture_2d; +// The bricks-occupied bits of the near and far cascades (a bit per brick, set when its forward +// 2x2x2 neighbourhood holds segments): the fog skips reads that reach only empty bricks. +@group(0) @binding(11) var smoke_occupied_near: array; +@group(0) @binding(12) var smoke_occupied_far: array; //SPOT @@ -116,6 +120,20 @@ fn smoke_cell(far: bool, p: vec3) -> vec4 { return smoke_raw(smoke_tex, linear, p, frame.smoke_min.xyz, frame.smoke.y); } +// Whether the point's brick holds no smoke: the grid fills a brick's cells only from its own +// segments and the trilinear read reaches one brick forward, so a clear bit means the read is +// exactly zero. The brick is the cell coordinate's eighth, clamped to the grid (outside, the sample +// is zero anyway). +fn smoke_brick_empty(far: bool, p: vec3) -> bool { + let cell = select(frame.smoke.y, frame.smoke_far.w, far); + let lo = select(frame.smoke_min.xyz, frame.smoke_far.xyz, far); + let g = (p - lo) / cell - vec3(0.5); + let brick = clamp(vec3(floor(g / 8.0)), vec3(0), vec3(15, 7, 15)); + let b = u32(brick.x + 16 * (brick.z + 16 * brick.y)); + let word = select(smoke_occupied_near[b / 32u], smoke_occupied_far[b / 32u], far); + return (word & (1u << (b % 32u))) == 0u; +} + // The smoke of one cascade between the camera and `len` along `dir`: light and transmittance (a). // The near cascade weighs a point by `smoke_near_cover`, the far one by what is left, so the seam // carries the same smoke either way. @@ -143,6 +161,24 @@ fn march_smoke(dir: vec3, len: f32, jitter: f32, haze: vec3, cos_v: f3 for (var i = 0; i < n; i++) { if trans < 0.02 { break; } let pos = dir * (t_in + (f32(i) + jitter) * ds); + // An empty brick reads exactly zero, so skip the steps that stay inside it (bit-identical to + // marching them: they would take the g.x < 0.004 path and change nothing). + let gp = (pos - lo) / cell - vec3(0.5); + let brick = clamp(vec3(floor(gp / 8.0)), vec3(0), vec3(15, 7, 15)); + let b = u32(brick.x + 16 * (brick.z + 16 * brick.y)); + let word = select(smoke_occupied_near[b / 32u], smoke_occupied_far[b / 32u], far); + if (word & (1u << (b % 32u))) == 0u { + // Distance along the ray to the brick's exit face (the next face per axis; a zero + // direction has no exit on that axis). Bias the count towards skipping less, never more. + let bmin = lo + (vec3(brick) * 8.0 + vec3(0.5)) * cell; + let bmax = bmin + vec3(8.0 * cell); + let next = select(bmin, bmax, dir > vec3(0.0)); + var face_dist = abs(next - pos) / max(abs(dir), vec3(1e-5)); + face_dist = select(face_dist, vec3(1e9), abs(dir) < vec3(1e-5)); + let remaining = min(min(face_dist.x, face_dist.y), face_dist.z); + i += max(i32(ceil(remaining / ds - 1.0 - 1e-3)), 0); + continue; + } let cover = select(0.0, smoke_near_cover(pos), near_on); let weight = select(cover, 1.0 - cover, far); if weight < 0.003 { continue; } @@ -232,7 +268,10 @@ fn fs_fog(in: FullOut) -> FogOut { let ds = len * (f1 - f0); let pos = dir * (t + 0.5 * ds); var sigma = fog_sigma(pos); - if frame.smoke.x > 0.5 { sigma *= 1.0 - smoke_at(smoke_tex, linear, pos).a; } + // The clear amount is zero in an empty brick too, so skip the read there (same bits). + if frame.smoke.x > 0.5 && !smoke_brick_empty(false, pos) { + sigma *= 1.0 - smoke_at(smoke_tex, linear, pos).a; + } let a = 1.0 - exp(-sigma * ds); var vis = 1.0; if sun_on > 0.0 { vis = sun_visible(pos); } diff --git a/crates/horizon-client/src/gfx/hd/mod.rs b/crates/horizon-client/src/gfx/hd/mod.rs index 407d55ace..816cc1582 100644 --- a/crates/horizon-client/src/gfx/hd/mod.rs +++ b/crates/horizon-client/src/gfx/hd/mod.rs @@ -110,7 +110,8 @@ pub use frame::{HdLight, HdScene, HdSettings, HdSpot, MAX_SPOTS, light_of, vanil pub use gbuffer::{ALBEDO, LIGHT_LEVELS, MOTION, NORMAL}; pub use materials::{Table as MaterialTable, table as material_table, wind_enabled, wind_seconds}; pub use shadows::{CASCADES, SHADOW_TINT, cascades, color_shadows_enabled}; -pub use smoke::{HdSmoke, smoke_enabled, smoke_possible}; +pub use smoke::{HdSmoke, set_skip, smoke_enabled, smoke_possible}; +pub use tiles::set_untiled; pub use taa::{film_quality, jitter, jitter_count, scale_override, set_film_quality, taa_enabled}; pub use volumes::clouds_enabled; diff --git a/crates/horizon-client/src/gfx/hd/smoke.rs b/crates/horizon-client/src/gfx/hd/smoke.rs index 34f3fd77c..39a733528 100644 --- a/crates/horizon-client/src/gfx/hd/smoke.rs +++ b/crates/horizon-client/src/gfx/hd/smoke.rs @@ -64,6 +64,20 @@ pub fn smoke_enabled() -> bool { *ON.get_or_init(|| std::env::var("HORIZON_HD_SMOKE").map_or(true, |v| v != "0")) } +/// The fog's empty-brick skip is on unless `HORIZON_HD_SMOKE_SKIP=0` (diagnostics only: off +/// makes every brick count as occupied, the march as it was before the skip). The bench driver +/// flips it at runtime (`smoke-skip` control command) to compare both ways on one recording. +static SKIP: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + +pub fn skip_enabled() -> bool { + SKIP.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The diagnostic runtime toggle: off marches every step. +pub fn set_skip(on: bool) { + SKIP.store(on, std::sync::atomic::Ordering::Relaxed); +} + /// Whether the smoke can be drawn at all: its volume is ray-marched in the fog pass, so it needs /// the volumetric fog as well as `HORIZON_HD_SMOKE`. This is what the mods are told. pub fn smoke_possible() -> bool { @@ -142,6 +156,11 @@ struct Cascade { atlas: wgpu::TextureView, segments: wgpu::Buffer, bricks: wgpu::Buffer, + /// A bit per brick: set when any brick of its forward 2x2x2 neighbourhood holds segments, so + /// the fog can skip a trilinear read that reaches only empty bricks (it reads one brick forward). + /// Stale bits are never read: a cascade with no kept segments has `count == 0`, the frame's smoke + /// flag is 0, and `march_smoke` is not called for it. + occupied: wgpu::Buffer, /// xyz: the grid's corner relative to the camera; w: the cell (for `fs_smoke_grid`). grid: wgpu::Buffer, group: wgpu::BindGroup, @@ -175,6 +194,8 @@ impl Cascade { max_segments * std::mem::size_of::(), ); let bricks = storage("HD smoke bricks", (BRICKS * 2 + MAX_INDICES) * 4); + // 64 words = one bit per brick (2048 bricks); read-only storage, as the fog layout binds it. + let occupied = storage("HD smoke bricks occupied", 64 * 4); let grid = device.create_buffer(&wgpu::BufferDescriptor { label: Some("HD smoke grid corner"), size: 16, @@ -211,6 +232,7 @@ impl Cascade { atlas, segments, bricks, + occupied, grid, group, count: 0, @@ -338,6 +360,9 @@ impl Cascade { if kept.is_empty() { return; } + // The fog's empty-brick skip reads these bits; only upload them with a valid brick upload. + // With the skip off every brick counts as occupied: nothing is skipped. + let occupied = if skip_enabled() { occupied_bits(&counts) } else { [u32::MAX; 64] }; let mut data = vec![0u32; BRICKS * 2 + total]; let mut start = 0u32; for (b, &c) in counts.iter().enumerate() { @@ -360,6 +385,7 @@ impl Cascade { self.bricks_cpu = data; queue.write_buffer(&self.segments, 0, bytemuck::cast_slice(&kept)); queue.write_buffer(&self.bricks, 0, bytemuck::cast_slice(&self.bricks_cpu)); + queue.write_buffer(&self.occupied, 0, bytemuck::cast_slice(&occupied)); self.count = kept.len(); } } @@ -379,6 +405,10 @@ pub struct Smoke { impl Smoke { pub fn new(device: &wgpu::Device, frame: &wgpu::Buffer) -> Self { + SKIP.store( + std::env::var("HORIZON_HD_SMOKE_SKIP").map_or(true, |v| v != "0"), + std::sync::atomic::Ordering::Relaxed, + ); let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("HD smoke grid"), entries: &entries(&SMOKE_GRID_BINDINGS), @@ -414,6 +444,12 @@ impl Smoke { } } + /// The bricks-occupied bits of the near and far cascades, for the fog's empty-brick skip. The + /// buffers are made once in `Cascade::new`, so their identity is stable across frames. + pub fn occupied(&self) -> (&wgpu::Buffer, &wgpu::Buffer) { + (&self.near.occupied, &self.far.occupied) + } + /// Bakes this frame's segments into both grids and uploads them; picks the lights that glow on /// the smoke. `clock` is the mod's clock in seconds. pub fn prepare( @@ -527,6 +563,46 @@ fn brick_index(x: u32, y: u32, z: u32) -> usize { (x + BRICKS_XZ * (z + BRICKS_XZ * y)) as usize } +/// One bit per brick: set when any brick of its forward 2x2x2 neighbourhood (B..B+1 per axis, +/// clamped to the grid) holds segments. The grid fills a brick's cells only from its own segments +/// and the trilinear read reaches one brick forward, so a clear bit means every channel of the read +/// is exactly zero. +fn occupied_bits(counts: &[u32]) -> [u32; 64] { + let mut bits = [0u32; 64]; + for y in 0..BRICKS_Y { + for z in 0..BRICKS_XZ { + for x in 0..BRICKS_XZ { + let mut any = false; + for dz in 0..2 { + for dy in 0..2 { + for dx in 0..2 { + let xx = (x + dx).min(BRICKS_XZ - 1); + let yy = (y + dy).min(BRICKS_Y - 1); + let zz = (z + dz).min(BRICKS_XZ - 1); + any |= counts[brick_index(xx, yy, zz)] > 0; + } + } + } + if any { + let b = brick_index(x, y, z); + bits[b / 32] |= 1u32 << (b % 32); + } + } + } + } + bits +} + +/// The documented twin of `march_smoke`'s skip arithmetic: how many following steps stay inside the +/// empty brick, given the distance `remaining` to its exit face and the step length `ds`. Steps sit +/// at multiples of `ds` from the current one, so the count is `ceil(remaining / ds - 1)`; the extra +/// `-1e-3` biases any rounding towards skipping LESS (a step left unskipped just reads zero), never +/// more. The shader writes `i32(ceil(remaining / ds - 1.0 - 1e-3))`. +#[cfg(test)] +fn steps_ahead(remaining: f32, ds: f32) -> i32 { + (remaining / ds - 1.0 - 1e-3).ceil() as i32 +} + /// A segment at its age: drifted with the wind, risen, grown, thinned, cooled; None once spent. fn bake(s: &HdSmoke, min_tube: f32) -> Option { let t = s.a[3]; @@ -628,4 +704,76 @@ mod tests { let b = bake(&s, MIN_TUBE).unwrap(); assert!(b.extra[3] > 0.5 && b.extra[2] >= 3.0); } + + /// A bit is set exactly when the brick's forward 2x2x2 neighbourhood holds a segment, including + /// the clamped far corner; the packing into 64 words round-trips. + #[test] + fn occupied_bits_dilate_the_forward_neighbourhood() { + let occ = |x: u32, y: u32, z: u32| { + (x * 7 + y * 13 + z * 5) % 11 == 0 || (x == 15 && y == 7 && z == 15) + }; + let mut counts = vec![0u32; BRICKS]; + for y in 0..BRICKS_Y { + for z in 0..BRICKS_XZ { + for x in 0..BRICKS_XZ { + if occ(x, y, z) { + counts[brick_index(x, y, z)] = 3; + } + } + } + } + let bits = occupied_bits(&counts); + for y in 0..BRICKS_Y { + for z in 0..BRICKS_XZ { + for x in 0..BRICKS_XZ { + let mut expect = false; + for dz in 0..2 { + for dy in 0..2 { + for dx in 0..2 { + expect |= occ( + (x + dx).min(BRICKS_XZ - 1), + (y + dy).min(BRICKS_Y - 1), + (z + dz).min(BRICKS_XZ - 1), + ); + } + } + } + let b = brick_index(x, y, z); + let got = bits[b / 32] & (1u32 << (b % 32)) != 0; + assert_eq!(got, expect, "brick {x},{y},{z}"); + } + } + } + } + + /// The skip never overshoots the brick's exit: every skipped step is below `t_exit`, and the + /// first kept step is at or above it less the bias margin (so a kept step may read zero, but a + /// skipped one never lands in an occupied brick). Deterministic pseudo-random rays. + #[test] + fn steps_ahead_stays_below_the_exit_face() { + // Whole multiples skip one fewer (the step on the face belongs to the next brick). + assert_eq!(steps_ahead(3.0 * 4.0, 4.0), 2); + assert_eq!(steps_ahead(0.5 * 4.0, 4.0), 0); + let mut seed = 0x1234_5678u32; + let mut rnd = || { + seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); + (seed >> 8) as f32 / (1u32 << 24) as f32 + }; + for _ in 0..2000 { + let ds = 1.0 + rnd() * 19.0; + let jitter = rnd(); + let t = rnd() * 800.0 + jitter * ds; + let remaining = rnd() * 60.0; + let t_exit = t + remaining; + let ahead = steps_ahead(remaining, ds).max(0); + for j in 1..=ahead { + assert!(t + j as f32 * ds < t_exit, "skipped step past the exit"); + } + let first_kept = t + (ahead + 1) as f32 * ds; + assert!( + first_kept >= t_exit - 1e-3 * ds - 1e-2, + "skipped too far: kept {first_kept}, exit {t_exit}" + ); + } + } } diff --git a/crates/horizon-client/src/gfx/hd/volumes.rs b/crates/horizon-client/src/gfx/hd/volumes.rs index fd88b9ece..def9b8261 100644 --- a/crates/horizon-client/src/gfx/hd/volumes.rs +++ b/crates/horizon-client/src/gfx/hd/volumes.rs @@ -27,7 +27,7 @@ use super::ground::Ground; use super::noise as hd_noise; use super::{ - DEPTH, FLOAT, Hd, SAMPLER, SHADOW_ARRAY, SHADOW_SAMPLER, UNFILTERED, UNIFORM, entries, + DEPTH, FLOAT, Hd, SAMPLER, SHADOW_ARRAY, SHADOW_SAMPLER, STORAGE, UNFILTERED, UNIFORM, entries, fullscreen, module, stamp, stamped_pass, target, }; @@ -131,8 +131,9 @@ pub(super) const CLOUD_BINDINGS: [wgpu::BindingType; 10] = [ pub(super) const CLOUD_SHADOW_BINDINGS: [wgpu::BindingType; 6] = [UNIFORM, D3, FLOAT, SAMPLER, SAMPLER, FLOAT]; /// `fs_fog`'s group 0: frame, the world's depth, the shadow cascades and their sampler, 3D noise, -/// repeating and clamped samplers, the sky texture. -pub(super) const FOG_BINDINGS: [wgpu::BindingType; 11] = [ +/// repeating and clamped samplers, the sky texture. The last two are the near and far cascades' +/// bricks-occupied bits, for the empty-brick skip. +pub(super) const FOG_BINDINGS: [wgpu::BindingType; 13] = [ UNIFORM, DEPTH, SHADOW_ARRAY, @@ -144,6 +145,8 @@ pub(super) const FOG_BINDINGS: [wgpu::BindingType; 11] = [ FLOAT, FLOAT, FLOAT, + STORAGE, + STORAGE, ]; impl HdVolumes { @@ -634,8 +637,11 @@ impl HdVolumes { sky_lut: &wgpu::TextureView, atlas: &wgpu::TextureView, far_atlas: &wgpu::TextureView, + near_occupied: &wgpu::Buffer, + far_occupied: &wgpu::Buffer, stamp: Option>, ) { + // The smoke atlases and occupied buffers are made once, so the depth-keyed cache stays valid. if self.fog_group.as_ref().is_none_or(|(v, _)| v != depth) { let layout = self.fog_layout.clone(); let ground = self.ground.view.clone(); @@ -661,6 +667,8 @@ impl HdVolumes { wgpu::BindingResource::TextureView(atlas), wgpu::BindingResource::TextureView(&ground), wgpu::BindingResource::TextureView(far_atlas), + wgpu::BindingResource::Buffer(near_occupied.as_entire_buffer_binding()), + wgpu::BindingResource::Buffer(far_occupied.as_entire_buffer_binding()), ], ); self.fog_group = Some((depth.clone(), group)); @@ -722,6 +730,7 @@ impl Hd { .draw(encoder, stamp(&mut self.timing, "hd smoke grid")); self.smoke .draw_far(encoder, stamp(&mut self.timing, "hd smoke grid far")); + let (near_occupied, far_occupied) = self.smoke.occupied(); self.volumes.draw_fog( device, encoder, @@ -731,6 +740,8 @@ impl Hd { &self.sky.lut, &self.smoke.atlas, &self.smoke.far_atlas, + near_occupied, + far_occupied, stamp(&mut self.timing, "hd fog"), ); }